sitepong 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdn/sitepong.min.js +5 -5
- package/dist/cdn/sitepong.min.js.map +1 -1
- package/dist/index.js +3879 -4315
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3818 -4315
- package/dist/index.mjs.map +1 -1
- package/dist/react/index.js +3928 -4374
- package/dist/react/index.js.map +1 -1
- package/dist/react/index.mjs +3831 -4337
- package/dist/react/index.mjs.map +1 -1
- package/dist/rn/index.d.ts.map +1 -1
- package/dist/rn/index.js +3 -2
- package/dist/rn/index.js.map +1 -1
- package/dist/rn/react/hooks.d.ts.map +1 -1
- package/dist/rn/react-native/index.d.ts +1 -1
- package/dist/rn/react-native/index.d.ts.map +1 -1
- package/dist/rn/react-native/index.js +2 -2
- package/dist/rn/react-native/index.js.map +1 -1
- package/dist/rn/react-native/provider.d.ts +7 -3
- package/dist/rn/react-native/provider.d.ts.map +1 -1
- package/dist/rn/react-native/provider.js +4 -4
- package/dist/rn/react-native/provider.js.map +1 -1
- package/dist/rn/react-native/push.d.ts +12 -0
- package/dist/rn/react-native/push.d.ts.map +1 -1
- package/dist/rn/react-native/push.js +35 -9
- package/dist/rn/react-native/push.js.map +1 -1
- package/package.json +1 -1
package/dist/cdn/sitepong.min.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var SitePong=(function(exports){'use strict';var ge=Object.defineProperty;var tn=Object.getOwnPropertyDescriptor;var nn=Object.getOwnPropertyNames;var rn=Object.prototype.hasOwnProperty;var h=(r,e)=>()=>(r&&(e=r(r=0)),e);var je=(r,e)=>{for(var t in e)ge(r,t,{get:e[t],enumerable:true});},on=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nn(e))!rn.call(r,i)&&i!==t&&ge(r,i,{get:()=>e[i],enumerable:!(n=tn(e,i))||n.enumerable});return r};var Qe=r=>on(ge({},"__esModule",{value:true}),r);function me(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return (r==="x"?e:e&3|8).toString(16)})}function E(){if(typeof window<"u"&&typeof localStorage<"u")try{let r=localStorage.getItem(Z);return r||(r=me(),localStorage.setItem(Z,r)),r}catch{return T||(T=me()),T}return T||(T=me()),T}function Ye(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(Z);}catch{}T=null;}function Je(r){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.setItem(Z,r);}catch{T=r;}else T=r;}var Z,T,ee=h(()=>{Z="sitepong_anonymous_id";T=null;});function Ze(r){let e=r.toLowerCase();return /ipad/.test(e)||/android/.test(e)&&!/mobile/.test(e)||/tablet/.test(e)?"tablet":/mobile/.test(e)||/iphone/.test(e)||/ipod/.test(e)||/android/.test(e)||/blackberry/.test(e)||/windows phone/.test(e)?"mobile":"desktop"}function et(r){let e=r.toLowerCase();return /edg/.test(e)?"edge":/opr|opera/.test(e)?"opera":/samsungbrowser/.test(e)?"samsung":/chrome|chromium|crios/.test(e)?"chrome":/safari/.test(e)&&!/chrome/.test(e)?"safari":/firefox|fxios/.test(e)?"firefox":/msie|trident/.test(e)?"ie":"other"}function tt(r){let e=r.toLowerCase();return /iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":/mac os|macos|macintosh/.test(e)?"macos":/windows/.test(e)?"windows":/linux/.test(e)?"linux":"other"}function ve(){let r=typeof navigator<"u"?navigator.userAgent:"";return {anonymous_id:E(),device_type:r?Ze(r):void 0,browser:r?et(r):void 0,os:r?tt(r):void 0,user_agent:r||void 0,timestamp:new Date}}var ye=h(()=>{ee();});function nt(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e^r.charCodeAt(t);return e>>>0}function sn(r){return Math.random()*100<r.percentage}function an(r,e,t){let n=`${e.anonymous_id}:${t}`;return nt(n)%100<r.percentage}function te(r){let[e,t]=r.split(":").map(Number);return e*60+t}function cn(r,e){let t=e.timestamp||new Date,i=new Intl.DateTimeFormat("en-US",{timeZone:r.timezone,weekday:"short",hour:"2-digit",minute:"2-digit",hour12:false}).formatToParts(t),o=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].indexOf(i.find(d=>d.type==="weekday")?.value||""),s=parseInt(i.find(d=>d.type==="hour")?.value||"0",10),c=parseInt(i.find(d=>d.type==="minute")?.value||"0",10),l=s*60+c;if(r.days_of_week&&r.days_of_week.length>0&&!r.days_of_week.includes(o))return false;if(r.start_time&&r.end_time){let d=te(r.start_time),f=te(r.end_time);if(d>f){if(l<d&&l>=f)return false}else if(l<d||l>=f)return false}else if(r.start_time){let d=te(r.start_time);if(l<d)return false}else if(r.end_time){let d=te(r.end_time);if(l>=d)return false}return true}function ln(r,e){return e.device_type?r.types.includes(e.device_type):false}function un(r,e){return e.browser?r.browsers.includes(e.browser):false}function dn(r,e){return e.os?r.operating_systems.includes(e.os):false}function fn(r,e,t,n){switch(r){case "percentage_rollout":return sn(e);case "userbase_percentage":return an(e,t,n);case "time_based":return cn(e,t);case "device_type":return ln(e,t);case "browser":return un(e,t);case "os":return dn(e,t);default:return false}}function ne(r,e){if(r.override==="force_on")return true;if(r.override==="force_off"||!r.enabled)return false;if(!r.rules||r.rules.length===0)return true;for(let t of r.rules)if(!fn(t.rule_type,t.config,e,r.key))return false;return true}function rt(r,e){if(!ne(r,e)||r.flag_type!=="multivariate"||!r.variants||r.variants.length===0)return null;let t=`${e.anonymous_id}:${r.key}:variant`,n=nt(t),i=r.variants.reduce((c,l)=>c+l.weight,0),o=n%i,s=0;for(let c of r.variants)if(s+=c.weight,o<s)return c.key;return r.variants[0].key}function it(r,e){return r.variant_payloads&&r.variant_payloads[e]!==void 0?r.variant_payloads[e]:r.variants?.find(n=>n.key===e)?.payload||null}var be=h(()=>{});var pn,M,ot=h(()=>{ye();be();pn="https://api.sitepong.com",M=class{constructor(e){this.flags=new Map;this.evaluatedFlags=new Map;this.evaluatedVariants=new Map;this.context=null;this.initialized=false;this.initPromise=null;this.config={endpoint:pn,debug:false,...e};}async init(){if(!this.initialized){if(this.initPromise)return this.initPromise;this.initPromise=this.fetchAndEvaluateFlags();try{await this.initPromise,this.initialized=!0;}catch(e){this.log("Failed to initialize flags:",e),this.initialized=true;}finally{this.initPromise=null;}}}async fetchAndEvaluateFlags(){try{let e=await fetch(`${this.config.endpoint}/api/sdk/flags`,{method:"GET",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey}});if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);let t=await e.json();this.log("Fetched flags:",t.flags.length),this.context=ve(),this.log("Evaluation context:",this.context),this.flags.clear(),this.evaluatedFlags.clear(),this.evaluatedVariants.clear();for(let n of t.flags){this.flags.set(n.key,n);let i=ne(n,this.context);if(this.evaluatedFlags.set(n.key,i),n.flag_type==="multivariate"&&n.variants){let o=rt(n,this.context);this.evaluatedVariants.set(n.key,o),this.log(`Flag "${n.key}": ${i}, variant: ${o}`);}else this.log(`Flag "${n.key}": ${i}`);}}catch(e){throw this.log("Error fetching flags:",e),e}}getFlag(e,t=false){if(!this.initialized)return this.log(`Flag "${e}" requested before init, returning default:`,t),t;let n=this.evaluatedFlags.get(e);return n===void 0?(this.log(`Flag "${e}" not found, returning default:`,t),t):n}getVariant(e,t=null){if(!this.initialized)return this.log(`Variant "${e}" requested before init, returning default:`,t),t;let n=this.evaluatedVariants.get(e);return n===void 0?(this.log(`Variant "${e}" not found, returning default:`,t),t):n}getVariantPayload(e,t=null){let n=this.getVariant(e);if(!n)return t;let i=this.flags.get(e);return i?it(i,n)??t:t}getAllFlags(){let e={};for(let[t,n]of this.evaluatedFlags)e[t]=n;return e}hasFlag(e){return this.flags.has(e)}isInitialized(){return this.initialized}async waitForInit(){this.initialized||await this.init();}async refresh(){this.initialized=false,await this.init();}getContext(){return this.context}log(...e){this.config.debug&&console.log("[SitePong Flags]",...e);}};});var we=h(()=>{ee();ye();be();ot();});function at(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return (r==="x"?e:e&3|8).toString(16)})}function ct(r){return Date.now()-r>18e5}function Te(){if(typeof window<"u"&&typeof sessionStorage<"u")try{let r=sessionStorage.getItem(Se),e=sessionStorage.getItem(re);if(r&&e&&!ct(parseInt(e,10)))return sessionStorage.setItem(re,String(Date.now())),r;let t=at();return sessionStorage.setItem(Se,t),sessionStorage.setItem(re,String(Date.now())),t}catch{return st()}return st()}function st(){return L&&O&&!ct(O)?(O=Date.now(),L):(L=at(),O=Date.now(),L)}function xe(){if(typeof window<"u"&&typeof sessionStorage<"u")try{sessionStorage.removeItem(Se),sessionStorage.removeItem(re);}catch{}L=null,O=null;}var Se,re,L,O,ke=h(()=>{Se="sitepong_session_id",re="sitepong_session_ts",L=null,O=null;});var lt,N,Ce=h(()=>{lt=["[data-sp-no-capture]",".sp-no-capture"],N=class{constructor(e,t){this.clickHandler=null;this.submitHandler=null;this.active=false;this.config={clicks:true,forms:true,pageviews:true,blockSelectors:lt,maxTextLength:255,debug:false,...e},this.callback=t;}start(){this.active||typeof document>"u"||typeof document.addEventListener!="function"||(this.active=true,this.config.clicks&&this.setupClickCapture(),this.config.forms&&this.setupFormCapture(),this.log("Autocapture started"));}stop(){this.active&&(this.active=false,this.clickHandler&&(document.removeEventListener("click",this.clickHandler,true),this.clickHandler=null),this.submitHandler&&(document.removeEventListener("submit",this.submitHandler,true),this.submitHandler=null),this.log("Autocapture stopped"));}setupClickCapture(){this.clickHandler=e=>{let t=e.target;if(!t||!this.shouldCapture(t))return;let n=this.getElementProperties(t);n.$event_type="click",n.$x=e.clientX,n.$y=e.clientY,this.callback({type:"click",timestamp:new Date().toISOString(),properties:n});},document.addEventListener("click",this.clickHandler,true);}setupFormCapture(){this.submitHandler=e=>{let t=e.target;if(!t||!this.shouldCapture(t))return;let n={$event_type:"form_submit",$form_action:t.action||void 0,$form_method:t.method||"get",$form_name:t.name||t.id||void 0,$field_names:this.getFormFieldNames(t),$field_count:t.elements.length},i=this.getElementProperties(t);Object.assign(n,i),this.callback({type:"form_submit",timestamp:new Date().toISOString(),properties:n});},document.addEventListener("submit",this.submitHandler,true);}shouldCapture(e){let t=this.config.blockSelectors||lt;for(let n of t)if(e.matches(n)||e.closest(n))return false;return !(this.config.allowSelectors&&this.config.allowSelectors.length>0&&!this.config.allowSelectors.some(i=>e.matches(i)||e.closest(i)!==null)||e.offsetParent===null&&e.tagName!=="BODY")}getElementProperties(e){let t={};t.$tag_name=e.tagName.toLowerCase(),t.$el_id=e.id||void 0,e.classList.length>0&&(t.$el_classes=Array.from(e.classList).slice(0,5));let n=this.getElementText(e);n&&(t.$el_text=n),e instanceof HTMLAnchorElement&&(t.$href=e.href||void 0,t.$target=e.target||void 0),(e instanceof HTMLInputElement||e instanceof HTMLButtonElement)&&(t.$el_type=e.type||void 0,t.$el_name=e.name||void 0);let i=e.getAttribute("aria-label");i&&(t.$aria_label=this.truncate(i));let o=e.getAttribute("role");return o&&(t.$el_role=o),t.$selector=this.getSelector(e),t.$current_url=window.location.href,t.$pathname=window.location.pathname,t}getElementText(e){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)return;let t="";if(e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement)t=e.innerText||e.textContent||"";else for(let n of Array.from(e.childNodes))n.nodeType===Node.TEXT_NODE&&(t+=n.textContent||"");return t=t.trim().replace(/\s+/g," "),t?this.truncate(t):void 0}getFormFieldNames(e){let t=[];for(let n of Array.from(e.elements)){let i=n;i.name&&i.type!=="password"&&i.type!=="hidden"&&t.push(i.name);}return t.slice(0,20)}getSelector(e){let t=[],n=e,i=0;for(;n&&n!==document.body&&i<5;){let o=n.tagName.toLowerCase();if(n.id){o=`#${n.id}`,t.unshift(o);break}n.classList.length>0&&(o+=`.${Array.from(n.classList).slice(0,2).join(".")}`);let s=n.parentElement;if(s){let c=Array.from(s.children).filter(l=>l.tagName===n.tagName);if(c.length>1){let l=c.indexOf(n)+1;o+=`:nth-of-type(${l})`;}}t.unshift(o),n=n.parentElement,i++;}return t.join(" > ")}truncate(e){let t=this.config.maxTextLength||255;return e.length>t?e.slice(0,t)+"...":e}log(...e){this.config.debug&&console.log("[SitePong Autocapture]",...e);}};});var dt={};je(dt,{currentPlatform:()=>H,detectPlatform:()=>ie,getCurrentUrl:()=>bn,getDeviceInfo:()=>vn,getNativeDeviceId:()=>B,getReferrer:()=>wn,getStorageAdapter:()=>oe,isBrowser:()=>V,isNode:()=>hn,isReactNative:()=>x,platformFetch:()=>yn,setNativeDeviceId:()=>mn,setRNDeviceInfo:()=>gn});function ie(){return typeof navigator<"u"&&navigator.product==="ReactNative"?"react-native":typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"&&typeof document<"u"?"browser":"unknown"}function V(){return H==="browser"}function x(){return H==="react-native"}function hn(){return H==="node"}function gn(r){Ee=r;}function mn(r){ut=r;}function B(){return ut}function vn(){if(x()&&Ee)return Ee;let r={platform:H};return V()&&typeof navigator<"u"&&(r.userAgent=navigator.userAgent),r}function oe(){return V()&&typeof localStorage<"u"?{getItem:async r=>localStorage.getItem(r),setItem:async(r,e)=>localStorage.setItem(r,e),removeItem:async r=>localStorage.removeItem(r)}:null}async function yn(r,e){if(typeof fetch<"u")return fetch(r,e);throw new Error("No fetch implementation available")}function bn(){return V()&&typeof window<"u"?window.location.href:null}function wn(){return V()&&typeof document<"u"&&document.referrer||null}var H,Ee,ut,P=h(()=>{H=ie();Ee=null,ut=null;});var Sn,Tn,xn,Me,I,ft=h(()=>{ke();ee();Ce();P();Sn="https://ingest.sitepong.com",Tn=20,xn=1e4,Me=3,I=class{constructor(e){this.eventQueue=[];this.flushTimer=null;this.flushFailures=0;this.disabled=false;this.userId=null;this.groupId=null;this.userTraits=null;this.groupTraits=null;this.lastUrl=null;this.popstateHandler=null;this.autocaptureModule=null;this.config={endpoint:Sn,enabled:true,autocapturePageviews:false,maxBatchSize:Tn,flushInterval:xn,debug:false,...e};}init(){this.config.enabled&&(this.startFlushTimer(),this.setupPageHideListener(),this.config.autocapturePageviews&&this.setupSPATracking(),this.setupAutocapture(),this.log("Analytics initialized"));}initHeadless(){this.config.enabled&&(this.startFlushTimer(),this.log("Analytics initialized (headless)"));}setupAutocapture(){let e=this.config.autocapture,t=this.config.autocaptureClicks,n=this.config.autocaptureForms,i=t||false,o=n||false,s,c;e===true?(i=true,o=true):e&&typeof e=="object"&&(i=e.clicks!==false,o=e.forms!==false,s=e.blockSelectors,c=e.allowSelectors,e.pageviews!==false&&!this.config.autocapturePageviews&&this.setupSPATracking()),!(!i&&!o)&&(this.autocaptureModule=new N({clicks:i,forms:o,pageviews:false,blockSelectors:s,allowSelectors:c,debug:this.config.debug},l=>{let d=l.type==="click"?"$autocapture_click":l.type==="form_submit"?"$autocapture_form_submit":"$autocapture";this.track(d,l.properties);}),this.autocaptureModule.start());}track(e,t){if(!this.config.enabled)return;let n=this.createEvent("track",{name:e,properties:t});this.enqueue(n),this.log("Track:",e,t);}trackPageView(e,t){if(!this.config.enabled)return;let n=e||(typeof window<"u"?window.location.href:void 0),i=this.createEvent("page",{properties:{url:n,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0,...t}});this.enqueue(i),this.log("Page view:",n);}identify(e,t){if(!this.config.enabled)return;this.userId=e,t&&(this.userTraits={...this.userTraits,...t});let n=this.createEvent("identify",{traits:this.userTraits||void 0});this.enqueue(n),this.log("Identify:",e,t);}group(e,t){if(!this.config.enabled)return;this.groupId=e,t&&(this.groupTraits={...this.groupTraits,...t});let n=this.createEvent("group",{traits:this.groupTraits||void 0});this.enqueue(n),this.log("Group:",e,t);}reset(){this.userId=null,this.groupId=null,this.userTraits=null,this.groupTraits=null,xe(),this.log("Analytics state reset");}async flush(){if(this.eventQueue.length===0)return;if(this.disabled){this.eventQueue=[];return}let e=[...this.eventQueue];this.eventQueue=[];let t=this.config.eventsEndpoint||`${this.config.endpoint}/api/events`;try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({events:e})});if(!n.ok)throw new Error(`HTTP ${n.status}`);this.flushFailures=0,this.log(`Flushed ${e.length} events`);}catch(n){if(this.flushFailures++,this.flushFailures>=Me){this.disabled=true,console.warn(`[SitePong Analytics] Disabled after ${Me} consecutive failures. Check that ${t} is accessible and has proper CORS headers.`);return}this.eventQueue.unshift(...e),this.log(`Failed to flush events (attempt ${this.flushFailures}/${Me}):`,n);}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.popstateHandler&&typeof window<"u"&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),this.autocaptureModule&&(this.autocaptureModule.stop(),this.autocaptureModule=null),this.flushWithBeacon();}createEvent(e,t){return {type:e,name:t.name,properties:t.properties,userId:this.userId||void 0,anonymousId:E(),deviceId:B()||void 0,groupId:this.groupId||void 0,traits:t.traits,sessionId:Te(),timestamp:new Date().toISOString(),url:typeof window<"u"?window.location.href:void 0,referrer:typeof document<"u"?document.referrer:void 0,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}}enqueue(e){this.eventQueue.push(e),this.eventQueue.length>=this.config.maxBatchSize&&this.flush();}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval);}setupPageHideListener(){typeof window>"u"||x()||typeof window.addEventListener!="function"||window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushWithBeacon();});}flushWithBeacon(){if(this.eventQueue.length===0||x()||typeof navigator?.sendBeacon!="function")return;let e=[...this.eventQueue];this.eventQueue=[];let t=this.config.eventsEndpoint||`${this.config.endpoint}/api/events`,n=new Blob([JSON.stringify({events:e,apiKey:this.config.apiKey})],{type:"application/json"});navigator.sendBeacon(t,n),this.log(`Flushed ${e.length} events via beacon`);}setupSPATracking(){if(typeof window>"u"||x()||typeof window.addEventListener!="function")return;this.lastUrl=window.location.href,this.trackPageView(),this.popstateHandler=()=>{let n=window.location.href;n!==this.lastUrl&&(this.lastUrl=n,this.trackPageView(n));},window.addEventListener("popstate",this.popstateHandler);let e=history.pushState.bind(history),t=history.replaceState.bind(history);history.pushState=(...n)=>{e(...n),this.handleUrlChange();},history.replaceState=(...n)=>{t(...n),this.handleUrlChange();};}handleUrlChange(){if(typeof window>"u")return;let e=window.location.href;e!==this.lastUrl&&(this.lastUrl=e,this.trackPageView(e));}log(...e){this.config.debug&&console.log("[SitePong Analytics]",...e);}};});var pt=h(()=>{ft();Ce();ke();});function Pe(){let r={uaSpoofed:false,antiDetectBrowser:false,canvasNoise:false,canvasBlocked:false,webglSpoofed:false,webglBlocked:false,vmIndicators:[],platformMismatch:false,pluginAnomaly:false,featureAnomaly:false,geolocationSpoofed:false,mitmIndicators:[]},e=0,t=kn(r);e+=t;let n=Cn(r);e+=n;let i=En(r);e+=i;let o=Mn(r);e+=o;let s=Pn(r);e+=s;let c=In(r);return e+=c,e=Math.min(e,1),{browserTampered:r.uaSpoofed||r.antiDetectBrowser||r.platformMismatch,canvasTampered:r.canvasNoise||r.canvasBlocked,webglTampered:r.webglSpoofed||r.webglBlocked,vmDetected:r.vmIndicators.length>=2,geolocationSpoofed:r.geolocationSpoofed,mitmDetected:r.mitmIndicators.length>=1,confidence:e,signals:r}}function kn(r){if(typeof navigator>"u"||typeof window>"u")return 0;let e=0,t=navigator.userAgent,n=navigator.platform||"",i=/Windows/.test(t),o=/Mac/.test(t),s=/Linux/.test(t)&&!/Android/.test(t),c=/Win/.test(n),l=/Mac/.test(n),d=/Linux/.test(n);(i&&!c||o&&!l||s&&!d)&&(r.platformMismatch=true,r.uaSpoofed=true,e+=.3);let f=/Chrome\/\d+/.test(t)&&!/Edge|OPR|Brave/.test(t);f&&!("chrome"in window||"CSS"in window&&"paintWorklet"in window.CSS)&&!("brave"in navigator)&&(r.uaSpoofed=true,e+=.2),/Firefox\/\d+/.test(t)&&!/Seamonkey/.test(t)&&("InstallTrigger"in window||CSS.supports("-moz-appearance","none")||(r.uaSpoofed=true,e+=.2));let u=navigator;if(u.userAgentData?.brands){let y=u.userAgentData.brands.map(k=>k.brand);(y.length===0||y.every(k=>k===""||k==="Not A;Brand"))&&(r.antiDetectBrowser=true,e+=.25);}/mobile|android|iphone|ipad/i.test(t)||(navigator.plugins?.length||0)===0&&f&&(r.pluginAnomaly=true,e+=.1);let p=navigator.hardwareConcurrency||0,m=navigator.deviceMemory||0;return p>0&&m>0&&p>=16&&m<=1&&(r.featureAnomaly=true,e+=.15),Math.min(e,.5)}function Cn(r){if(typeof document>"u")return 0;let e=0;try{let t=document.createElement("canvas");t.width=100,t.height=20;let n=t.getContext("2d");if(!n)return r.canvasBlocked=!0,.1;n.fillStyle="#ff0000",n.fillRect(0,0,100,20),n.fillStyle="#00ff00",n.font="12px Arial",n.fillText("SitePong",5,14);let i=t.toDataURL();n.clearRect(0,0,100,20),n.fillStyle="#ff0000",n.fillRect(0,0,100,20),n.fillStyle="#00ff00",n.font="12px Arial",n.fillText("SitePong",5,14);let o=t.toDataURL();i!==o&&(r.canvasNoise=!0,e+=.35);let c=n.getImageData(0,0,100,20).data,l=!0,d=!0,f=c[0];for(let u=0;u<c.length;u+=4)(c[u]!==0||c[u+1]!==0||c[u+2]!==0)&&(l=!1),c[u]!==f&&(d=!1);(l||d)&&(r.canvasBlocked=!0,e+=.2);let g=Object.getOwnPropertyDescriptor(HTMLCanvasElement.prototype,"toDataURL");g&&g.value!==HTMLCanvasElement.prototype.toDataURL&&(r.canvasNoise=!0,e+=.3);}catch{r.canvasBlocked=true,e+=.1;}return Math.min(e,.4)}function En(r){if(typeof document>"u")return 0;let e=0;try{let t=document.createElement("canvas"),n=t.getContext("webgl")||t.getContext("experimental-webgl");if(!n||!(n instanceof WebGLRenderingContext))return r.webglBlocked=!0,.1;let i=n.getExtension("WEBGL_debug_renderer_info");if(!i)return r.webglBlocked=!0,.1;let o=n.getParameter(i.UNMASKED_VENDOR_WEBGL),s=n.getParameter(i.UNMASKED_RENDERER_WEBGL),c=["Brian Paul","Mesa","VMware"];["llvmpipe","softpipe","Mesa","SwiftShader"].some(m=>s.includes(m))&&!c.some(m=>o.includes(m))&&(r.webglSpoofed=!0,e+=.25);let d=navigator.userAgent,f=/mobile|android|iphone|ipad/i.test(d),g=/GeForce|Radeon|Intel.*HD|GTX|RTX|Vega/i.test(s);f&&g&&(r.webglSpoofed=!0,e+=.3);let u=Object.getOwnPropertyDescriptor(WebGLRenderingContext.prototype,"getParameter");u&&typeof u.value=="function"&&(u.value.toString().includes("[native code]")||(r.webglSpoofed=!0,e+=.35)),(n.getSupportedExtensions()||[]).length<5&&g&&(r.webglSpoofed=!0,e+=.1);}catch{r.webglBlocked=true,e+=.1;}return Math.min(e,.4)}function Mn(r){if(typeof navigator>"u"||typeof window>"u")return 0;let e=[],t=navigator.userAgent;try{let s=document.createElement("canvas"),c=s.getContext("webgl")||s.getContext("experimental-webgl");if(c&&c instanceof WebGLRenderingContext){let l=c.getExtension("WEBGL_debug_renderer_info");if(l){let d=c.getParameter(l.UNMASKED_RENDERER_WEBGL).toLowerCase(),f=c.getParameter(l.UNMASKED_VENDOR_WEBGL).toLowerCase(),g=["vmware","virtualbox","hyper-v","parallels","qemu","llvmpipe","mesa"],u=["vmware","innotek","microsoft basic","parallels"];for(let p of g)d.includes(p)&&e.push(`webgl_renderer:${p}`);for(let p of u)f.includes(p)&&e.push(`webgl_vendor:${p}`);}}}catch{}if(typeof screen<"u"){let s=screen.width,c=screen.height;[[800,600],[1024,768],[1280,800]].some(([d,f])=>s===d&&c===f)&&screen.colorDepth===24&&navigator.hardwareConcurrency<=2&&e.push("vm_resolution");}let n=navigator.hardwareConcurrency||0,i=navigator.deviceMemory||0;if(n>0&&n<=2&&i>0&&i<=2&&(/mobile|android|iphone/i.test(t)||e.push("low_hw_specs")),typeof performance<"u"){let s=[];for(let l=0;l<10;l++)s.push(performance.now());new Set(s.map(l=>Math.floor(l*1e3))).size<=3&&s.length===10&&e.push("coarse_timing");}if(typeof navigator<"u"){let s=navigator.connection;s&&s.downlink&&s.downlink>=10&&s.rtt&&s.rtt<=5&&e.push("cloud_vm_network");}return r.vmIndicators=e,Math.min(e.length*.15,.5)}function Pn(r){if(typeof navigator>"u")return 0;let e=0;if("geolocation"in navigator){let t=Object.getOwnPropertyDescriptor(navigator,"geolocation");t&&t.configurable===false&&t.get&&(t.get.toString().includes("[native code]")||(r.geolocationSpoofed=true,e+=.3));try{let n=Object.getOwnPropertyDescriptor(Geolocation.prototype,"getCurrentPosition");n?.value&&(n.value.toString().includes("[native code]")||(r.geolocationSpoofed=!0,e+=.3));}catch{}}if(typeof window<"u")try{let t=Object.getPrototypeOf(navigator),n=Object.getOwnPropertyDescriptor(t,"geolocation");n&&n.get&&!n.get.toString().includes("[native code]")&&(r.geolocationSpoofed=!0,e+=.2);}catch{}return Math.min(e,.4)}function In(r){if(typeof window>"u"||typeof document>"u")return 0;let e=[];if(window.location?.protocol==="https:"){let n=document.querySelectorAll("script[src]");for(let i=0;i<n.length;i++){let o=n[i].getAttribute("src")||"";if(o.startsWith("http://")&&!o.includes("localhost")){e.push("mixed_content_script");break}}}let t=document.querySelectorAll("iframe");for(let n=0;n<t.length;n++){let i=t[n].getAttribute("src")||"";if(i&&!i.startsWith(window.location?.origin||"")&&!i.startsWith("about:")&&!i.startsWith("javascript:")){let o=window.getComputedStyle(t[n]);(o.display==="none"||o.visibility==="hidden"||parseInt(o.width)<=1||parseInt(o.height)<=1)&&e.push("hidden_iframe");}}if("serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(n=>{for(let i of n){let o=i.active?.scriptURL||"";o&&!o.startsWith(window.location?.origin||"")&&e.push("foreign_service_worker");}}).catch(()=>{}),typeof performance<"u"&&performance.getEntriesByType)try{let n=performance.getEntriesByType("navigation")[0];if(n){let i=n.connectEnd-n.connectStart,o=n.requestStart-n.secureConnectionStart;i>1e3&&o>500&&e.push("slow_tls_handshake");}}catch{}if(window.location?.protocol==="https:"&&typeof performance<"u")try{let n=performance.getEntriesByType("resource");for(let i of n.slice(0,20))if(i.transferSize===0&&i.encodedBodySize>0&&!i.name.includes("cache")){e.push("intercepted_resource");break}}catch{}return r.mitmIndicators=e,Math.min(e.length*.2,.5)}var Ie=h(()=>{});function ht(){return {userAgent:typeof navigator<"u"?navigator.userAgent:"",language:typeof navigator<"u"?navigator.language:"",languages:typeof navigator<"u"?Array.from(navigator.languages||[]):[],platform:typeof navigator<"u"&&navigator.platform||"",screenWidth:typeof screen<"u"?screen.width:0,screenHeight:typeof screen<"u"?screen.height:0,screenColorDepth:typeof screen<"u"?screen.colorDepth:0,devicePixelRatio:typeof window<"u"&&window.devicePixelRatio||1,timezoneOffset:new Date().getTimezoneOffset(),timezone:Intl?.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone||"",sessionStorage:Rn(),localStorage:Dn(),indexedDB:typeof indexedDB<"u",cookieEnabled:typeof navigator<"u"?navigator.cookieEnabled:false,hardwareConcurrency:typeof navigator<"u"&&navigator.hardwareConcurrency||0,maxTouchPoints:typeof navigator<"u"&&navigator.maxTouchPoints||0,deviceMemory:typeof navigator<"u"?navigator.deviceMemory:void 0}}async function gt(){let r={};r.canvasFingerprint=_n();let e=Fn();return r.webglVendor=e.vendor,r.webglRenderer=e.renderer,r.audioFingerprint=await An(),r.fontFingerprint=Kn(),r.mathFingerprint=zn(),r.webglRenderHash=qn(),r.cssFeatureHash=Wn(),r.localIps=await Xn(),r}async function Re(r){let t={...ht()};r&&(t.extended=await gt());let n=vt();return t.smart=n,t.incognito=n.incognito,t.bot=n.bot,t}async function mt(r){let e={userAgent:r.userAgent,language:r.language,languages:r.languages,platform:r.platform,screenWidth:r.screenWidth,screenHeight:r.screenHeight,screenColorDepth:r.screenColorDepth,devicePixelRatio:r.devicePixelRatio,timezoneOffset:r.timezoneOffset,timezone:r.timezone,hardwareConcurrency:r.hardwareConcurrency,maxTouchPoints:r.maxTouchPoints,deviceMemory:r.deviceMemory};return r.extended&&(e.canvasFingerprint=r.extended.canvasFingerprint,e.webglVendor=r.extended.webglVendor,e.webglRenderer=r.extended.webglRenderer,e.audioFingerprint=r.extended.audioFingerprint,e.fontFingerprint=r.extended.fontFingerprint,e.mathFingerprint=r.extended.mathFingerprint,e.webglRenderHash=r.extended.webglRenderHash,e.cssFeatureHash=r.extended.cssFeatureHash,e.localIps=r.extended.localIps),e}function vt(){let r={};r.incognito=Ln(),r.bot=On(),r.privacyBrowser=Nn(),r.devToolsOpen=Hn(),r.connectionType=Vn(),r.doNotTrack=Bn(),r.notificationsEnabled=$n();let e=Un();r.deviceFirstSeen=e.firstSeen,r.deviceVisitCount=e.visitCount;let t=Pe();return r.browserTampered=t.browserTampered,r.canvasTampered=t.canvasTampered,r.webglTampered=t.webglTampered,r.vmDetected=t.vmDetected,r.vmIndicators=t.signals.vmIndicators,r}function Rn(){try{let r="__sp_test__";return sessionStorage.setItem(r,"1"),sessionStorage.removeItem(r),!0}catch{return false}}function Dn(){try{let r="__sp_test__";return localStorage.setItem(r,"1"),localStorage.removeItem(r),!0}catch{return false}}function _n(){if(!(typeof document>"u"))try{let r=document.createElement("canvas"),e=r.getContext("2d");return e?(r.width=200,r.height=50,e.textBaseline="top",e.font="14px Arial",e.fillStyle="#f60",e.fillRect(0,0,200,50),e.fillStyle="#069",e.fillText("SitePong fingerprint",2,15),e.fillStyle="rgba(102, 204, 0, 0.7)",e.fillText("SitePong fingerprint",4,17),R(r.toDataURL())):void 0}catch{return}}function Fn(){if(typeof document>"u")return {};try{let r=document.createElement("canvas"),e=r.getContext("webgl")||r.getContext("experimental-webgl");if(!e||!(e instanceof WebGLRenderingContext))return {};let t=e.getExtension("WEBGL_debug_renderer_info");return t?{vendor:e.getParameter(t.UNMASKED_VENDOR_WEBGL),renderer:e.getParameter(t.UNMASKED_RENDERER_WEBGL)}:{}}catch{return {}}}async function An(){if(!(typeof window>"u"||typeof OfflineAudioContext>"u"))try{let r=new OfflineAudioContext(1,4500,44100),e=r.createOscillator();e.type="triangle",e.frequency.setValueAtTime(1e4,r.currentTime);let t=r.createDynamicsCompressor();t.threshold.setValueAtTime(-50,r.currentTime),t.knee.setValueAtTime(40,r.currentTime),t.ratio.setValueAtTime(12,r.currentTime),t.attack.setValueAtTime(0,r.currentTime),t.release.setValueAtTime(.25,r.currentTime),e.connect(t),t.connect(r.destination),e.start(0);let i=(await r.startRendering()).getChannelData(0),o=0;for(let s=4e3;s<4500;s++)o+=Math.abs(i[s]);return R(`audio:${o.toFixed(6)}`)}catch{return}}function Ln(){if(typeof window>"u")return false;try{let r="__sp_incognito_test__";try{localStorage.setItem(r,new Array(100).join("x")),localStorage.removeItem(r);}catch{return !0}if(typeof indexedDB<"u")try{let t=indexedDB.open("__sp_test__");t.onerror=()=>{};}catch{return !0}if("webkitRequestFileSystem"in window){let t=!1;try{window.webkitRequestFileSystem(0,1,()=>{t=!1;},()=>{t=!0;});}catch{}if(t)return !0}let e=performance;if(e.memory){let t=e.memory.jsHeapSizeLimit||0;if(t>0&&t<1073741824)return !0}return !1}catch{return false}}function On(){if(typeof navigator>"u")return false;let r=navigator.userAgent.toLowerCase();return !!(["bot","crawler","spider","headless","phantom","puppeteer","selenium","webdriver","playwright"].some(t=>r.includes(t))||"webdriver"in navigator&&navigator.webdriver||navigator.plugins&&navigator.plugins.length===0&&!/mobile|android|iphone/i.test(r))}function Nn(){if(typeof navigator>"u")return false;let r=navigator.userAgent.toLowerCase();return !!("brave"in navigator||r.includes("focus")&&r.includes("firefox")||r.includes("duckduckgo")||typeof window<"u"&&(screen.width===1e3&&screen.height===1e3||new Date().getTimezoneOffset()===0&&navigator.language!=="en"))}function Hn(){if(typeof window>"u")return false;try{let r=window.outerWidth-window.innerWidth>160,e=window.outerHeight-window.innerHeight>160;if(r||e)return !0}catch{}return false}function Vn(){if(typeof navigator>"u")return;let r=navigator.connection;if(r)return r.effectiveType||r.type||void 0}function Bn(){if(typeof navigator>"u")return false;let r=navigator.doNotTrack;return r==="1"||r==="yes"}function $n(){return typeof Notification>"u"?false:Notification.permission==="granted"}function Un(){let r="sitepong_device_age",e={visitCount:1};if(typeof localStorage>"u")return e;try{let t=localStorage.getItem(r);if(t){let n=JSON.parse(t);e.firstSeen=n.firstSeen,e.visitCount=(n.visitCount||0)+1;}else e.firstSeen=new Date().toISOString();localStorage.setItem(r,JSON.stringify({firstSeen:e.firstSeen,visitCount:e.visitCount}));}catch{}return e}function Kn(){if(!(typeof document>"u"))try{let r=["monospace","sans-serif","serif"],e=["Arial","Arial Black","Courier New","Georgia","Helvetica","Impact","Lucida Console","Lucida Sans Unicode","Palatino Linotype","Tahoma","Times New Roman","Trebuchet MS","Verdana","Comic Sans MS","Courier","Garamond","Monaco"],t="mmmmmmmmmmlli",n="72px",o=document.createElement("canvas").getContext("2d");if(!o)return;let s={};for(let l of r)o.font=`${n} ${l}`,s[l]=o.measureText(t).width;let c=[];for(let l of e)for(let d of r)if(o.font=`${n} '${l}', ${d}`,o.measureText(t).width!==s[d]){c.push(l);break}return R(c.join(","))}catch{return}}function zn(){try{let r=[Math.tan(-1e300),Math.log(1e-10),Math.pow(Math.PI,-100),Math.acos(.5),Math.atan2(1,1),Math.exp(1),Math.sinh(1)];return R(r.map(e=>e.toString()).join(","))}catch{return}}function qn(){if(!(typeof document>"u"))try{let r=document.createElement("canvas");r.width=50,r.height=50;let e=r.getContext("webgl");if(!e)return;let t=e.createShader(e.VERTEX_SHADER);e.shaderSource(t,"attribute vec2 p;void main(){gl_Position=vec4(p,0,1);}"),e.compileShader(t);let n=e.createShader(e.FRAGMENT_SHADER);e.shaderSource(n,"precision mediump float;void main(){gl_FragColor=vec4(.86,.27,.33,1);}"),e.compileShader(n);let i=e.createProgram();e.attachShader(i,t),e.attachShader(i,n),e.linkProgram(i),e.useProgram(i);let o=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,o),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,.5,-.5,-.5,.5,-.5]),e.STATIC_DRAW);let s=e.getAttribLocation(i,"p");return e.enableVertexAttribArray(s),e.vertexAttribPointer(s,2,e.FLOAT,!1,0,0),e.clearColor(0,0,0,1),e.clear(e.COLOR_BUFFER_BIT),e.drawArrays(e.TRIANGLES,0,3),R(r.toDataURL())}catch{return}}function Wn(){if(!(typeof CSS>"u"||typeof CSS.supports!="function"))try{let e=["display: grid","display: flex","display: contents","position: sticky","backdrop-filter: blur(1px)","gap: 1px","aspect-ratio: 1","contain: paint","overflow: clip","accent-color: red","color: oklch(0.5 0.2 0)","container-type: inline-size","text-wrap: balance","view-transition-name: x","anchor-name: --x","field-sizing: content"].map(t=>CSS.supports(t)?"1":"0").join("");return R(e)}catch{return}}async function Xn(){if(!(typeof window>"u"||typeof RTCPeerConnection>"u"))try{let r=new Set,e=new RTCPeerConnection({iceServers:[]});e.createDataChannel("");let t=await e.createOffer();return await e.setLocalDescription(t),new Promise(n=>{let i=setTimeout(()=>{e.close(),n(r.size>0?Array.from(r):void 0);},1e3);e.onicecandidate=o=>{if(!o.candidate){clearTimeout(i),e.close(),n(r.size>0?Array.from(r):void 0);return}let s=o.candidate.candidate.match(/([0-9]{1,3}\.([0-9]{1,3}\.){2}[0-9]{1,3})/);s&&s[1]&&!s[1].startsWith("0.")&&r.add(s[1]);};})}catch{return}}function R(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);e=(e<<5)-e+n,e=e&e;}return Math.abs(e).toString(16)}var De=h(()=>{Ie();});var $,_e=h(()=>{$=class{constructor(){this.mousePoints=[];this.keyDownTimes=new Map;this.keyIntervals=[];this.keyHoldTimes=[];this.lastKeyTime=0;this.scrollEvents=[];this.clickTimes=[];this.running=false;this.maxSamples=500;this.handleMouseMove=e=>{this.mousePoints.length>=this.maxSamples||this.mousePoints.push({x:e.clientX,y:e.clientY,t:Date.now()});};this.handleKeyDown=e=>{if(this.keyIntervals.length>=this.maxSamples)return;let t=Date.now();this.keyDownTimes.set(e.key,t),this.lastKeyTime>0&&this.keyIntervals.push(t-this.lastKeyTime),this.lastKeyTime=t;};this.handleKeyUp=e=>{let t=this.keyDownTimes.get(e.key);t&&(this.keyHoldTimes.push(Date.now()-t),this.keyDownTimes.delete(e.key));};this.handleScroll=()=>{this.scrollEvents.length>=this.maxSamples||this.scrollEvents.push({deltaY:window.scrollY,t:Date.now()});};this.handleClick=()=>{this.clickTimes.length>=this.maxSamples||this.clickTimes.push(Date.now());};}start(){this.running||typeof window>"u"||typeof window.addEventListener!="function"||(this.running=true,window.addEventListener("mousemove",this.handleMouseMove,{passive:true}),window.addEventListener("keydown",this.handleKeyDown,{passive:true}),window.addEventListener("keyup",this.handleKeyUp,{passive:true}),window.addEventListener("scroll",this.handleScroll,{passive:true}),window.addEventListener("click",this.handleClick,{passive:true}));}stop(){!this.running||typeof window>"u"||typeof window.removeEventListener!="function"||(this.running=false,window.removeEventListener("mousemove",this.handleMouseMove),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),window.removeEventListener("scroll",this.handleScroll),window.removeEventListener("click",this.handleClick));}getMetrics(){let e=this.analyzeMouseMovement(),t=this.analyzeKeyboard(),n=this.analyzeScroll(),i=this.analyzeClicks(),o=this.calculateHumanScore(e,t,n,i);return {mouse:e,keyboard:t,scroll:n,clicks:i,score:o}}reset(){this.mousePoints=[],this.keyDownTimes.clear(),this.keyIntervals=[],this.keyHoldTimes=[],this.lastKeyTime=0,this.scrollEvents=[],this.clickTimes=[];}analyzeMouseMovement(){if(this.mousePoints.length<3)return {totalMovements:this.mousePoints.length,averageSpeed:0,maxSpeed:0,averageAcceleration:0,straightLineRatio:0,jitter:0,hasMovement:false};let e=[],t=[],n=0,i=0,o=0;for(let d=1;d<this.mousePoints.length;d++){let f=this.mousePoints[d-1],g=this.mousePoints[d],u=g.t-f.t||1,p=g.x-f.x,m=g.y-f.y,y=Math.sqrt(p*p+m*m),k=y/u;if(e.push(k),y<3&&y>0&&o++,d>=2){let w=this.mousePoints[d-2],Jt=w.x+(g.x-w.x)*((f.t-w.t)/(g.t-w.t)),Zt=w.y+(g.y-w.y)*((f.t-w.t)/(g.t-w.t)),en=Math.sqrt((f.x-Jt)**2+(f.y-Zt)**2);i++,en<2&&n++;}if(d>=2){let w=e[e.length-2]||0;t.push(Math.abs(k-w)/u);}}let s=e.reduce((d,f)=>d+f,0)/e.length,c=Math.max(...e),l=t.length>0?t.reduce((d,f)=>d+f,0)/t.length:0;return {totalMovements:this.mousePoints.length,averageSpeed:Math.round(s*1e3)/1e3,maxSpeed:Math.round(c*1e3)/1e3,averageAcceleration:Math.round(l*1e3)/1e3,straightLineRatio:i>0?n/i:0,jitter:this.mousePoints.length>0?o/this.mousePoints.length:0,hasMovement:true}}analyzeKeyboard(){if(this.keyIntervals.length<2)return {totalKeystrokes:this.keyIntervals.length,averageInterval:0,intervalVariance:0,holdTimeAverage:0,holdTimeVariance:0,hasKeystrokes:false};let e=this.keyIntervals.reduce((o,s)=>o+s,0)/this.keyIntervals.length,t=this.variance(this.keyIntervals),n=this.keyHoldTimes.length>0?this.keyHoldTimes.reduce((o,s)=>o+s,0)/this.keyHoldTimes.length:0,i=this.keyHoldTimes.length>0?this.variance(this.keyHoldTimes):0;return {totalKeystrokes:this.keyIntervals.length+1,averageInterval:Math.round(e),intervalVariance:Math.round(t),holdTimeAverage:Math.round(n),holdTimeVariance:Math.round(i),hasKeystrokes:true}}analyzeScroll(){if(this.scrollEvents.length<2)return {totalScrolls:this.scrollEvents.length,averageSpeed:0,smoothness:0,hasScroll:false};let e=[];for(let s=1;s<this.scrollEvents.length;s++){let c=this.scrollEvents[s].t-this.scrollEvents[s-1].t||1,l=Math.abs(this.scrollEvents[s].deltaY-this.scrollEvents[s-1].deltaY);e.push(l/c);}let n=e.reduce((s,c)=>s+c,0)/e.length,i=this.variance(e),o=n>0?Math.min(1,n/(i+n)):0;return {totalScrolls:this.scrollEvents.length,averageSpeed:Math.round(n*100)/100,smoothness:Math.round(o*100)/100,hasScroll:true}}analyzeClicks(){if(this.clickTimes.length<2)return {totalClicks:this.clickTimes.length,averageInterval:0,intervalVariance:0,doubleClickCount:0,hasClicks:this.clickTimes.length>0};let e=[],t=0;for(let o=1;o<this.clickTimes.length;o++){let s=this.clickTimes[o]-this.clickTimes[o-1];e.push(s),s<500&&t++;}let n=e.reduce((o,s)=>o+s,0)/e.length,i=this.variance(e);return {totalClicks:this.clickTimes.length,averageInterval:Math.round(n),intervalVariance:Math.round(i),doubleClickCount:t,hasClicks:true}}calculateHumanScore(e,t,n,i){let o=.5,s=0;if(e.hasMovement){s++;let c=.5;e.jitter>.05&&(c+=.15),e.straightLineRatio<.5?c+=.15:e.straightLineRatio>.9&&(c-=.2),e.averageSpeed>0&&e.maxSpeed/e.averageSpeed>3&&(c+=.1),e.averageAcceleration>0&&(c+=.1),o+=Math.max(0,Math.min(1,c))-.5;}if(t.hasKeystrokes){s++;let c=.5;t.intervalVariance>1e3?c+=.2:t.intervalVariance<100&&(c-=.2),(t.averageInterval>0?Math.sqrt(t.intervalVariance)/t.averageInterval:0)>.3&&(c+=.15),t.holdTimeVariance>500&&(c+=.1),o+=Math.max(0,Math.min(1,c))-.5;}if(n.hasScroll){s++;let c=.5;n.smoothness>.3&&n.smoothness<.9&&(c+=.2),o+=Math.max(0,Math.min(1,c))-.5;}if(i.hasClicks){s++;let c=.5;i.intervalVariance>5e4?c+=.15:i.intervalVariance<100&&(c-=.2),o+=Math.max(0,Math.min(1,c))-.5;}return s===0?.3:Math.max(0,Math.min(1,o))}variance(e){if(e.length<2)return 0;let t=e.reduce((n,i)=>n+i,0)/e.length;return e.reduce((n,i)=>n+(i-t)**2,0)/(e.length-1)}};});async function Fe(){let r={webrtcLeak:null,timezoneIPMismatch:false,dnsLeak:null,connectionType:null,multipleIPs:false,torBrowser:false,knownVPNExtension:false},e=0,t=false,n=false,i=false;r.torBrowser=Gn(),r.torBrowser&&(i=true,e+=.9);try{r.webrtcLeak=await jn(),r.webrtcLeak&&(t=!0,e+=.3);}catch{r.webrtcLeak=null;}r.connectionType=Qn(),(r.connectionType==="unknown"||r.connectionType===null)&&(e+=.05),r.knownVPNExtension=Yn(),r.knownVPNExtension&&(t=true,e+=.4);let o=Intl.DateTimeFormat().resolvedOptions().timeZone,s=navigator.language;if(o&&s){let c=Jn(o),l=s.split("-")[1]?.toUpperCase();c&&l&&c!==l&&(r.timezoneIPMismatch=true,e+=.1);}return e=Math.min(e,1),e<.3&&(t=false,n=false),{vpnDetected:t,proxyDetected:n,torDetected:i,confidence:e,signals:r}}function Gn(){if(typeof window>"u")return false;let r=[];r.push(window.screen.width===1e3&&window.screen.height===1e3),r.push(!window.MediaDevices),r.push(navigator.plugins.length===0),r.push(new Date().getTimezoneOffset()===0);let e=navigator.userAgent;return r.push(e.includes("Firefox")&&!e.includes("Chrome")),r.filter(Boolean).length>=3}async function jn(){return typeof window>"u"||!window.RTCPeerConnection?false:new Promise(r=>{let e=setTimeout(()=>r(false),3e3),t=new Set;try{let n=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]});n.createDataChannel(""),n.onicecandidate=i=>{if(!i.candidate){clearTimeout(e),n.close(),r(t.size>1);return}let s=i.candidate.candidate.match(/(\d{1,3}\.){3}\d{1,3}/);s&&t.add(s[0]);},n.createOffer().then(i=>n.setLocalDescription(i)).catch(()=>{clearTimeout(e),r(!1);});}catch{clearTimeout(e),r(false);}})}function Qn(){if(typeof navigator>"u")return null;let r=navigator;return r.connection&&(r.connection.type||r.connection.effectiveType)||null}function Yn(){if(typeof document>"u"||!document.body)return false;let e=["[data-windscribe]","[data-nord]",".surfshark-extension","#vpn-indicator","[data-expressvpn]"];for(let t of e)try{if(document.querySelector(t))return !0}catch{}return false}function Jn(r){return {"America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","Europe/London":"GB","Europe/Paris":"FR","Europe/Berlin":"DE","Europe/Madrid":"ES","Europe/Rome":"IT","Asia/Tokyo":"JP","Asia/Shanghai":"CN","Asia/Kolkata":"IN","Asia/Seoul":"KR","Australia/Sydney":"AU","America/Toronto":"CA","America/Sao_Paulo":"BR","America/Mexico_City":"MX"}[r]||null}var Ae=h(()=>{});var Zn,Le,yt,bt,er,U,wt=h(()=>{De();_e();Ae();P();Zn="https://ingest.sitepong.com",Le="sitepong_visitor",yt=720*60*60*1e3,bt="__sp_vid",er=63072e3,U=class{constructor(e){this.cachedVisitor=null;this.pendingRequest=null;this.config={endpoint:Zn,enabled:true,debug:false,...e},this.behaviorAnalyzer=new $,this.config.enabled&&typeof window<"u"&&typeof window.addEventListener=="function"&&this.behaviorAnalyzer.start(),this.loadFromStorage();}async getVisitorId(){if(!this.config.enabled)throw new Error("Fingerprint is not enabled");let e=x()?B():null;if(e){let t={visitorId:e,confidence:1,firstSeenAt:new Date().toISOString(),lastSeenAt:new Date().toISOString()};return this.log("Using native device ID as visitor ID:",e),t}if(this.cachedVisitor&&!this.isCacheExpired())return this.log("Returning cached visitor ID:",this.cachedVisitor.result.visitorId),this.cachedVisitor.result;if(this.pendingRequest)return this.pendingRequest;this.pendingRequest=this.fetchVisitorId();try{return await this.pendingRequest}finally{this.pendingRequest=null;}}async getDeviceSignals(){return Re(this.config.extendedSignals??false)}async getFraudCheck(){let[e,t,n]=await Promise.all([this.getVisitorId(),this.getDeviceSignals(),Fe().catch(()=>null)]),i=this.behaviorAnalyzer.getMetrics();t.behavior={score:i.score,mouseMovements:i.mouse.totalMovements,keystrokes:i.keyboard.totalKeystrokes,scrolls:i.scroll.totalScrolls,clicks:i.clicks.totalClicks,isHuman:i.score>.6};let o=n?.vpnDetected||n?.torDetected||false;return {visitorId:e.visitorId,riskScore:this.calculateRiskScore(t,o),signals:t,flags:{incognito:t.smart?.incognito||t.incognito,bot:t.smart?.bot||t.bot||!t.behavior.isHuman,vpn:o||t.smart?.timezoneMismatch,tampered:t.smart?.privacyBrowser}}}stopBehaviorTracking(){this.behaviorAnalyzer.stop();}async fetchVisitorId(){let e=await this.getDeviceSignals(),t=await mt(e),n=this.config.visitorEndpoint||`${this.config.endpoint}/api/visitors`,i=this.getCookieVisitorId()||this.cachedVisitor?.result.visitorId||void 0;try{let o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},credentials:"include",body:JSON.stringify({signals:e,stableFingerprint:t,previousVisitorId:i})});if(!o.ok)throw new Error(`HTTP ${o.status}`);let s=await o.json();return this.cachedVisitor={result:s,signals:e,cachedAt:Date.now()},this.saveToStorage(),this.setCookieVisitorId(s.visitorId),this.log("Visitor ID fetched:",s.visitorId),s}catch(o){throw this.log("Failed to fetch visitor ID:",o),o}}calculateRiskScore(e,t=false){let n=0,i=e.smart;return (i?.bot||e.bot)&&(n+=.8),e.behavior&&(e.behavior.score<.3?n+=.4:e.behavior.score<.5&&(n+=.2)),t&&(n+=.25),(i?.incognito||e.incognito)&&(n+=.2),i?.devToolsOpen&&(n+=.1),i?.privacyBrowser&&(n+=.1),e.hardwareConcurrency===0&&(n+=.1),e.maxTouchPoints===0&&/mobile|android|iphone/i.test(e.userAgent)&&(n+=.15),e.cookieEnabled||(n+=.1),i?.doNotTrack&&(n+=.05),i?.deviceVisitCount===1&&(n+=.05),Math.round(Math.min(n,1)*100)/100}isCacheExpired(){return this.cachedVisitor?Date.now()-this.cachedVisitor.cachedAt>yt:true}loadFromStorage(){if(!(typeof window>"u"||typeof localStorage>"u"))try{let e=localStorage.getItem(Le);if(!e)return;let t=JSON.parse(e);this.isCacheExpiredAt(t.cachedAt)?localStorage.removeItem(Le):(this.cachedVisitor=t,this.log("Loaded cached visitor from storage"));}catch{}}saveToStorage(){if(!(typeof window>"u"||typeof localStorage>"u")&&this.cachedVisitor)try{localStorage.setItem(Le,JSON.stringify(this.cachedVisitor));}catch{}}isCacheExpiredAt(e){return Date.now()-e>yt}getCookieVisitorId(){if(!(typeof document>"u"))try{return document.cookie.match(new RegExp(`(?:^|; )${bt}=([^;]*)`))?.[1]||void 0}catch{return}}setCookieVisitorId(e){if(!(typeof document>"u"))try{document.cookie=`${bt}=${e}; path=/; max-age=${er}; SameSite=Lax`;}catch{}}log(...e){this.config.debug&&console.log("[SitePong Fingerprint]",...e);}};});var St=h(()=>{});var Tt=h(()=>{wt();De();_e();Ae();Ie();St();});function tr(){Ct=0;}function b(r){let e=xt.get(r);return e===void 0&&(e=++Ct,xt.set(r,e)),e}function rr(r){if(typeof document>"u")return {};K||(K=new Map);let e=K.get(r);if(e)return e;try{S||(S=document.createElement("iframe"),S.style.cssText="position:fixed;top:-9999px;left:-9999px;width:0;height:0;border:none;visibility:hidden;",document.body.appendChild(S));let t=S.contentDocument;if(!t)return {};let n=t.createElement(r);t.body.appendChild(n);let i=t.defaultView.getComputedStyle(n),o={};for(let s of Mt)o[s]=i.getPropertyValue(s);return t.body.removeChild(n),K.set(r,o),o}catch{return {}}}function Oe(r){if(typeof window>"u")return null;try{let e=r.tagName.toLowerCase();if(Et.has(e)||e==="head"||e==="html"||e==="meta"||e==="link"||e==="title")return null;let t=window.getComputedStyle(r),n=rr(e),i=[];for(let o of Mt){let s=t.getPropertyValue(o);s&&s!==n[o]&&i.push(`${o}:${s}`);}return i.length>0?i.join(";"):null}catch{return null}}async function Pt(r){if(C.has(r))return C.get(r)??null;try{let e=await fetch(r,{mode:"cors"});if(!e.ok)return C.set(r,null),null;let t=await e.text(),n=se(t,r);return C.set(r,n),n}catch{return C.set(r,null),null}}function ir(r){return C.get(r)??null}function It(){S&&S.parentNode&&S.parentNode.removeChild(S),S=null,K=null,C.clear();}function Rt(r,e){if(!r||r.startsWith("data:")||r.startsWith("blob:")||r.startsWith("#"))return r;try{return new URL(r,e).href}catch{return r}}function se(r,e){return r.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(t,n,i)=>{let o=i.trim();if(o.startsWith("data:")||o.startsWith("blob:")||o.startsWith("http://")||o.startsWith("https://")||o.startsWith("//"))return `url(${n}${o}${n})`;try{let s=new URL(o,e).href;return `url(${n}${s}${n})`}catch{return `url(${n}${o}${n})`}})}function kt(r){try{let e=r.cssRules,t="";for(let n=0;n<e.length;n++)t+=e[n].cssText+`
|
|
2
|
-
`;return t}catch{return null}}function
|
|
1
|
+
var SitePong=(function(exports){'use strict';var Te=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var K="sitepong_anonymous_id";function re(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return (r==="x"?e:e&3|8).toString(16)})}var S=null;function k(){if(typeof window<"u"&&typeof localStorage<"u")try{let r=localStorage.getItem(K);return r||(r=re(),localStorage.setItem(K,r)),r}catch{return S||(S=re()),S}return S||(S=re()),S}function xe(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(K);}catch{}S=null;}function ke(r){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.setItem(K,r);}catch{S=r;}else S=r;}function Ce(r){let e=r.toLowerCase();return /ipad/.test(e)||/android/.test(e)&&!/mobile/.test(e)||/tablet/.test(e)?"tablet":/mobile/.test(e)||/iphone/.test(e)||/ipod/.test(e)||/android/.test(e)||/blackberry/.test(e)||/windows phone/.test(e)?"mobile":"desktop"}function Ee(r){let e=r.toLowerCase();return /edg/.test(e)?"edge":/opr|opera/.test(e)?"opera":/samsungbrowser/.test(e)?"samsung":/chrome|chromium|crios/.test(e)?"chrome":/safari/.test(e)&&!/chrome/.test(e)?"safari":/firefox|fxios/.test(e)?"firefox":/msie|trident/.test(e)?"ie":"other"}function Me(r){let e=r.toLowerCase();return /iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":/mac os|macos|macintosh/.test(e)?"macos":/windows/.test(e)?"windows":/linux/.test(e)?"linux":"other"}function ie(){let r=typeof navigator<"u"?navigator.userAgent:"";return {anonymous_id:k(),device_type:r?Ce(r):void 0,browser:r?Ee(r):void 0,os:r?Me(r):void 0,user_agent:r||void 0,timestamp:new Date}}function Re(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e^r.charCodeAt(t);return e>>>0}function it(r){return Math.random()*100<r.percentage}function ot(r,e,t){let n=`${e.anonymous_id}:${t}`;return Re(n)%100<r.percentage}function q(r){let[e,t]=r.split(":").map(Number);return e*60+t}function st(r,e){let t=e.timestamp||new Date,i=new Intl.DateTimeFormat("en-US",{timeZone:r.timezone,weekday:"short",hour:"2-digit",minute:"2-digit",hour12:false}).formatToParts(t),o=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].indexOf(i.find(d=>d.type==="weekday")?.value||""),s=parseInt(i.find(d=>d.type==="hour")?.value||"0",10),l=parseInt(i.find(d=>d.type==="minute")?.value||"0",10),c=s*60+l;if(r.days_of_week&&r.days_of_week.length>0&&!r.days_of_week.includes(o))return false;if(r.start_time&&r.end_time){let d=q(r.start_time),f=q(r.end_time);if(d>f){if(c<d&&c>=f)return false}else if(c<d||c>=f)return false}else if(r.start_time){let d=q(r.start_time);if(c<d)return false}else if(r.end_time){let d=q(r.end_time);if(c>=d)return false}return true}function at(r,e){return e.device_type?r.types.includes(e.device_type):false}function lt(r,e){return e.browser?r.browsers.includes(e.browser):false}function ct(r,e){return e.os?r.operating_systems.includes(e.os):false}function ut(r,e,t,n){switch(r){case "percentage_rollout":return it(e);case "userbase_percentage":return ot(e,t,n);case "time_based":return st(e,t);case "device_type":return at(e,t);case "browser":return lt(e,t);case "os":return ct(e,t);default:return false}}function W(r,e){if(r.override==="force_on")return true;if(r.override==="force_off"||!r.enabled)return false;if(!r.rules||r.rules.length===0)return true;for(let t of r.rules)if(!ut(t.rule_type,t.config,e,r.key))return false;return true}function Pe(r,e){if(!W(r,e)||r.flag_type!=="multivariate"||!r.variants||r.variants.length===0)return null;let t=`${e.anonymous_id}:${r.key}:variant`,n=Re(t),i=r.variants.reduce((l,c)=>l+c.weight,0),o=n%i,s=0;for(let l of r.variants)if(s+=l.weight,o<s)return l.key;return r.variants[0].key}function Ie(r,e){return r.variant_payloads&&r.variant_payloads[e]!==void 0?r.variant_payloads[e]:r.variants?.find(n=>n.key===e)?.payload||null}var dt="https://api.sitepong.com",C=class{constructor(e){this.flags=new Map;this.evaluatedFlags=new Map;this.evaluatedVariants=new Map;this.context=null;this.initialized=false;this.initPromise=null;this.config={endpoint:dt,debug:false,...e};}async init(){if(!this.initialized){if(this.initPromise)return this.initPromise;this.initPromise=this.fetchAndEvaluateFlags();try{await this.initPromise,this.initialized=!0;}catch(e){this.log("Failed to initialize flags:",e),this.initialized=true;}finally{this.initPromise=null;}}}async fetchAndEvaluateFlags(){try{let e=await fetch(`${this.config.endpoint}/api/sdk/flags`,{method:"GET",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey}});if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);let t=await e.json();this.log("Fetched flags:",t.flags.length),this.context=ie(),this.log("Evaluation context:",this.context),this.flags.clear(),this.evaluatedFlags.clear(),this.evaluatedVariants.clear();for(let n of t.flags){this.flags.set(n.key,n);let i=W(n,this.context);if(this.evaluatedFlags.set(n.key,i),n.flag_type==="multivariate"&&n.variants){let o=Pe(n,this.context);this.evaluatedVariants.set(n.key,o),this.log(`Flag "${n.key}": ${i}, variant: ${o}`);}else this.log(`Flag "${n.key}": ${i}`);}}catch(e){throw this.log("Error fetching flags:",e),e}}getFlag(e,t=false){if(!this.initialized)return this.log(`Flag "${e}" requested before init, returning default:`,t),t;let n=this.evaluatedFlags.get(e);return n===void 0?(this.log(`Flag "${e}" not found, returning default:`,t),t):n}getVariant(e,t=null){if(!this.initialized)return this.log(`Variant "${e}" requested before init, returning default:`,t),t;let n=this.evaluatedVariants.get(e);return n===void 0?(this.log(`Variant "${e}" not found, returning default:`,t),t):n}getVariantPayload(e,t=null){let n=this.getVariant(e);if(!n)return t;let i=this.flags.get(e);return i?Ie(i,n)??t:t}getAllFlags(){let e={};for(let[t,n]of this.evaluatedFlags)e[t]=n;return e}hasFlag(e){return this.flags.has(e)}isInitialized(){return this.initialized}async waitForInit(){this.initialized||await this.init();}async refresh(){this.initialized=false,await this.init();}getContext(){return this.context}log(...e){this.config.debug&&console.log("[SitePong Flags]",...e);}};var oe="sitepong_session_id",X="sitepong_session_ts";var I=null,D=null;function Fe(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return (r==="x"?e:e&3|8).toString(16)})}function Ae(r){return Date.now()-r>18e5}function se(){if(typeof window<"u"&&typeof sessionStorage<"u")try{let r=sessionStorage.getItem(oe),e=sessionStorage.getItem(X);if(r&&e&&!Ae(parseInt(e,10)))return sessionStorage.setItem(X,String(Date.now())),r;let t=Fe();return sessionStorage.setItem(oe,t),sessionStorage.setItem(X,String(Date.now())),t}catch{return De()}return De()}function De(){return I&&D&&!Ae(D)?(D=Date.now(),I):(I=Fe(),D=Date.now(),I)}function ae(){if(typeof window<"u"&&typeof sessionStorage<"u")try{sessionStorage.removeItem(oe),sessionStorage.removeItem(X);}catch{}I=null,D=null;}var _e=["[data-sp-no-capture]",".sp-no-capture"];var F=class{constructor(e,t){this.clickHandler=null;this.submitHandler=null;this.active=false;this.config={clicks:true,forms:true,pageviews:true,blockSelectors:_e,maxTextLength:255,debug:false,...e},this.callback=t;}start(){this.active||typeof document>"u"||typeof document.addEventListener!="function"||(this.active=true,this.config.clicks&&this.setupClickCapture(),this.config.forms&&this.setupFormCapture(),this.log("Autocapture started"));}stop(){this.active&&(this.active=false,this.clickHandler&&(document.removeEventListener("click",this.clickHandler,true),this.clickHandler=null),this.submitHandler&&(document.removeEventListener("submit",this.submitHandler,true),this.submitHandler=null),this.log("Autocapture stopped"));}setupClickCapture(){this.clickHandler=e=>{let t=e.target;if(!t||!this.shouldCapture(t))return;let n=this.getElementProperties(t);n.$event_type="click",n.$x=e.clientX,n.$y=e.clientY,this.callback({type:"click",timestamp:new Date().toISOString(),properties:n});},document.addEventListener("click",this.clickHandler,true);}setupFormCapture(){this.submitHandler=e=>{let t=e.target;if(!t||!this.shouldCapture(t))return;let n={$event_type:"form_submit",$form_action:t.action||void 0,$form_method:t.method||"get",$form_name:t.name||t.id||void 0,$field_names:this.getFormFieldNames(t),$field_count:t.elements.length},i=this.getElementProperties(t);Object.assign(n,i),this.callback({type:"form_submit",timestamp:new Date().toISOString(),properties:n});},document.addEventListener("submit",this.submitHandler,true);}shouldCapture(e){let t=this.config.blockSelectors||_e;for(let n of t)if(e.matches(n)||e.closest(n))return false;return !(this.config.allowSelectors&&this.config.allowSelectors.length>0&&!this.config.allowSelectors.some(i=>e.matches(i)||e.closest(i)!==null)||e.offsetParent===null&&e.tagName!=="BODY")}getElementProperties(e){let t={};t.$tag_name=e.tagName.toLowerCase(),t.$el_id=e.id||void 0,e.classList.length>0&&(t.$el_classes=Array.from(e.classList).slice(0,5));let n=this.getElementText(e);n&&(t.$el_text=n),e instanceof HTMLAnchorElement&&(t.$href=e.href||void 0,t.$target=e.target||void 0),(e instanceof HTMLInputElement||e instanceof HTMLButtonElement)&&(t.$el_type=e.type||void 0,t.$el_name=e.name||void 0);let i=e.getAttribute("aria-label");i&&(t.$aria_label=this.truncate(i));let o=e.getAttribute("role");return o&&(t.$el_role=o),t.$selector=this.getSelector(e),t.$current_url=window.location.href,t.$pathname=window.location.pathname,t}getElementText(e){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)return;let t="";if(e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement)t=e.innerText||e.textContent||"";else for(let n of Array.from(e.childNodes))n.nodeType===Node.TEXT_NODE&&(t+=n.textContent||"");return t=t.trim().replace(/\s+/g," "),t?this.truncate(t):void 0}getFormFieldNames(e){let t=[];for(let n of Array.from(e.elements)){let i=n;i.name&&i.type!=="password"&&i.type!=="hidden"&&t.push(i.name);}return t.slice(0,20)}getSelector(e){let t=[],n=e,i=0;for(;n&&n!==document.body&&i<5;){let o=n.tagName.toLowerCase();if(n.id){o=`#${n.id}`,t.unshift(o);break}n.classList.length>0&&(o+=`.${Array.from(n.classList).slice(0,2).join(".")}`);let s=n.parentElement;if(s){let l=Array.from(s.children).filter(c=>c.tagName===n.tagName);if(l.length>1){let c=l.indexOf(n)+1;o+=`:nth-of-type(${c})`;}}t.unshift(o),n=n.parentElement,i++;}return t.join(" > ")}truncate(e){let t=this.config.maxTextLength||255;return e.length>t?e.slice(0,t)+"...":e}log(...e){this.config.debug&&console.log("[SitePong Autocapture]",...e);}};function le(){return typeof navigator<"u"&&navigator.product==="ReactNative"?"react-native":typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"&&typeof document<"u"?"browser":"unknown"}var Le=le();function ft(){return Le==="browser"}function E(){return Le==="react-native"}function ce(){return ft()&&typeof localStorage<"u"?{getItem:async r=>localStorage.getItem(r),setItem:async(r,e)=>localStorage.setItem(r,e),removeItem:async r=>localStorage.removeItem(r)}:null}var ht="https://ingest.sitepong.com",gt=20,mt=1e4,ue=3,M=class{constructor(e){this.eventQueue=[];this.flushTimer=null;this.flushFailures=0;this.disabled=false;this.userId=null;this.groupId=null;this.userTraits=null;this.groupTraits=null;this.lastUrl=null;this.popstateHandler=null;this.autocaptureModule=null;this.config={endpoint:ht,enabled:true,autocapturePageviews:false,maxBatchSize:gt,flushInterval:mt,debug:false,...e};}init(){this.config.enabled&&(this.startFlushTimer(),this.setupPageHideListener(),this.config.autocapturePageviews&&this.setupSPATracking(),this.setupAutocapture(),this.log("Analytics initialized"));}initHeadless(){this.config.enabled&&(this.startFlushTimer(),this.log("Analytics initialized (headless)"));}setupAutocapture(){let e=this.config.autocapture,t=this.config.autocaptureClicks,n=this.config.autocaptureForms,i=t||false,o=n||false,s,l;e===true?(i=true,o=true):e&&typeof e=="object"&&(i=e.clicks!==false,o=e.forms!==false,s=e.blockSelectors,l=e.allowSelectors,e.pageviews!==false&&!this.config.autocapturePageviews&&this.setupSPATracking()),!(!i&&!o)&&(this.autocaptureModule=new F({clicks:i,forms:o,pageviews:false,blockSelectors:s,allowSelectors:l,debug:this.config.debug},c=>{let d=c.type==="click"?"$autocapture_click":c.type==="form_submit"?"$autocapture_form_submit":"$autocapture";this.track(d,c.properties);}),this.autocaptureModule.start());}track(e,t){if(!this.config.enabled)return;let n=this.createEvent("track",{name:e,properties:t});this.enqueue(n),this.log("Track:",e,t);}trackPageView(e,t){if(!this.config.enabled)return;let n=e||(typeof window<"u"?window.location.href:void 0),i=this.createEvent("page",{properties:{url:n,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0,...t}});this.enqueue(i),this.log("Page view:",n);}identify(e,t){if(!this.config.enabled)return;this.userId=e,t&&(this.userTraits={...this.userTraits,...t});let n=this.createEvent("identify",{traits:this.userTraits||void 0});this.enqueue(n),this.log("Identify:",e,t);}group(e,t){if(!this.config.enabled)return;this.groupId=e,t&&(this.groupTraits={...this.groupTraits,...t});let n=this.createEvent("group",{traits:this.groupTraits||void 0});this.enqueue(n),this.log("Group:",e,t);}reset(){this.userId=null,this.groupId=null,this.userTraits=null,this.groupTraits=null,ae(),this.log("Analytics state reset");}async flush(){if(this.eventQueue.length===0)return;if(this.disabled){this.eventQueue=[];return}let e=[...this.eventQueue];this.eventQueue=[];let t=this.config.eventsEndpoint||`${this.config.endpoint}/api/events`;try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({events:e})});if(!n.ok)throw new Error(`HTTP ${n.status}`);this.flushFailures=0,this.log(`Flushed ${e.length} events`);}catch(n){if(this.flushFailures++,this.flushFailures>=ue){this.disabled=true,console.warn(`[SitePong Analytics] Disabled after ${ue} consecutive failures. Check that ${t} is accessible and has proper CORS headers.`);return}this.eventQueue.unshift(...e),this.log(`Failed to flush events (attempt ${this.flushFailures}/${ue}):`,n);}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.popstateHandler&&typeof window<"u"&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),this.autocaptureModule&&(this.autocaptureModule.stop(),this.autocaptureModule=null),this.flushWithBeacon();}createEvent(e,t){return {type:e,name:t.name,properties:t.properties,userId:this.userId||void 0,anonymousId:k(),deviceId:void 0,groupId:this.groupId||void 0,traits:t.traits,sessionId:se(),timestamp:new Date().toISOString(),url:typeof window<"u"?window.location.href:void 0,referrer:typeof document<"u"?document.referrer:void 0,userAgent:typeof navigator<"u"?navigator.userAgent:void 0}}enqueue(e){this.eventQueue.push(e),this.eventQueue.length>=this.config.maxBatchSize&&this.flush();}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval);}setupPageHideListener(){typeof window>"u"||E()||typeof window.addEventListener!="function"||window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushWithBeacon();});}flushWithBeacon(){if(this.eventQueue.length===0||E()||typeof navigator?.sendBeacon!="function")return;let e=[...this.eventQueue];this.eventQueue=[];let t=this.config.eventsEndpoint||`${this.config.endpoint}/api/events`,n=new Blob([JSON.stringify({events:e,apiKey:this.config.apiKey})],{type:"application/json"});navigator.sendBeacon(t,n),this.log(`Flushed ${e.length} events via beacon`);}setupSPATracking(){if(typeof window>"u"||E()||typeof window.addEventListener!="function")return;this.lastUrl=window.location.href,this.trackPageView(),this.popstateHandler=()=>{let n=window.location.href;n!==this.lastUrl&&(this.lastUrl=n,this.trackPageView(n));},window.addEventListener("popstate",this.popstateHandler);let e=history.pushState.bind(history),t=history.replaceState.bind(history);history.pushState=(...n)=>{e(...n),this.handleUrlChange();},history.replaceState=(...n)=>{t(...n),this.handleUrlChange();};}handleUrlChange(){if(typeof window>"u")return;let e=window.location.href;e!==this.lastUrl&&(this.lastUrl=e,this.trackPageView(e));}log(...e){this.config.debug&&console.log("[SitePong Analytics]",...e);}};function de(){let r={uaSpoofed:false,antiDetectBrowser:false,canvasNoise:false,canvasBlocked:false,webglSpoofed:false,webglBlocked:false,vmIndicators:[],platformMismatch:false,pluginAnomaly:false,featureAnomaly:false,geolocationSpoofed:false,mitmIndicators:[]},e=0,t=vt(r);e+=t;let n=yt(r);e+=n;let i=bt(r);e+=i;let o=wt(r);e+=o;let s=St(r);e+=s;let l=Tt(r);return e+=l,e=Math.min(e,1),{browserTampered:r.uaSpoofed||r.antiDetectBrowser||r.platformMismatch,canvasTampered:r.canvasNoise||r.canvasBlocked,webglTampered:r.webglSpoofed||r.webglBlocked,vmDetected:r.vmIndicators.length>=2,geolocationSpoofed:r.geolocationSpoofed,mitmDetected:r.mitmIndicators.length>=1,confidence:e,signals:r}}function vt(r){if(typeof navigator>"u"||typeof window>"u")return 0;let e=0,t=navigator.userAgent,n=navigator.platform||"",i=/Windows/.test(t),o=/Mac/.test(t),s=/Linux/.test(t)&&!/Android/.test(t),l=/Win/.test(n),c=/Mac/.test(n),d=/Linux/.test(n);(i&&!l||o&&!c||s&&!d)&&(r.platformMismatch=true,r.uaSpoofed=true,e+=.3);let f=/Chrome\/\d+/.test(t)&&!/Edge|OPR|Brave/.test(t);f&&!("chrome"in window||"CSS"in window&&"paintWorklet"in window.CSS)&&!("brave"in navigator)&&(r.uaSpoofed=true,e+=.2),/Firefox\/\d+/.test(t)&&!/Seamonkey/.test(t)&&("InstallTrigger"in window||CSS.supports("-moz-appearance","none")||(r.uaSpoofed=true,e+=.2));let u=navigator;if(u.userAgentData?.brands){let v=u.userAgentData.brands.map(T=>T.brand);(v.length===0||v.every(T=>T===""||T==="Not A;Brand"))&&(r.antiDetectBrowser=true,e+=.25);}/mobile|android|iphone|ipad/i.test(t)||(navigator.plugins?.length||0)===0&&f&&(r.pluginAnomaly=true,e+=.1);let p=navigator.hardwareConcurrency||0,g=navigator.deviceMemory||0;return p>0&&g>0&&p>=16&&g<=1&&(r.featureAnomaly=true,e+=.15),Math.min(e,.5)}function yt(r){if(typeof document>"u")return 0;let e=0;try{let t=document.createElement("canvas");t.width=100,t.height=20;let n=t.getContext("2d");if(!n)return r.canvasBlocked=!0,.1;n.fillStyle="#ff0000",n.fillRect(0,0,100,20),n.fillStyle="#00ff00",n.font="12px Arial",n.fillText("SitePong",5,14);let i=t.toDataURL();n.clearRect(0,0,100,20),n.fillStyle="#ff0000",n.fillRect(0,0,100,20),n.fillStyle="#00ff00",n.font="12px Arial",n.fillText("SitePong",5,14);let o=t.toDataURL();i!==o&&(r.canvasNoise=!0,e+=.35);let l=n.getImageData(0,0,100,20).data,c=!0,d=!0,f=l[0];for(let u=0;u<l.length;u+=4)(l[u]!==0||l[u+1]!==0||l[u+2]!==0)&&(c=!1),l[u]!==f&&(d=!1);(c||d)&&(r.canvasBlocked=!0,e+=.2);let h=Object.getOwnPropertyDescriptor(HTMLCanvasElement.prototype,"toDataURL");h&&h.value!==HTMLCanvasElement.prototype.toDataURL&&(r.canvasNoise=!0,e+=.3);}catch{r.canvasBlocked=true,e+=.1;}return Math.min(e,.4)}function bt(r){if(typeof document>"u")return 0;let e=0;try{let t=document.createElement("canvas"),n=t.getContext("webgl")||t.getContext("experimental-webgl");if(!n||!(n instanceof WebGLRenderingContext))return r.webglBlocked=!0,.1;let i=n.getExtension("WEBGL_debug_renderer_info");if(!i)return r.webglBlocked=!0,.1;let o=n.getParameter(i.UNMASKED_VENDOR_WEBGL),s=n.getParameter(i.UNMASKED_RENDERER_WEBGL),l=["Brian Paul","Mesa","VMware"];["llvmpipe","softpipe","Mesa","SwiftShader"].some(g=>s.includes(g))&&!l.some(g=>o.includes(g))&&(r.webglSpoofed=!0,e+=.25);let d=navigator.userAgent,f=/mobile|android|iphone|ipad/i.test(d),h=/GeForce|Radeon|Intel.*HD|GTX|RTX|Vega/i.test(s);f&&h&&(r.webglSpoofed=!0,e+=.3);let u=Object.getOwnPropertyDescriptor(WebGLRenderingContext.prototype,"getParameter");u&&typeof u.value=="function"&&(u.value.toString().includes("[native code]")||(r.webglSpoofed=!0,e+=.35)),(n.getSupportedExtensions()||[]).length<5&&h&&(r.webglSpoofed=!0,e+=.1);}catch{r.webglBlocked=true,e+=.1;}return Math.min(e,.4)}function wt(r){if(typeof navigator>"u"||typeof window>"u")return 0;let e=[],t=navigator.userAgent;try{let s=document.createElement("canvas"),l=s.getContext("webgl")||s.getContext("experimental-webgl");if(l&&l instanceof WebGLRenderingContext){let c=l.getExtension("WEBGL_debug_renderer_info");if(c){let d=l.getParameter(c.UNMASKED_RENDERER_WEBGL).toLowerCase(),f=l.getParameter(c.UNMASKED_VENDOR_WEBGL).toLowerCase(),h=["vmware","virtualbox","hyper-v","parallels","qemu","llvmpipe","mesa"],u=["vmware","innotek","microsoft basic","parallels"];for(let p of h)d.includes(p)&&e.push(`webgl_renderer:${p}`);for(let p of u)f.includes(p)&&e.push(`webgl_vendor:${p}`);}}}catch{}if(typeof screen<"u"){let s=screen.width,l=screen.height;[[800,600],[1024,768],[1280,800]].some(([d,f])=>s===d&&l===f)&&screen.colorDepth===24&&navigator.hardwareConcurrency<=2&&e.push("vm_resolution");}let n=navigator.hardwareConcurrency||0,i=navigator.deviceMemory||0;if(n>0&&n<=2&&i>0&&i<=2&&(/mobile|android|iphone/i.test(t)||e.push("low_hw_specs")),typeof performance<"u"){let s=[];for(let c=0;c<10;c++)s.push(performance.now());new Set(s.map(c=>Math.floor(c*1e3))).size<=3&&s.length===10&&e.push("coarse_timing");}if(typeof navigator<"u"){let s=navigator.connection;s&&s.downlink&&s.downlink>=10&&s.rtt&&s.rtt<=5&&e.push("cloud_vm_network");}return r.vmIndicators=e,Math.min(e.length*.15,.5)}function St(r){if(typeof navigator>"u")return 0;let e=0;if("geolocation"in navigator){let t=Object.getOwnPropertyDescriptor(navigator,"geolocation");t&&t.configurable===false&&t.get&&(t.get.toString().includes("[native code]")||(r.geolocationSpoofed=true,e+=.3));try{let n=Object.getOwnPropertyDescriptor(Geolocation.prototype,"getCurrentPosition");n?.value&&(n.value.toString().includes("[native code]")||(r.geolocationSpoofed=!0,e+=.3));}catch{}}if(typeof window<"u")try{let t=Object.getPrototypeOf(navigator),n=Object.getOwnPropertyDescriptor(t,"geolocation");n&&n.get&&!n.get.toString().includes("[native code]")&&(r.geolocationSpoofed=!0,e+=.2);}catch{}return Math.min(e,.4)}function Tt(r){if(typeof window>"u"||typeof document>"u")return 0;let e=[];if(window.location?.protocol==="https:"){let n=document.querySelectorAll("script[src]");for(let i=0;i<n.length;i++){let o=n[i].getAttribute("src")||"";if(o.startsWith("http://")&&!o.includes("localhost")){e.push("mixed_content_script");break}}}let t=document.querySelectorAll("iframe");for(let n=0;n<t.length;n++){let i=t[n].getAttribute("src")||"";if(i&&!i.startsWith(window.location?.origin||"")&&!i.startsWith("about:")&&!i.startsWith("javascript:")){let o=window.getComputedStyle(t[n]);(o.display==="none"||o.visibility==="hidden"||parseInt(o.width)<=1||parseInt(o.height)<=1)&&e.push("hidden_iframe");}}if("serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(n=>{for(let i of n){let o=i.active?.scriptURL||"";o&&!o.startsWith(window.location?.origin||"")&&e.push("foreign_service_worker");}}).catch(()=>{}),typeof performance<"u"&&performance.getEntriesByType)try{let n=performance.getEntriesByType("navigation")[0];if(n){let i=n.connectEnd-n.connectStart,o=n.requestStart-n.secureConnectionStart;i>1e3&&o>500&&e.push("slow_tls_handshake");}}catch{}if(window.location?.protocol==="https:"&&typeof performance<"u")try{let n=performance.getEntriesByType("resource");for(let i of n.slice(0,20))if(i.transferSize===0&&i.encodedBodySize>0&&!i.name.includes("cache")){e.push("intercepted_resource");break}}catch{}return r.mitmIndicators=e,Math.min(e.length*.2,.5)}function Oe(){return {userAgent:typeof navigator<"u"?navigator.userAgent:"",language:typeof navigator<"u"?navigator.language:"",languages:typeof navigator<"u"?Array.from(navigator.languages||[]):[],platform:typeof navigator<"u"&&navigator.platform||"",screenWidth:typeof screen<"u"?screen.width:0,screenHeight:typeof screen<"u"?screen.height:0,screenColorDepth:typeof screen<"u"?screen.colorDepth:0,devicePixelRatio:typeof window<"u"&&window.devicePixelRatio||1,timezoneOffset:new Date().getTimezoneOffset(),timezone:Intl?.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone||"",sessionStorage:xt(),localStorage:kt(),indexedDB:typeof indexedDB<"u",cookieEnabled:typeof navigator<"u"?navigator.cookieEnabled:false,hardwareConcurrency:typeof navigator<"u"&&navigator.hardwareConcurrency||0,maxTouchPoints:typeof navigator<"u"&&navigator.maxTouchPoints||0,deviceMemory:typeof navigator<"u"?navigator.deviceMemory:void 0}}async function Ne(){let r={};r.canvasFingerprint=Ct();let e=Et();return r.webglVendor=e.vendor,r.webglRenderer=e.renderer,r.audioFingerprint=await Mt(),r.fontFingerprint=Ot(),r.mathFingerprint=Nt(),r.webglRenderHash=Ht(),r.cssFeatureHash=Bt(),r.localIps=await Vt(),r}async function fe(r){let t={...Oe()};r&&(t.extended=await Ne());let n=Be();return t.smart=n,t.incognito=n.incognito,t.bot=n.bot,t}async function He(r){let e={userAgent:r.userAgent,language:r.language,languages:r.languages,platform:r.platform,screenWidth:r.screenWidth,screenHeight:r.screenHeight,screenColorDepth:r.screenColorDepth,devicePixelRatio:r.devicePixelRatio,timezoneOffset:r.timezoneOffset,timezone:r.timezone,hardwareConcurrency:r.hardwareConcurrency,maxTouchPoints:r.maxTouchPoints,deviceMemory:r.deviceMemory};return r.extended&&(e.canvasFingerprint=r.extended.canvasFingerprint,e.webglVendor=r.extended.webglVendor,e.webglRenderer=r.extended.webglRenderer,e.audioFingerprint=r.extended.audioFingerprint,e.fontFingerprint=r.extended.fontFingerprint,e.mathFingerprint=r.extended.mathFingerprint,e.webglRenderHash=r.extended.webglRenderHash,e.cssFeatureHash=r.extended.cssFeatureHash,e.localIps=r.extended.localIps),e}function Be(){let r={};r.incognito=Rt(),r.bot=Pt(),r.privacyBrowser=It(),r.devToolsOpen=Dt(),r.connectionType=Ft(),r.doNotTrack=At(),r.notificationsEnabled=_t();let e=Lt();r.deviceFirstSeen=e.firstSeen,r.deviceVisitCount=e.visitCount;let t=de();return r.browserTampered=t.browserTampered,r.canvasTampered=t.canvasTampered,r.webglTampered=t.webglTampered,r.vmDetected=t.vmDetected,r.vmIndicators=t.signals.vmIndicators,r}function xt(){try{let r="__sp_test__";return sessionStorage.setItem(r,"1"),sessionStorage.removeItem(r),!0}catch{return false}}function kt(){try{let r="__sp_test__";return localStorage.setItem(r,"1"),localStorage.removeItem(r),!0}catch{return false}}function Ct(){if(!(typeof document>"u"))try{let r=document.createElement("canvas"),e=r.getContext("2d");return e?(r.width=200,r.height=50,e.textBaseline="top",e.font="14px Arial",e.fillStyle="#f60",e.fillRect(0,0,200,50),e.fillStyle="#069",e.fillText("SitePong fingerprint",2,15),e.fillStyle="rgba(102, 204, 0, 0.7)",e.fillText("SitePong fingerprint",4,17),R(r.toDataURL())):void 0}catch{return}}function Et(){if(typeof document>"u")return {};try{let r=document.createElement("canvas"),e=r.getContext("webgl")||r.getContext("experimental-webgl");if(!e||!(e instanceof WebGLRenderingContext))return {};let t=e.getExtension("WEBGL_debug_renderer_info");return t?{vendor:e.getParameter(t.UNMASKED_VENDOR_WEBGL),renderer:e.getParameter(t.UNMASKED_RENDERER_WEBGL)}:{}}catch{return {}}}async function Mt(){if(!(typeof window>"u"||typeof OfflineAudioContext>"u"))try{let r=new OfflineAudioContext(1,4500,44100),e=r.createOscillator();e.type="triangle",e.frequency.setValueAtTime(1e4,r.currentTime);let t=r.createDynamicsCompressor();t.threshold.setValueAtTime(-50,r.currentTime),t.knee.setValueAtTime(40,r.currentTime),t.ratio.setValueAtTime(12,r.currentTime),t.attack.setValueAtTime(0,r.currentTime),t.release.setValueAtTime(.25,r.currentTime),e.connect(t),t.connect(r.destination),e.start(0);let i=(await r.startRendering()).getChannelData(0),o=0;for(let s=4e3;s<4500;s++)o+=Math.abs(i[s]);return R(`audio:${o.toFixed(6)}`)}catch{return}}function Rt(){if(typeof window>"u")return false;try{let r="__sp_incognito_test__";try{localStorage.setItem(r,new Array(100).join("x")),localStorage.removeItem(r);}catch{return !0}if(typeof indexedDB<"u")try{let t=indexedDB.open("__sp_test__");t.onerror=()=>{};}catch{return !0}if("webkitRequestFileSystem"in window){let t=!1;try{window.webkitRequestFileSystem(0,1,()=>{t=!1;},()=>{t=!0;});}catch{}if(t)return !0}let e=performance;if(e.memory){let t=e.memory.jsHeapSizeLimit||0;if(t>0&&t<1073741824)return !0}return !1}catch{return false}}function Pt(){if(typeof navigator>"u")return false;let r=navigator.userAgent.toLowerCase();return !!(["bot","crawler","spider","headless","phantom","puppeteer","selenium","webdriver","playwright"].some(t=>r.includes(t))||"webdriver"in navigator&&navigator.webdriver||navigator.plugins&&navigator.plugins.length===0&&!/mobile|android|iphone/i.test(r))}function It(){if(typeof navigator>"u")return false;let r=navigator.userAgent.toLowerCase();return !!("brave"in navigator||r.includes("focus")&&r.includes("firefox")||r.includes("duckduckgo")||typeof window<"u"&&(screen.width===1e3&&screen.height===1e3||new Date().getTimezoneOffset()===0&&navigator.language!=="en"))}function Dt(){if(typeof window>"u")return false;try{let r=window.outerWidth-window.innerWidth>160,e=window.outerHeight-window.innerHeight>160;if(r||e)return !0}catch{}return false}function Ft(){if(typeof navigator>"u")return;let r=navigator.connection;if(r)return r.effectiveType||r.type||void 0}function At(){if(typeof navigator>"u")return false;let r=navigator.doNotTrack;return r==="1"||r==="yes"}function _t(){return typeof Notification>"u"?false:Notification.permission==="granted"}function Lt(){let r="sitepong_device_age",e={visitCount:1};if(typeof localStorage>"u")return e;try{let t=localStorage.getItem(r);if(t){let n=JSON.parse(t);e.firstSeen=n.firstSeen,e.visitCount=(n.visitCount||0)+1;}else e.firstSeen=new Date().toISOString();localStorage.setItem(r,JSON.stringify({firstSeen:e.firstSeen,visitCount:e.visitCount}));}catch{}return e}function Ot(){if(!(typeof document>"u"))try{let r=["monospace","sans-serif","serif"],e=["Arial","Arial Black","Courier New","Georgia","Helvetica","Impact","Lucida Console","Lucida Sans Unicode","Palatino Linotype","Tahoma","Times New Roman","Trebuchet MS","Verdana","Comic Sans MS","Courier","Garamond","Monaco"],t="mmmmmmmmmmlli",n="72px",o=document.createElement("canvas").getContext("2d");if(!o)return;let s={};for(let c of r)o.font=`${n} ${c}`,s[c]=o.measureText(t).width;let l=[];for(let c of e)for(let d of r)if(o.font=`${n} '${c}', ${d}`,o.measureText(t).width!==s[d]){l.push(c);break}return R(l.join(","))}catch{return}}function Nt(){try{let r=[Math.tan(-1e300),Math.log(1e-10),Math.pow(Math.PI,-100),Math.acos(.5),Math.atan2(1,1),Math.exp(1),Math.sinh(1)];return R(r.map(e=>e.toString()).join(","))}catch{return}}function Ht(){if(!(typeof document>"u"))try{let r=document.createElement("canvas");r.width=50,r.height=50;let e=r.getContext("webgl");if(!e)return;let t=e.createShader(e.VERTEX_SHADER);e.shaderSource(t,"attribute vec2 p;void main(){gl_Position=vec4(p,0,1);}"),e.compileShader(t);let n=e.createShader(e.FRAGMENT_SHADER);e.shaderSource(n,"precision mediump float;void main(){gl_FragColor=vec4(.86,.27,.33,1);}"),e.compileShader(n);let i=e.createProgram();e.attachShader(i,t),e.attachShader(i,n),e.linkProgram(i),e.useProgram(i);let o=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,o),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,.5,-.5,-.5,.5,-.5]),e.STATIC_DRAW);let s=e.getAttribLocation(i,"p");return e.enableVertexAttribArray(s),e.vertexAttribPointer(s,2,e.FLOAT,!1,0,0),e.clearColor(0,0,0,1),e.clear(e.COLOR_BUFFER_BIT),e.drawArrays(e.TRIANGLES,0,3),R(r.toDataURL())}catch{return}}function Bt(){if(!(typeof CSS>"u"||typeof CSS.supports!="function"))try{let e=["display: grid","display: flex","display: contents","position: sticky","backdrop-filter: blur(1px)","gap: 1px","aspect-ratio: 1","contain: paint","overflow: clip","accent-color: red","color: oklch(0.5 0.2 0)","container-type: inline-size","text-wrap: balance","view-transition-name: x","anchor-name: --x","field-sizing: content"].map(t=>CSS.supports(t)?"1":"0").join("");return R(e)}catch{return}}async function Vt(){if(!(typeof window>"u"||typeof RTCPeerConnection>"u"))try{let r=new Set,e=new RTCPeerConnection({iceServers:[]});e.createDataChannel("");let t=await e.createOffer();return await e.setLocalDescription(t),new Promise(n=>{let i=setTimeout(()=>{e.close(),n(r.size>0?Array.from(r):void 0);},1e3);e.onicecandidate=o=>{if(!o.candidate){clearTimeout(i),e.close(),n(r.size>0?Array.from(r):void 0);return}let s=o.candidate.candidate.match(/([0-9]{1,3}\.([0-9]{1,3}\.){2}[0-9]{1,3})/);s&&s[1]&&!s[1].startsWith("0.")&&r.add(s[1]);};})}catch{return}}function R(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);e=(e<<5)-e+n,e=e&e;}return Math.abs(e).toString(16)}var A=class{constructor(){this.mousePoints=[];this.keyDownTimes=new Map;this.keyIntervals=[];this.keyHoldTimes=[];this.lastKeyTime=0;this.scrollEvents=[];this.clickTimes=[];this.running=false;this.maxSamples=500;this.handleMouseMove=e=>{this.mousePoints.length>=this.maxSamples||this.mousePoints.push({x:e.clientX,y:e.clientY,t:Date.now()});};this.handleKeyDown=e=>{if(this.keyIntervals.length>=this.maxSamples)return;let t=Date.now();this.keyDownTimes.set(e.key,t),this.lastKeyTime>0&&this.keyIntervals.push(t-this.lastKeyTime),this.lastKeyTime=t;};this.handleKeyUp=e=>{let t=this.keyDownTimes.get(e.key);t&&(this.keyHoldTimes.push(Date.now()-t),this.keyDownTimes.delete(e.key));};this.handleScroll=()=>{this.scrollEvents.length>=this.maxSamples||this.scrollEvents.push({deltaY:window.scrollY,t:Date.now()});};this.handleClick=()=>{this.clickTimes.length>=this.maxSamples||this.clickTimes.push(Date.now());};}start(){this.running||typeof window>"u"||typeof window.addEventListener!="function"||(this.running=true,window.addEventListener("mousemove",this.handleMouseMove,{passive:true}),window.addEventListener("keydown",this.handleKeyDown,{passive:true}),window.addEventListener("keyup",this.handleKeyUp,{passive:true}),window.addEventListener("scroll",this.handleScroll,{passive:true}),window.addEventListener("click",this.handleClick,{passive:true}));}stop(){!this.running||typeof window>"u"||typeof window.removeEventListener!="function"||(this.running=false,window.removeEventListener("mousemove",this.handleMouseMove),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),window.removeEventListener("scroll",this.handleScroll),window.removeEventListener("click",this.handleClick));}getMetrics(){let e=this.analyzeMouseMovement(),t=this.analyzeKeyboard(),n=this.analyzeScroll(),i=this.analyzeClicks(),o=this.calculateHumanScore(e,t,n,i);return {mouse:e,keyboard:t,scroll:n,clicks:i,score:o}}reset(){this.mousePoints=[],this.keyDownTimes.clear(),this.keyIntervals=[],this.keyHoldTimes=[],this.lastKeyTime=0,this.scrollEvents=[],this.clickTimes=[];}analyzeMouseMovement(){if(this.mousePoints.length<3)return {totalMovements:this.mousePoints.length,averageSpeed:0,maxSpeed:0,averageAcceleration:0,straightLineRatio:0,jitter:0,hasMovement:false};let e=[],t=[],n=0,i=0,o=0;for(let d=1;d<this.mousePoints.length;d++){let f=this.mousePoints[d-1],h=this.mousePoints[d],u=h.t-f.t||1,p=h.x-f.x,g=h.y-f.y,v=Math.sqrt(p*p+g*g),T=v/u;if(e.push(T),v<3&&v>0&&o++,d>=2){let b=this.mousePoints[d-2],tt=b.x+(h.x-b.x)*((f.t-b.t)/(h.t-b.t)),nt=b.y+(h.y-b.y)*((f.t-b.t)/(h.t-b.t)),rt=Math.sqrt((f.x-tt)**2+(f.y-nt)**2);i++,rt<2&&n++;}if(d>=2){let b=e[e.length-2]||0;t.push(Math.abs(T-b)/u);}}let s=e.reduce((d,f)=>d+f,0)/e.length,l=Math.max(...e),c=t.length>0?t.reduce((d,f)=>d+f,0)/t.length:0;return {totalMovements:this.mousePoints.length,averageSpeed:Math.round(s*1e3)/1e3,maxSpeed:Math.round(l*1e3)/1e3,averageAcceleration:Math.round(c*1e3)/1e3,straightLineRatio:i>0?n/i:0,jitter:this.mousePoints.length>0?o/this.mousePoints.length:0,hasMovement:true}}analyzeKeyboard(){if(this.keyIntervals.length<2)return {totalKeystrokes:this.keyIntervals.length,averageInterval:0,intervalVariance:0,holdTimeAverage:0,holdTimeVariance:0,hasKeystrokes:false};let e=this.keyIntervals.reduce((o,s)=>o+s,0)/this.keyIntervals.length,t=this.variance(this.keyIntervals),n=this.keyHoldTimes.length>0?this.keyHoldTimes.reduce((o,s)=>o+s,0)/this.keyHoldTimes.length:0,i=this.keyHoldTimes.length>0?this.variance(this.keyHoldTimes):0;return {totalKeystrokes:this.keyIntervals.length+1,averageInterval:Math.round(e),intervalVariance:Math.round(t),holdTimeAverage:Math.round(n),holdTimeVariance:Math.round(i),hasKeystrokes:true}}analyzeScroll(){if(this.scrollEvents.length<2)return {totalScrolls:this.scrollEvents.length,averageSpeed:0,smoothness:0,hasScroll:false};let e=[];for(let s=1;s<this.scrollEvents.length;s++){let l=this.scrollEvents[s].t-this.scrollEvents[s-1].t||1,c=Math.abs(this.scrollEvents[s].deltaY-this.scrollEvents[s-1].deltaY);e.push(c/l);}let n=e.reduce((s,l)=>s+l,0)/e.length,i=this.variance(e),o=n>0?Math.min(1,n/(i+n)):0;return {totalScrolls:this.scrollEvents.length,averageSpeed:Math.round(n*100)/100,smoothness:Math.round(o*100)/100,hasScroll:true}}analyzeClicks(){if(this.clickTimes.length<2)return {totalClicks:this.clickTimes.length,averageInterval:0,intervalVariance:0,doubleClickCount:0,hasClicks:this.clickTimes.length>0};let e=[],t=0;for(let o=1;o<this.clickTimes.length;o++){let s=this.clickTimes[o]-this.clickTimes[o-1];e.push(s),s<500&&t++;}let n=e.reduce((o,s)=>o+s,0)/e.length,i=this.variance(e);return {totalClicks:this.clickTimes.length,averageInterval:Math.round(n),intervalVariance:Math.round(i),doubleClickCount:t,hasClicks:true}}calculateHumanScore(e,t,n,i){let o=.5,s=0;if(e.hasMovement){s++;let l=.5;e.jitter>.05&&(l+=.15),e.straightLineRatio<.5?l+=.15:e.straightLineRatio>.9&&(l-=.2),e.averageSpeed>0&&e.maxSpeed/e.averageSpeed>3&&(l+=.1),e.averageAcceleration>0&&(l+=.1),o+=Math.max(0,Math.min(1,l))-.5;}if(t.hasKeystrokes){s++;let l=.5;t.intervalVariance>1e3?l+=.2:t.intervalVariance<100&&(l-=.2),(t.averageInterval>0?Math.sqrt(t.intervalVariance)/t.averageInterval:0)>.3&&(l+=.15),t.holdTimeVariance>500&&(l+=.1),o+=Math.max(0,Math.min(1,l))-.5;}if(n.hasScroll){s++;let l=.5;n.smoothness>.3&&n.smoothness<.9&&(l+=.2),o+=Math.max(0,Math.min(1,l))-.5;}if(i.hasClicks){s++;let l=.5;i.intervalVariance>5e4?l+=.15:i.intervalVariance<100&&(l-=.2),o+=Math.max(0,Math.min(1,l))-.5;}return s===0?.3:Math.max(0,Math.min(1,o))}variance(e){if(e.length<2)return 0;let t=e.reduce((n,i)=>n+i,0)/e.length;return e.reduce((n,i)=>n+(i-t)**2,0)/(e.length-1)}};async function pe(){let r={webrtcLeak:null,timezoneIPMismatch:false,dnsLeak:null,connectionType:null,multipleIPs:false,torBrowser:false,knownVPNExtension:false},e=0,t=false,n=false,i=false;r.torBrowser=Ut(),r.torBrowser&&(i=true,e+=.9);try{r.webrtcLeak=await $t(),r.webrtcLeak&&(t=!0,e+=.3);}catch{r.webrtcLeak=null;}r.connectionType=zt(),(r.connectionType==="unknown"||r.connectionType===null)&&(e+=.05),r.knownVPNExtension=Kt(),r.knownVPNExtension&&(t=true,e+=.4);let o=Intl.DateTimeFormat().resolvedOptions().timeZone,s=navigator.language;if(o&&s){let l=qt(o),c=s.split("-")[1]?.toUpperCase();l&&c&&l!==c&&(r.timezoneIPMismatch=true,e+=.1);}return e=Math.min(e,1),e<.3&&(t=false,n=false),{vpnDetected:t,proxyDetected:n,torDetected:i,confidence:e,signals:r}}function Ut(){if(typeof window>"u")return false;let r=[];r.push(window.screen.width===1e3&&window.screen.height===1e3),r.push(!window.MediaDevices),r.push(navigator.plugins.length===0),r.push(new Date().getTimezoneOffset()===0);let e=navigator.userAgent;return r.push(e.includes("Firefox")&&!e.includes("Chrome")),r.filter(Boolean).length>=3}async function $t(){return typeof window>"u"||!window.RTCPeerConnection?false:new Promise(r=>{let e=setTimeout(()=>r(false),3e3),t=new Set;try{let n=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]});n.createDataChannel(""),n.onicecandidate=i=>{if(!i.candidate){clearTimeout(e),n.close(),r(t.size>1);return}let s=i.candidate.candidate.match(/(\d{1,3}\.){3}\d{1,3}/);s&&t.add(s[0]);},n.createOffer().then(i=>n.setLocalDescription(i)).catch(()=>{clearTimeout(e),r(!1);});}catch{clearTimeout(e),r(false);}})}function zt(){if(typeof navigator>"u")return null;let r=navigator;return r.connection&&(r.connection.type||r.connection.effectiveType)||null}function Kt(){if(typeof document>"u"||!document.body)return false;let e=["[data-windscribe]","[data-nord]",".surfshark-extension","#vpn-indicator","[data-expressvpn]"];for(let t of e)try{if(document.querySelector(t))return !0}catch{}return false}function qt(r){return {"America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","Europe/London":"GB","Europe/Paris":"FR","Europe/Berlin":"DE","Europe/Madrid":"ES","Europe/Rome":"IT","Asia/Tokyo":"JP","Asia/Shanghai":"CN","Asia/Kolkata":"IN","Asia/Seoul":"KR","Australia/Sydney":"AU","America/Toronto":"CA","America/Sao_Paulo":"BR","America/Mexico_City":"MX"}[r]||null}var Wt="https://ingest.sitepong.com",he="sitepong_visitor",Ve=720*60*60*1e3,Ue="__sp_vid",Xt=63072e3,_=class{constructor(e){this.cachedVisitor=null;this.pendingRequest=null;this.config={endpoint:Wt,enabled:true,debug:false,...e},this.behaviorAnalyzer=new A,this.config.enabled&&typeof window<"u"&&typeof window.addEventListener=="function"&&this.behaviorAnalyzer.start(),this.loadFromStorage();}async getVisitorId(){if(!this.config.enabled)throw new Error("Fingerprint is not enabled");if(this.cachedVisitor&&!this.isCacheExpired())return this.log("Returning cached visitor ID:",this.cachedVisitor.result.visitorId),this.cachedVisitor.result;if(this.pendingRequest)return this.pendingRequest;this.pendingRequest=this.fetchVisitorId();try{return await this.pendingRequest}finally{this.pendingRequest=null;}}async getDeviceSignals(){return fe(this.config.extendedSignals??false)}async getFraudCheck(){let[e,t,n]=await Promise.all([this.getVisitorId(),this.getDeviceSignals(),pe().catch(()=>null)]),i=this.behaviorAnalyzer.getMetrics();t.behavior={score:i.score,mouseMovements:i.mouse.totalMovements,keystrokes:i.keyboard.totalKeystrokes,scrolls:i.scroll.totalScrolls,clicks:i.clicks.totalClicks,isHuman:i.score>.6};let o=n?.vpnDetected||n?.torDetected||false;return {visitorId:e.visitorId,riskScore:this.calculateRiskScore(t,o),signals:t,flags:{incognito:t.smart?.incognito||t.incognito,bot:t.smart?.bot||t.bot||!t.behavior.isHuman,vpn:o||t.smart?.timezoneMismatch,tampered:t.smart?.privacyBrowser}}}stopBehaviorTracking(){this.behaviorAnalyzer.stop();}async fetchVisitorId(){let e=await this.getDeviceSignals(),t=await He(e),n=this.config.visitorEndpoint||`${this.config.endpoint}/api/visitors`,i=this.getCookieVisitorId()||this.cachedVisitor?.result.visitorId||void 0;try{let o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},credentials:"include",body:JSON.stringify({signals:e,stableFingerprint:t,previousVisitorId:i})});if(!o.ok)throw new Error(`HTTP ${o.status}`);let s=await o.json();return this.cachedVisitor={result:s,signals:e,cachedAt:Date.now()},this.saveToStorage(),this.setCookieVisitorId(s.visitorId),this.log("Visitor ID fetched:",s.visitorId),s}catch(o){throw this.log("Failed to fetch visitor ID:",o),o}}calculateRiskScore(e,t=false){let n=0,i=e.smart;return (i?.bot||e.bot)&&(n+=.8),e.behavior&&(e.behavior.score<.3?n+=.4:e.behavior.score<.5&&(n+=.2)),t&&(n+=.25),(i?.incognito||e.incognito)&&(n+=.2),i?.devToolsOpen&&(n+=.1),i?.privacyBrowser&&(n+=.1),e.hardwareConcurrency===0&&(n+=.1),e.maxTouchPoints===0&&/mobile|android|iphone/i.test(e.userAgent)&&(n+=.15),e.cookieEnabled||(n+=.1),i?.doNotTrack&&(n+=.05),i?.deviceVisitCount===1&&(n+=.05),Math.round(Math.min(n,1)*100)/100}isCacheExpired(){return this.cachedVisitor?Date.now()-this.cachedVisitor.cachedAt>Ve:true}loadFromStorage(){if(!(typeof window>"u"||typeof localStorage>"u"))try{let e=localStorage.getItem(he);if(!e)return;let t=JSON.parse(e);this.isCacheExpiredAt(t.cachedAt)?localStorage.removeItem(he):(this.cachedVisitor=t,this.log("Loaded cached visitor from storage"));}catch{}}saveToStorage(){if(!(typeof window>"u"||typeof localStorage>"u")&&this.cachedVisitor)try{localStorage.setItem(he,JSON.stringify(this.cachedVisitor));}catch{}}isCacheExpiredAt(e){return Date.now()-e>Ve}getCookieVisitorId(){if(!(typeof document>"u"))try{return document.cookie.match(new RegExp(`(?:^|; )${Ue}=([^;]*)`))?.[1]||void 0}catch{return}}setCookieVisitorId(e){if(!(typeof document>"u"))try{document.cookie=`${Ue}=${e}; path=/; max-age=${Xt}; SameSite=Lax`;}catch{}}log(...e){this.config.debug&&console.log("[SitePong Fingerprint]",...e);}};var Ke=0,$e=new WeakMap;function Gt(){Ke=0;}function y(r){let e=$e.get(r);return e===void 0&&(e=++Ke,$e.set(r,e)),e}var qe=new Set(["script","noscript"]),jt=new Set(["src","href","action","poster"]),We=["display","visibility","opacity","position","top","right","bottom","left","z-index","float","clear","width","height","min-width","min-height","max-width","max-height","margin-top","margin-right","margin-bottom","margin-left","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-top-style","border-right-style","border-bottom-style","border-left-style","border-top-color","border-right-color","border-bottom-color","border-left-color","border-radius","background-color","background-image","background-size","background-position","color","font-family","font-size","font-weight","font-style","line-height","letter-spacing","text-align","text-decoration","text-transform","overflow","overflow-x","overflow-y","flex-direction","flex-wrap","justify-content","align-items","align-self","flex-grow","flex-shrink","flex-basis","gap","grid-template-columns","grid-template-rows","transform","box-shadow","text-shadow","cursor","white-space","word-break","box-sizing"],L=null,w=null;function Qt(r){if(typeof document>"u")return {};L||(L=new Map);let e=L.get(r);if(e)return e;try{w||(w=document.createElement("iframe"),w.style.cssText="position:fixed;top:-9999px;left:-9999px;width:0;height:0;border:none;visibility:hidden;",document.body.appendChild(w));let t=w.contentDocument;if(!t)return {};let n=t.createElement(r);t.body.appendChild(n);let i=t.defaultView.getComputedStyle(n),o={};for(let s of We)o[s]=i.getPropertyValue(s);return t.body.removeChild(n),L.set(r,o),o}catch{return {}}}function ge(r){if(typeof window>"u")return null;try{let e=r.tagName.toLowerCase();if(qe.has(e)||e==="head"||e==="html"||e==="meta"||e==="link"||e==="title")return null;let t=window.getComputedStyle(r),n=Qt(e),i=[];for(let o of We){let s=t.getPropertyValue(o);s&&s!==n[o]&&i.push(`${o}:${s}`);}return i.length>0?i.join(";"):null}catch{return null}}var x=new Map;async function Xe(r){if(x.has(r))return x.get(r)??null;try{let e=await fetch(r,{mode:"cors"});if(!e.ok)return x.set(r,null),null;let t=await e.text(),n=j(t,r);return x.set(r,n),n}catch{return x.set(r,null),null}}function Yt(r){return x.get(r)??null}function Ge(){w&&w.parentNode&&w.parentNode.removeChild(w),w=null,L=null,x.clear();}function je(r,e){if(!r||r.startsWith("data:")||r.startsWith("blob:")||r.startsWith("#"))return r;try{return new URL(r,e).href}catch{return r}}function j(r,e){return r.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(t,n,i)=>{let o=i.trim();if(o.startsWith("data:")||o.startsWith("blob:")||o.startsWith("http://")||o.startsWith("https://")||o.startsWith("//"))return `url(${n}${o}${n})`;try{let s=new URL(o,e).href;return `url(${n}${s}${n})`}catch{return `url(${n}${o}${n})`}})}function ze(r){try{let e=r.cssRules,t="";for(let n=0;n<e.length;n++)t+=e[n].cssText+`
|
|
2
|
+
`;return t}catch{return null}}function Q(r){let e=r.tagName.toLowerCase(),t=location.href;if(e==="style"){let n=r;if(n.sheet){let o=ze(n.sheet);if(o!==null)return j(o,t)}let i=r.textContent||"";return i?j(i,t):null}if(e==="link"){let n=r;if(n.rel!=="stylesheet")return null;let i=n.href||t;if(n.sheet){let o=ze(n.sheet);if(o!==null)return j(o,i)}if(n.href){let o=Yt(n.href);if(o)return o}return null}return null}function Jt(r,e){return r.split(",").map(t=>{let n=t.trim().split(/\s+/);return n[0]&&(n[0]=je(n[0],e)),n.join(" ")}).join(", ")}function Y(r,e,t=false){let n=y(r);if(r.nodeType===Node.TEXT_NODE){let i=r.parentElement,o=r.textContent||"";return i&&e.maskSelector&&i.matches(e.maskSelector)&&(o=o.replace(/\S/g,"*")),{id:n,type:"text",textContent:o}}if(r.nodeType===Node.COMMENT_NODE)return {id:n,type:"comment",textContent:""};if(r.nodeType===Node.ELEMENT_NODE){let i=r,o=i;if(e.blockSelector&&i.matches(e.blockSelector))return {id:n,type:"element",tagName:"div",attributes:{"data-blocked":"true",style:`width:${o.offsetWidth}px;height:${o.offsetHeight}px;background:#f0f0f0;`}};let s=i.tagName.toLowerCase();if(qe.has(s))return null;let l=t||s==="svg"||i instanceof SVGElement,c={},d=location.href;for(let u=0;u<i.attributes.length;u++){let p=i.attributes[u],g=p.name,v=p.value;g.startsWith("on")||v&&v.toLowerCase().startsWith("javascript:")||(jt.has(g)&&(v=je(v,d)),g==="srcset"&&(v=Jt(v,d)),c[g]=v);}if(s==="style"||s==="link"&&i.getAttribute("rel")==="stylesheet"){let u=Q(i);u&&(c._cssText=u);}if(!l&&s!=="style"&&s!=="link"){let u=ge(i);u&&(c._computedStyle=u);}if(s==="input"){let u=i,p=(u.type||"").toLowerCase();if(p==="checkbox"||p==="radio")c._checked=String(u.checked);else {let g=e.maskInputs?"***":u.value;g&&(c._value=g);}}else if(s==="textarea"){let u=i,p=e.maskInputs?"***":u.value;p&&(c._value=p);}else if(s==="select"){let u=i;c._selectedIndex=String(u.selectedIndex);}if(s==="canvas")try{let p=i.toDataURL("image/webp",.4);p&&p!=="data:,"&&(c._canvasDataUrl=p);}catch{}e.maskSelector&&i.matches(e.maskSelector);let f=[];for(let u of Array.from(i.childNodes)){let p=Y(u,e,l);p&&f.push(p);}let h={id:n,type:"element",tagName:s,attributes:Object.keys(c).length>0?c:void 0,children:f.length>0?f:void 0};return l&&(h.isSVG=true),h}return null}function J(r){if(typeof document>"u")return null;Gt();let e=Y(document.documentElement,r);return e?{_version:2,doctype:document.doctype?`<!DOCTYPE ${document.doctype.name}>`:void 0,html:e,width:window.innerWidth,height:window.innerHeight}:null}var Z=["authorization","cookie","set-cookie","x-api-key","x-auth-token"],O=class{constructor(e,t){this.originalFetch=null;this.originalXhrOpen=null;this.originalXhrSend=null;this.active=false;this.callback=e,this.captureHeaders=t?.captureHeaders??false,this.urlFilter=t?.urlFilter;}start(){this.active||typeof window>"u"||(this.active=true,this.interceptFetch(),this.interceptXHR());}stop(){this.active&&(this.active=false,this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXhrOpen&&(XMLHttpRequest.prototype.open=this.originalXhrOpen,this.originalXhrOpen=null),this.originalXhrSend&&(XMLHttpRequest.prototype.send=this.originalXhrSend,this.originalXhrSend=null));}interceptFetch(){if(typeof window.fetch!="function")return;this.originalFetch=window.fetch;let e=this;window.fetch=async function(t,n){let i=typeof t=="string"?t:t instanceof URL?t.toString():t.url;if(e.urlFilter&&!e.urlFilter(i))return e.originalFetch.call(window,t,n);let o=Date.now(),s=n?.method||(t instanceof Request?t.method:"GET"),l;n?.body&&(typeof n.body=="string"?l=n.body.length:n.body instanceof Blob&&(l=n.body.size));try{let c=await e.originalFetch.call(window,t,n),d=Date.now()-o,f={method:s.toUpperCase(),url:e.truncateUrl(i),status:c.status,statusText:c.statusText,duration:d,requestSize:l,initiator:"fetch"};return e.captureHeaders&&(f.requestHeaders=e.safeHeaders(n?.headers),f.responseHeaders=e.headersToObject(c.headers)),e.emit(f),c}catch(c){let d=Date.now()-o;throw e.emit({method:s.toUpperCase(),url:e.truncateUrl(i),duration:d,requestSize:l,error:c instanceof Error?c.message:"Network error",initiator:"fetch"}),c}};}interceptXHR(){if(typeof XMLHttpRequest>"u")return;this.originalXhrOpen=XMLHttpRequest.prototype.open,this.originalXhrSend=XMLHttpRequest.prototype.send;let e=this;XMLHttpRequest.prototype.open=function(t,n,...i){return this._spMethod=t,this._spUrl=typeof n=="string"?n:n.toString(),e.originalXhrOpen.apply(this,[t,n,...i])},XMLHttpRequest.prototype.send=function(t){let n=this,i=n._spUrl;if(e.urlFilter&&!e.urlFilter(i))return e.originalXhrSend.call(this,t);let o=Date.now(),s;typeof t=="string"&&(s=t.length);let l=()=>{let c=Date.now()-o,d;try{n.responseType===""||n.responseType==="text"?d=n.responseText?.length:n.responseType==="json"&&n.response!=null?d=JSON.stringify(n.response).length:n.responseType==="arraybuffer"&&n.response?d=n.response.byteLength:n.responseType==="blob"&&n.response&&(d=n.response.size);}catch{}let f={method:(n._spMethod||"GET").toUpperCase(),url:e.truncateUrl(i),status:n.status,statusText:n.statusText,duration:c,requestSize:s,responseSize:d,initiator:"xhr"};n.status===0&&(f.error="Network error"),e.emit(f),n.removeEventListener("loadend",l);};return n.addEventListener("loadend",l),e.originalXhrSend.call(this,t)};}emit(e){this.active&&this.callback({type:"network",timestamp:Date.now(),data:e});}truncateUrl(e){try{let t=new URL(e,window.location.origin),n=t.pathname+t.search;return n.length>500?n.slice(0,500)+"...":t.origin+n}catch{return e.length>500?e.slice(0,500)+"...":e}}safeHeaders(e){if(!e)return;let t={};if(e instanceof Headers)e.forEach((n,i)=>{t[i]=Z.includes(i.toLowerCase())?"[REDACTED]":n;});else if(Array.isArray(e))for(let[n,i]of e)t[n]=Z.includes(n.toLowerCase())?"[REDACTED]":i;else for(let[n,i]of Object.entries(e))t[n]=Z.includes(n.toLowerCase())?"[REDACTED]":i;return t}headersToObject(e){let t={};return e.forEach((n,i)=>{t[i]=Z.includes(i.toLowerCase())?"[REDACTED]":n;}),t}};var N=class{constructor(e,t){this.originals={};this.active=false;this.callback=e,this.levels=t?.levels||["log","info","warn","error","debug"];}start(){if(!(this.active||typeof console>"u")){this.active=true;for(let e of this.levels)this.originals[e]=console[e].bind(console),console[e]=(...t)=>{this.originals[e](...t),this.record(e,t);};}}stop(){if(this.active){this.active=false;for(let e of this.levels)this.originals[e]&&(console[e]=this.originals[e]);this.originals={};}}record(e,t){if(!this.active||t.length>0&&typeof t[0]=="string"&&t[0].startsWith("[SitePong"))return;let n=t.slice(0,10).map(o=>this.serialize(o)),i={level:e,args:n};if(e==="error"){let o=this.getStackTrace();o&&(i.trace=o.slice(0,2e3));}this.callback({type:"console",timestamp:Date.now(),data:i});}serialize(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof Error)return `Error: ${e.message}${e.stack?`
|
|
3
3
|
`+e.stack:""}`.slice(0,1e3);if(typeof e=="string")return e.slice(0,1e3);if(typeof e=="number"||typeof e=="boolean")return String(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof HTMLElement)return `<${e.tagName.toLowerCase()}${e.id?"#"+e.id:""}${e.className?"."+e.className.split(" ").join("."):""}>`;try{let t=JSON.stringify(e,this.getReplacer(),0);return t?t.slice(0,1e3):String(e)}catch{return String(e).slice(0,1e3)}}getReplacer(){let e=new WeakSet;return (t,n)=>{if(typeof n=="object"&&n!==null){if(e.has(n))return "[Circular]";e.add(n);}return typeof n=="function"?"[Function]":n instanceof RegExp?n.toString():n}}getStackTrace(){try{let e=new Error;return e.stack&&e.stack.split(`
|
|
4
4
|
`).slice(4).join(`
|
|
5
|
-
`)||void 0}catch{return}}};});var sr,ar,cr,Ve,lr,W,_t=h(()=>{Dt();Ne();He();sr="https://ingest.sitepong.com",ar=2e4,cr=3600*1e3,Ve=3,lr=5e3,W=class{constructor(e){this.recording=false;this.sessionId=null;this.events=[];this.trimTimer=null;this.flushFailures=0;this.disabled=false;this.sessionStartTime=0;this.observer=null;this.mouseMoveBuffer=[];this.mouseMoveFlushTimer=null;this.cleanupFns=[];this.networkRecorder=null;this.consoleRecorder=null;this.lastSnapshotTime=0;this.snapshotCooldown=500;this.userContext=null;this.mutationBuffer=null;this.mutationFlushTimer=null;this.lastScrollTime=0;this.latestSnapshot=null;this.config={endpoint:sr,enabled:true,maskInputs:true,maxSessionDuration:cr,flushInterval:5e3,maxBatchSize:100,sampleRate:1,debug:false,bufferDuration:ar,...e};}start(){if(typeof window>"u"||typeof document>"u"||typeof window.addEventListener!="function")return false;if(this.recording)return true;if(!this.config.enabled)return false;if(Math.random()>this.config.sampleRate)return this.log("Session not sampled"),false;this.sessionId=this.getOrCreateSessionId(),this.sessionStartTime=this.getOrCreateStartTime(),this.recording=true,this.events=[],this.prefetchCrossOriginStylesheets();let e=le({maskInputs:this.config.maskInputs,blockSelector:this.config.blockSelector,maskSelector:this.config.maskSelector});return e&&this.addEvent("snapshot",e),this.setupMutationObserver(),this.setupEventListeners(),this.setupNetworkRecording(),this.setupConsoleRecording(),this.startTrimTimer(),this.log("Recording started (rolling buffer mode):",this.sessionId),true}stop(){if(this.recording){this.recording=false,this.observer&&(this.observer.disconnect(),this.observer=null),this.trimTimer&&(clearInterval(this.trimTimer),this.trimTimer=null),this.mouseMoveFlushTimer&&(clearTimeout(this.mouseMoveFlushTimer),this.mouseMoveFlushTimer=null),this.mutationFlushTimer&&this.flushMutationBuffer(),this.networkRecorder&&(this.networkRecorder.stop(),this.networkRecorder=null),this.consoleRecorder&&(this.consoleRecorder.stop(),this.consoleRecorder=null);for(let e of this.cleanupFns)e();this.cleanupFns=[],It(),this.log("Recording stopped:",this.sessionId),this.sessionId=null;}}isRecording(){return this.recording}getSessionId(){return this.sessionId}setUser(e){this.userContext=e;}async flushOnError(){if(!this.recording||!this.sessionId||this.disabled)return;this.flushMutationBuffer();let e=[];if(this.latestSnapshot&&e.push(this.latestSnapshot),e.push(...this.events),e.length===0)return;this.events=[],this.latestSnapshot=null;let t=le({maskInputs:this.config.maskInputs,blockSelector:this.config.blockSelector,maskSelector:this.config.maskSelector});t&&this.addEvent("snapshot",t);let n=this.config.replayEndpoint||`${this.config.endpoint}/api/replays`;try{let i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({sessionId:this.sessionId,events:e,startedAt:new Date(this.sessionStartTime).toISOString(),pageUrl:typeof location<"u"?location.href:void 0,pageTitle:typeof document<"u"?document.title:void 0,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,userId:this.userContext?.id,trigger:"error"})});if(!i.ok)throw new Error(`HTTP ${i.status}`);this.flushFailures=0,this.log(`Flushed ${e.length} replay events (error-triggered)`);}catch(i){if(this.flushFailures++,this.flushFailures>=Ve){this.disabled=true,console.warn(`[SitePong Replay] Disabled after ${Ve} consecutive failures. Check that ${n} is accessible and has proper CORS headers.`);return}this.log(`Failed to flush replay events (attempt ${this.flushFailures}/${Ve}):`,i);}}async flush(){return this.flushOnError()}addEvent(e,t){if(!this.recording)return;if(Date.now()-this.sessionStartTime>this.config.maxSessionDuration){this.stop();return}let n={type:e,timestamp:Date.now()-this.sessionStartTime,data:t};e==="snapshot"&&(this.latestSnapshot=n),this.events.push(n);}trimBuffer(){if(this.events.length===0)return;let t=Date.now()-this.sessionStartTime-this.config.bufferDuration,n=0;for(let i=0;i<this.events.length;i++){if(this.events[i].timestamp>=t){n=i;break}this.events[i].type==="snapshot"&&(this.latestSnapshot=this.events[i]),n=i+1;}n>0&&(this.events=this.events.slice(n));}flushMutationBuffer(){this.mutationBuffer&&(this.mutationBuffer.adds.length||this.mutationBuffer.removes.length||this.mutationBuffer.attributes.length||this.mutationBuffer.texts.length)&&this.addEvent("mutation",this.mutationBuffer),this.mutationBuffer=null,this.mutationFlushTimer&&clearTimeout(this.mutationFlushTimer),this.mutationFlushTimer=null;}setupMutationObserver(){typeof MutationObserver>"u"||(this.observer=new MutationObserver(e=>{this.mutationBuffer||(this.mutationBuffer={adds:[],removes:[],attributes:[],texts:[]});for(let t of e)switch(t.type){case "childList":{for(let n of Array.from(t.addedNodes)){let i=ce(n,{maskInputs:this.config.maskInputs,blockSelector:this.config.blockSelector,maskSelector:this.config.maskSelector});i&&this.mutationBuffer.adds.push({parentId:b(t.target),nextId:t.nextSibling?b(t.nextSibling):null,node:i});}for(let n of Array.from(t.removedNodes))this.mutationBuffer.removes.push({parentId:b(t.target),id:b(n)});break}case "attributes":{let n=t.target,i=t.attributeName||"",o=n.getAttribute(i),s={[i]:o},c=n.tagName?.toLowerCase();if(c==="style"||c==="link"&&n.getAttribute("rel")==="stylesheet"){let l=ae(n);l&&(s._cssText=l);}if(i==="class"||i==="style"){let l=Oe(n);l&&(s._computedStyle=l);}this.mutationBuffer.attributes.push({id:b(t.target),attributes:s});break}case "characterData":{let n=t.target.textContent||"",i=t.target.parentElement;if(i&&this.config.maskSelector&&i.matches(this.config.maskSelector)&&(n=n.replace(/\S/g,"*")),this.mutationBuffer.texts.push({id:b(t.target),value:n}),i&&i.tagName?.toLowerCase()==="style"){let o=ae(i);o&&this.mutationBuffer.attributes.push({id:b(i),attributes:{_cssText:o}});}break}}this.mutationFlushTimer||(this.mutationFlushTimer=setTimeout(()=>this.flushMutationBuffer(),1e3));}),this.observer.observe(document.documentElement,{childList:true,subtree:true,attributes:true,characterData:true,attributeOldValue:false}));}setupEventListeners(){let e=u=>{this.mouseMoveBuffer.push({x:u.clientX,y:u.clientY,t:Date.now()-this.sessionStartTime}),this.mouseMoveFlushTimer||(this.mouseMoveFlushTimer=setTimeout(()=>{if(this.mouseMoveBuffer.length>0){let p={positions:[...this.mouseMoveBuffer]};this.addEvent("mouse_move",p),this.mouseMoveBuffer=[];}this.mouseMoveFlushTimer=null;},1e3));},t=u=>{let p=u.target;this.addEvent("mouse_click",{x:u.clientX,y:u.clientY,targetId:b(p),button:u.button}),this.takeInteractionSnapshot();},n=u=>{let p=u.target;this.addEvent("mouse_click",{x:u.clientX,y:u.clientY,targetId:b(p),button:2}),this.takeInteractionSnapshot();},i=()=>{this.addEvent("mouse_leave",{});},o=u=>{let p=u.touches[0];if(!p)return;let m=u.target;this.addEvent("touch",{x:p.clientX,y:p.clientY,targetId:b(m)}),this.takeInteractionSnapshot();},s=null,c=()=>{s&&clearTimeout(s),s=setTimeout(()=>{let u={id:0,x:window.scrollX,y:window.scrollY};this.addEvent("scroll",u),this.takeInteractionSnapshot();},1e3);},l=u=>{let p=u.target;if(!p)return;let m={id:b(p),value:this.config.maskInputs?"***":p.value};"checked"in p&&(m.isChecked=p.checked),this.addEvent("input",m);},d=()=>{this.addEvent("resize",{width:window.innerWidth,height:window.innerHeight});},f=u=>{u.target&&u.target!==document&&this.addEvent("focus",{id:b(u.target)});},g=u=>{u.target&&u.target!==document&&this.addEvent("blur",{id:b(u.target)});};document.addEventListener("mousemove",e,{passive:true}),document.addEventListener("click",t,{passive:true}),document.addEventListener("contextmenu",n,{passive:true}),document.documentElement.addEventListener("mouseleave",i,{passive:true}),document.addEventListener("touchstart",o,{passive:true}),window.addEventListener("scroll",c,{passive:true}),document.addEventListener("input",l,{passive:true}),window.addEventListener("resize",d,{passive:true}),document.addEventListener("focus",f,{passive:true,capture:true}),document.addEventListener("blur",g,{passive:true,capture:true}),this.cleanupFns.push(()=>document.removeEventListener("mousemove",e),()=>document.removeEventListener("click",t),()=>document.removeEventListener("contextmenu",n),()=>document.documentElement.removeEventListener("mouseleave",i),()=>document.removeEventListener("touchstart",o),()=>window.removeEventListener("scroll",c),()=>document.removeEventListener("input",l),()=>window.removeEventListener("resize",d),()=>document.removeEventListener("focus",f,{capture:true}),()=>document.removeEventListener("blur",g,{capture:true}));}setupNetworkRecording(){if(!this.config.recordNetwork)return;let e=this.config.replayEndpoint||this.config.endpoint;this.networkRecorder=new z(t=>{this.addEvent("network",t.data);},{captureHeaders:this.config.captureNetworkHeaders,urlFilter:t=>!t.startsWith(e)}),this.networkRecorder.start();}setupConsoleRecording(){this.config.recordConsole&&(this.consoleRecorder=new q(e=>{this.addEvent("console",e.data);},{levels:this.config.consoleLevels}),this.consoleRecorder.start());}startTrimTimer(){this.trimTimer=setInterval(()=>{this.trimBuffer();},lr);}takeInteractionSnapshot(){let e=Date.now();if(e-this.lastSnapshotTime<this.snapshotCooldown)return;this.lastSnapshotTime=e;let t=le({maskInputs:this.config.maskInputs,blockSelector:this.config.blockSelector,maskSelector:this.config.maskSelector});t&&this.addEvent("snapshot",t);}getOrCreateSessionId(){let e="__sp_replay_session";try{let n=sessionStorage.getItem(e);if(n)return n}catch{}let t=`rep_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`;try{sessionStorage.setItem(e,t);}catch{}return t}getOrCreateStartTime(){let e="__sp_replay_start";try{let n=sessionStorage.getItem(e);if(n)return parseInt(n,10)}catch{}let t=Date.now();try{sessionStorage.setItem(e,String(t));}catch{}return t}prefetchCrossOriginStylesheets(){if(typeof document>"u")return;let e=document.querySelectorAll('link[rel="stylesheet"]');for(let t of Array.from(e)){let n=t;if(n.href&&n.sheet)try{n.sheet.cssRules;}catch{Pt(n.href).catch(()=>{});}}}log(...e){this.config.debug&&console.log("[SitePong Replay]",...e);}};});var Ft=h(()=>{_t();Ne();He();});var ur,X,At=h(()=>{ur="https://ingest.sitepong.com",X=class{constructor(e){this.metrics=[];this.flushTimer=null;this.flushFailures=0;this.disabled=false;this.vitals={};this.activeTransactions=new Map;this.config={endpoint:ur,enabled:true,webVitals:true,navigationTiming:true,resourceTiming:false,flushInterval:1e4,sampleRate:1,debug:false,...e},this.sampled=Math.random()<=this.config.sampleRate;}init(){!this.config.enabled||!this.sampled||typeof window>"u"||typeof window.addEventListener!="function"||(this.config.webVitals&&this.observeWebVitals(),this.config.navigationTiming&&this.collectNavigationTiming(),this.startFlushTimer(),this.log("Performance monitoring initialized"));}startTransaction(e,t){let n=`txn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,i={id:n,name:e,startTime:performance.now(),status:"running",spans:[],data:t};return this.activeTransactions.set(n,i),this.log("Transaction started:",e,n),n}endTransaction(e,t="ok"){let n=this.activeTransactions.get(e);if(!n){this.log("Transaction not found:",e);return}n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.status=t;for(let i of n.spans)i.status==="running"&&(i.endTime=n.endTime,i.duration=i.endTime-i.startTime,i.status=t);this.activeTransactions.delete(e),this.addMetric({type:"transaction",name:n.name,value:n.duration,unit:"ms",timestamp:new Date().toISOString(),url:typeof window<"u"?window.location.href:void 0,transaction:n}),this.log("Transaction ended:",n.name,`${n.duration.toFixed(1)}ms`);}startSpan(e,t,n){let i=this.activeTransactions.get(e);if(!i)return this.log("Transaction not found for span:",e),"";let o={id:`span_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,name:t,startTime:performance.now(),status:"running",data:n};return i.spans.push(o),o.id}endSpan(e,t,n="ok"){let i=this.activeTransactions.get(e);if(!i)return;let o=i.spans.find(s=>s.id===t);o&&(o.endTime=performance.now(),o.duration=o.endTime-o.startTime,o.status=n);}getVitals(){return {...this.vitals}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush();}observeWebVitals(){if(!(typeof PerformanceObserver>"u")){try{new PerformanceObserver(t=>{let n=t.getEntries(),i=n[n.length-1];i&&(this.vitals.lcp=i.startTime,this.reportVital("LCP",i.startTime));}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{new PerformanceObserver(t=>{let n=t.getEntries()[0];if(n){let i=n.processingStart-n.startTime;this.vitals.fid=i,this.reportVital("FID",i);}}).observe({type:"first-input",buffered:!0});}catch{}try{let e=0;new PerformanceObserver(n=>{for(let i of n.getEntries()){let o=i;o.hadRecentInput||(e+=o.value);}this.vitals.cls=e;}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e>0&&this.reportVital("CLS",e,"score");});}catch{}try{new PerformanceObserver(t=>{let n=t.getEntries().find(i=>i.name==="first-contentful-paint");n&&(this.vitals.fcp=n.startTime,this.reportVital("FCP",n.startTime));}).observe({type:"paint",buffered:!0});}catch{}try{let e=0;new PerformanceObserver(n=>{for(let i of n.getEntries()){let o=i.duration;o>e&&(e=o,this.vitals.inp=e);}}).observe({type:"event",buffered:!0});}catch{}}}collectNavigationTiming(){if(typeof window>"u"||!window.performance)return;let e=()=>{let t=performance.getEntriesByType("navigation")[0];if(!t)return;let n=t.responseStart-t.requestStart;this.vitals.ttfb=n,this.reportVital("TTFB",n),this.addMetric({type:"navigation",name:"page_load",value:t.loadEventEnd-t.startTime,unit:"ms",timestamp:new Date().toISOString(),url:window.location.href,data:{dns:t.domainLookupEnd-t.domainLookupStart,tcp:t.connectEnd-t.connectStart,ttfb:n,domContentLoaded:t.domContentLoadedEventEnd-t.startTime,domComplete:t.domComplete-t.startTime,transferSize:t.transferSize,encodedBodySize:t.encodedBodySize,decodedBodySize:t.decodedBodySize}});};document.readyState==="complete"?setTimeout(e,0):window.addEventListener("load",()=>setTimeout(e,0));}reportVital(e,t,n="ms"){this.addMetric({type:"web_vital",name:e,value:t,unit:n,timestamp:new Date().toISOString(),url:typeof window<"u"?window.location.href:void 0});}addMetric(e){this.metrics.push(e);}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flush();});}async flush(){if(this.metrics.length===0)return;if(this.disabled){this.metrics=[];return}let e=[...this.metrics];this.metrics=[];let t=this.config.performanceEndpoint||`${this.config.endpoint}/api/performance`;try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({metrics:e})});if(!n.ok)throw new Error(`HTTP ${n.status}`);this.flushFailures=0,this.log(`Flushed ${e.length} performance metrics`);}catch(n){if(this.flushFailures++,this.flushFailures>=3){this.disabled=true,console.warn(`[SitePong Performance] Disabled after 3 consecutive failures. Check that ${t} is accessible and has proper CORS headers.`);return}this.metrics.unshift(...e),this.log(`Failed to flush metrics (attempt ${this.flushFailures}/3):`,n);}}log(...e){this.config.debug&&console.log("[SitePong Performance]",...e);}};});function Lt(r){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint8Array(r);return crypto.getRandomValues(t),Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}}catch{}let e="";for(let t=0;t<r;t++)e+=Math.floor(Math.random()*256).toString(16).padStart(2,"0");return e}function Be(){return Lt(16)}function pe(){return Lt(8)}function $e(){return {traceId:Be(),spanId:pe(),parentSpanId:null,sampled:true}}function de(r){let e=r.sampled?"01":"00";return {traceparent:`00-${r.traceId}-${r.spanId}-${e}`,tracestate:`sitepong=${r.spanId}`}}function Ot(r){let e=r.traceparent||r.Traceparent;if(!e)return null;let t=e.split("-");if(t.length!==4)return null;let[n,i,o,s]=t;if(n!=="00"||i.length!==32||!/^[0-9a-f]{32}$/.test(i)||o.length!==16||!/^[0-9a-f]{16}$/.test(o)||s.length!==2||!/^[0-9a-f]{2}$/.test(s))return null;let c=(parseInt(s,16)&1)===1;return {traceId:i,spanId:pe(),parentSpanId:o,sampled:c}}exports.TracePropagator=void 0;var Nt=h(()=>{exports.TracePropagator=class{constructor(e){this.originalFetch=null;this.targets=e;}shouldPropagate(e){return this.targets.some(t=>{if(t.includes("*")){let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}return e.startsWith(t)})}injectHeaders(e,t,n){if(!this.shouldPropagate(e))return t;let i=de(n);return {...t,...i}}start(){if(typeof window>"u"||!window.fetch||this.originalFetch)return;this.originalFetch=window.fetch;let e=this;window.fetch=function(t,n){let i=typeof t=="string"?t:t instanceof URL?t.toString():t.url;if(e.shouldPropagate(i)){let o=$e(),s=de(o),c={};if(n?.headers)if(n.headers instanceof Headers)n.headers.forEach((f,g)=>{c[g]=f;});else if(Array.isArray(n.headers))for(let[f,g]of n.headers)c[f]=g;else Object.assign(c,n.headers);let l={...c,...s},d={...n,headers:l};return e.originalFetch.call(window,t,d)}return e.originalFetch.call(window,t,n)};}stop(){typeof window>"u"||this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null);}};});var Ue=h(()=>{At();Nt();});var G,Ht=h(()=>{G=class{constructor(e){this.apiKey=e.apiKey,this.endpoint=e.endpoint,this.debug=e.debug||false;}async checkin(e,t={}){try{let n=await fetch(`${this.endpoint}/api/sdk/crons`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify({slug:e,status:t.status||"ok",duration_ms:t.duration_ms,message:t.message,environment:t.environment})});if(!n.ok)throw new Error(`HTTP ${n.status}`);this.log(`Check-in sent for "${e}" (${t.status||"ok"})`);}catch(n){this.log("Failed to send check-in:",n);}}start(e,t){let n=Date.now();return this.checkin(e,{status:"in_progress",environment:t}),{ok:async i=>{let o=Date.now()-n;await this.checkin(e,{status:"ok",duration_ms:o,message:i,environment:t});},error:async i=>{let o=Date.now()-n;await this.checkin(e,{status:"error",duration_ms:o,message:i,environment:t});}}}wrap(e,t,n){let i=this.start(e,n);return t().then(async o=>(await i.ok(),o),async o=>{throw await i.error(o?.message||String(o)),o})}log(...e){this.debug&&console.log("[SitePong:Cron]",...e);}};});var j,Vt=h(()=>{j=class{constructor(e){this.queue=[];this.flushTimer=null;this.apiKey=e.apiKey,this.endpoint=e.endpoint,this.debug=e.debug||false,this.flushInterval=e.flushInterval||1e4,this.maxBatchSize=e.maxBatchSize||100,this.startFlushTimer();}increment(e,t=1,n){this.enqueue(e,t,"counter",n);}decrement(e,t=1,n){this.enqueue(e,-t,"counter",n);}gauge(e,t,n){this.enqueue(e,t,"gauge",n);}histogram(e,t,n){this.enqueue(e,t,"histogram",n);}distribution(e,t,n){this.enqueue(e,t,"distribution",n);}async time(e,t,n){let i=Date.now();try{let o=await t();return this.distribution(e,Date.now()-i,{...n,unit:n?.unit||"ms"}),o}catch(o){throw this.distribution(e,Date.now()-i,{...n,unit:n?.unit||"ms",tags:{...n?.tags,error:"true"}}),o}}startTimer(e,t){let n=Date.now();return {stop:()=>{this.distribution(e,Date.now()-n,{...t,unit:t?.unit||"ms"});}}}async flush(){if(this.queue.length===0)return;let e=[...this.queue];this.queue=[];try{let t=await fetch(`${this.endpoint}/api/sdk/metrics`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify({metrics:e})});if(!t.ok)throw new Error(`HTTP ${t.status}`);this.log(`Flushed ${e.length} metrics`);}catch(t){this.queue.unshift(...e),this.log("Failed to flush metrics:",t);}}async destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush();}enqueue(e,t,n,i){this.queue.push({name:e,value:t,type:n,unit:i?.unit,tags:i?.tags,timestamp:i?.timestamp||new Date().toISOString()}),this.queue.length>=this.maxBatchSize&&this.flush();}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.flushInterval),typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushWithBeacon();});}flushWithBeacon(){if(this.queue.length===0||typeof navigator?.sendBeacon!="function")return;let e=[...this.queue];this.queue=[];let t=new Blob([JSON.stringify({metrics:e,apiKey:this.apiKey})],{type:"application/json"});navigator.sendBeacon(`${this.endpoint}/api/sdk/metrics`,t),this.log(`Flushed ${e.length} metrics via beacon`);}log(...e){this.debug&&console.log("[SitePong:Metrics]",...e);}};});var Q,Bt=h(()=>{Q=class{constructor(e){this.queue=[];this.flushTimer=null;this.queryCounter=0;this.nPlusOneDetector=new Map;this.config={slowQueryThreshold:1e3,maxBatchSize:50,flushInterval:1e4,redactParams:true,...e},this.startFlushTimer();}async track(e,t,n){let i=Date.now();this.queryCounter++;try{let o=await t(),s=Date.now()-i;return this.recordQuery({query:this.config.redactParams?this.redactQuery(e):e,duration_ms:s,timestamp:new Date().toISOString(),source:n,is_slow:s>=(this.config.slowQueryThreshold||1e3)}),this.detectNPlusOne(e),o}catch(o){let s=Date.now()-i;throw this.recordQuery({query:this.config.redactParams?this.redactQuery(e):e,duration_ms:s,timestamp:new Date().toISOString(),source:n,error:o instanceof Error?o.message:String(o)}),o}}trackSync(e,t,n){let i=Date.now();this.queryCounter++;try{let o=t(),s=Date.now()-i;return this.recordQuery({query:this.config.redactParams?this.redactQuery(e):e,duration_ms:s,timestamp:new Date().toISOString(),source:n,is_slow:s>=(this.config.slowQueryThreshold||1e3)}),o}catch(o){let s=Date.now()-i;throw this.recordQuery({query:this.config.redactParams?this.redactQuery(e):e,duration_ms:s,timestamp:new Date().toISOString(),source:n,error:o instanceof Error?o.message:String(o)}),o}}getQueryCount(){return this.queryCounter}resetQueryCount(){this.queryCounter=0,this.nPlusOneDetector.clear();}getNPlusOnePatterns(){let e=[];for(let[t,{count:n}]of this.nPlusOneDetector.entries())n>=5&&e.push({query:t,count:n});return e}async flush(){if(this.queue.length===0)return;let e=[...this.queue];this.queue=[];try{let t=await fetch(`${this.config.endpoint}/api/sdk/metrics`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({metrics:e.map(n=>({name:"db.query",value:n.duration_ms,type:"distribution",unit:"ms",tags:{query:n.query.substring(0,200),source:n.source||"unknown",is_slow:String(n.is_slow||!1),...n.error?{error:"true"}:{}},timestamp:n.timestamp}))})});if(!t.ok)throw new Error(`HTTP ${t.status}`);this.log(`Flushed ${e.length} query events`);}catch(t){this.queue.unshift(...e),this.log("Failed to flush query events:",t);}}async destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush();}recordQuery(e){this.queue.push(e),this.queue.length>=(this.config.maxBatchSize||50)&&this.flush(),e.is_slow&&this.log(`Slow query (${e.duration_ms}ms):`,e.query.substring(0,100));}detectNPlusOne(e){let t=this.normalizeQuery(e),n=Date.now(),i=this.nPlusOneDetector.get(t);if(i?n-i.since<1e3?(i.count++,i.count===5&&this.log(`N+1 query detected! Pattern repeated ${i.count} times:`,t.substring(0,100))):this.nPlusOneDetector.set(t,{count:1,since:n}):this.nPlusOneDetector.set(t,{count:1,since:n}),this.nPlusOneDetector.size>100){let o=[...this.nPlusOneDetector.entries()];o.sort((s,c)=>s[1].since-c[1].since);for(let s=0;s<50;s++)this.nPlusOneDetector.delete(o[s][0]);}}normalizeQuery(e){return e.replace(/\s+/g," ").replace(/'[^']*'/g,"?").replace(/\b\d+\b/g,"?").trim().substring(0,300)}redactQuery(e){return e.replace(/'[^']*'/g,"'***'").replace(/\b\d{4,}\b/g,"***")}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval||1e4);}log(...e){this.config.debug&&console.log("[SitePong:DB]",...e);}};});function $t(r){let e=r.length;for(let t of r)e+=$t(t.children);return e}var Y,Ut=h(()=>{Y=class{constructor(e){this.profiles=[];this.activeProfile=null;this.frameStack=[];this.flushTimer=null;this.config={sampleRate:.1,maxDuration:3e4,flushInterval:3e4,...e},this.startFlushTimer();}async profile(e,t,n){if(Math.random()>(this.config.sampleRate||.1))return t();let i=this.generateId(),o=performance.now();this.activeProfile={id:i,name:e,startTime:o,duration_ms:0,frames:[],metadata:n},this.frameStack=[];let s={name:e,start_ms:0,duration_ms:0,children:[],metadata:n};this.frameStack.push(s);try{let c=await t();return s.duration_ms=performance.now()-o,this.activeProfile.duration_ms=s.duration_ms,this.activeProfile.frames=[s],s.duration_ms<=(this.config.maxDuration||3e4)&&this.profiles.push(this.activeProfile),this.activeProfile=null,this.frameStack=[],c}catch(c){throw s.duration_ms=performance.now()-o,s.metadata={...s.metadata,error:true},this.activeProfile&&(this.activeProfile.duration_ms=s.duration_ms,this.activeProfile.frames=[s],this.profiles.push(this.activeProfile)),this.activeProfile=null,this.frameStack=[],c}}startSpan(e,t){if(!this.activeProfile)return ()=>{};let n=performance.now()-this.activeProfile.startTime,i={name:e,start_ms:n,duration_ms:0,children:[],metadata:t},o=this.frameStack[this.frameStack.length-1];return o&&o.children.push(i),this.frameStack.push(i),()=>{i.duration_ms=performance.now()-this.activeProfile.startTime-i.start_ms,this.frameStack.pop();}}getProfiles(){return [...this.profiles]}getLatestProfile(){return this.profiles.length>0?this.profiles[this.profiles.length-1]:null}async flush(){if(this.profiles.length===0)return;let e=[...this.profiles];this.profiles=[];try{let t=await fetch(`${this.config.endpoint}/api/sdk/metrics`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({metrics:e.map(n=>({name:`profile.${n.name}`,value:n.duration_ms,type:"distribution",unit:"ms",tags:{profile_id:n.id,frame_count:String($t(n.frames)),...n.metadata||{}},timestamp:new Date(Date.now()-n.duration_ms).toISOString()}))})});if(!t.ok)throw new Error(`HTTP ${t.status}`);this.log(`Flushed ${e.length} profiles`);}catch(t){this.profiles.unshift(...e),this.log("Failed to flush profiles:",t);}}async destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush();}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval||3e4);}generateId(){return `prof_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,8)}`}log(...e){this.config.debug&&console.log("[SitePong:Profiler]",...e);}};});var Ke,ze=h(()=>{Ke={features:{},sampling:{errors:1,analytics:1,replay:1,performance:1},transport:{flushInterval:1e4,maxBatchSize:20,maxRetries:3},autocapture:{clicks:true,forms:true,pageviews:true,appState:true,screenViews:true},ttl:300};});var Kt,zt,D,qt=h(()=>{ze();P();Kt="sitepong_remote_config",zt="sitepong_remote_config_ts",D=class{constructor(e){this.listeners=[];this.refreshTimer=null;this.initialized=false;this.options=e,this.config={...Ke};}async init(){await this.loadFromCache(),this.initialized=true,this.fetchAndApply().catch(e=>{this.log("Failed to fetch remote config:",e);});}getConfig(){return this.config}isFeatureEnabled(e,t=true){return this.config.features[e]??t}onChange(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e);}}isInitialized(){return this.initialized}destroy(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),this.listeners=[];}async loadFromCache(){let e=this.options.storage;if(e)try{let t=await e.getItem(Kt),n=await e.getItem(zt);if(t&&n){let i=Date.now()-parseInt(n,10),o=this.config.ttl*1e3;if(i<o){let s=JSON.parse(t);this.config=s,this.log("Loaded config from cache (age:",Math.round(i/1e3),"s)");}}}catch{this.log("Failed to load cached config");}}async fetchAndApply(){try{let e=ie(),t=new URLSearchParams({platform:e,...this.options.sdkVersion?{sdkVersion:this.options.sdkVersion}:{}}),n=await fetch(`${this.options.endpoint}/api/sdk/config?${t}`,{method:"GET",headers:{"X-API-Key":this.options.apiKey}});if(!n.ok)throw new Error(`HTTP ${n.status}`);let i=await n.json();this.config=i.config;for(let o of this.listeners)try{o(this.config);}catch{}await this.saveToCache(),this.scheduleRefresh(),i.config.minSdkVersion&&this.options.sdkVersion&&this.compareVersions(this.options.sdkVersion,i.config.minSdkVersion)<0&&console.warn(`[SitePong] SDK version ${this.options.sdkVersion} is outdated. Minimum recommended: ${i.config.minSdkVersion}. Please update.`),this.log("Remote config fetched successfully");}catch(e){throw this.scheduleRefresh(),e}}async saveToCache(){let e=this.options.storage;if(e)try{await e.setItem(Kt,JSON.stringify(this.config)),await e.setItem(zt,String(Date.now()));}catch{this.log("Failed to cache remote config");}}scheduleRefresh(){this.refreshTimer&&clearTimeout(this.refreshTimer);let e=this.config.ttl*1e3;this.refreshTimer=setTimeout(()=>{this.fetchAndApply().catch(t=>{this.log("Refresh failed:",t);});},e);}compareVersions(e,t){let n=e.split(".").map(Number),i=t.split(".").map(Number);for(let o=0;o<3;o++){let s=n[o]||0,c=i[o]||0;if(s>c)return 1;if(s<c)return -1}return 0}log(...e){this.options.debug&&console.log("[SitePong RemoteConfig]",...e);}};});var Wt=h(()=>{qt();ze();});var jt={};je(jt,{clearPushCache:()=>vr,endLiveActivity:()=>gr,reRegisterTokensWithUserId:()=>mr,registerLiveActivityToken:()=>pr,registerPushToStartToken:()=>hr,registerPushToken:()=>fr});function Xt(){return exports.client.config?.endpoint||"https://ingest.sitepong.com"}function Gt(){return exports.client.config?.apiKey||""}function F(){if(_)return _;try{let r=(P(),Qe(dt)),e=r.getRNDeviceInfo?.();_={deviceId:r.getNativeDeviceId?.()||void 0,platform:e?.platform||void 0,appVersion:e?.appVersion||void 0,deviceModel:e?.deviceModel||void 0,osVersion:e?.osVersion||void 0};}catch{_={};}return _}function We(){try{return exports.client.analyticsManager?.getUserId?.()||void 0}catch{return}}async function A(r,e){let t=Xt(),n=Gt();if(!n){console.warn("[SitePong] Cannot register push token: SDK not initialized");return}try{let i=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":n},body:JSON.stringify(e)});i.ok||console.warn(`[SitePong] Push token registration failed: HTTP ${i.status}`);}catch(i){console.warn("[SitePong] Push token registration failed:",i);}}async function dr(r,e){let t=Xt(),n=Gt();if(n)try{let i=await fetch(`${t}${r}`,{method:"DELETE",headers:{"Content-Type":"application/json","X-API-Key":n},body:JSON.stringify(e)});i.ok||console.warn(`[SitePong] Push token deactivation failed: HTTP ${i.status}`);}catch(i){console.warn("[SitePong] Push token deactivation failed:",i);}}function fr(r,e){let t=F(),n=We();J={token:r,environment:e.environment},A("/api/push/tokens",{expo_push_token:r,environment:e.environment,device_id:t.deviceId,user_id:n,platform:t.platform,app_version:t.appVersion,device_model:t.deviceModel,os_version:t.osVersion});}function pr(r,e,t,n){let i=F(),o=We(),s=`${r}:${e}`;he.set(s,{activityType:r,activityId:e,token:t,environment:n.environment}),A("/api/push/live-activity-tokens",{activity_type:r,activity_id:e,push_token:t,environment:n.environment,device_id:i.deviceId,user_id:o});}function hr(r,e,t){let n=F(),i=We();qe.set(r,{activityType:r,token:e,environment:t.environment}),A("/api/push/push-to-start-tokens",{activity_type:r,push_to_start_token:e,environment:t.environment,device_id:n.deviceId,user_id:i});}function gr(r,e){let t=`${r}:${e}`;he.delete(t),dr("/api/push/live-activity-tokens",{activity_type:r,activity_id:e});}function mr(r){if(J){let e=F();A("/api/push/tokens",{expo_push_token:J.token,environment:J.environment,device_id:e.deviceId,user_id:r,platform:e.platform,app_version:e.appVersion,device_model:e.deviceModel,os_version:e.osVersion});}for(let e of he.values()){let t=F();A("/api/push/live-activity-tokens",{activity_type:e.activityType,activity_id:e.activityId,push_token:e.token,environment:e.environment,device_id:t.deviceId,user_id:r});}for(let e of qe.values()){let t=F();A("/api/push/push-to-start-tokens",{activity_type:e.activityType,push_to_start_token:e.token,environment:e.environment,device_id:t.deviceId,user_id:r});}}function vr(){_=null,J=null,he.clear(),qe.clear();}var _,J,he,qe,Qt=h(()=>{Yt();_=null,J=null,he=new Map,qe=new Map;});var v,yr,br,Xe,Ge;exports.client=void 0;exports.init=void 0;exports.initRN=void 0;exports.captureError=void 0;exports.captureMessage=void 0;exports.setContext=void 0;exports.setUser=void 0;exports.setTags=void 0;exports.flush=void 0;exports.isInitialized=void 0;exports.clearUser=void 0;exports.addBreadcrumb=void 0;exports.getFlag=void 0;exports.getAllFlags=void 0;exports.getVariant=void 0;exports.getVariantPayload=void 0;exports.waitForFlags=void 0;exports.areFlagsReady=void 0;exports.refreshFlags=void 0;exports.track=void 0;exports.trackPageView=void 0;exports.identify=void 0;exports.group=void 0;exports.resetAnalytics=void 0;exports.getVisitorId=void 0;exports.getDeviceSignals=void 0;exports.getFraudCheck=void 0;exports.startReplay=void 0;exports.stopReplay=void 0;exports.isReplayRecording=void 0;exports.getReplaySessionId=void 0;exports.startTransaction=void 0;exports.endTransaction=void 0;exports.startSpan=void 0;exports.endSpan=void 0;exports.getWebVitals=void 0;exports.dbTrack=void 0;exports.dbTrackSync=void 0;exports.getDbQueryCount=void 0;exports.resetDbQueryCount=void 0;exports.getDbNPlusOnePatterns=void 0;exports.cronCheckin=void 0;exports.cronStart=void 0;exports.cronWrap=void 0;exports.metricIncrement=void 0;exports.metricGauge=void 0;exports.metricHistogram=void 0;exports.metricDistribution=void 0;exports.metricTime=void 0;exports.metricStartTimer=void 0;exports.flushMetrics=void 0;exports.profile=void 0;exports.startProfileSpan=void 0;exports.getProfiles=void 0;exports.getLatestProfile=void 0;exports.flushProfiles=void 0;exports.getRemoteConfig=void 0;exports.isRemoteConfigFeatureEnabled=void 0;exports.onRemoteConfigChange=void 0;exports.default=void 0;var Yt=h(()=>{we();pt();Tt();Ft();Ue();Ht();Vt();Bt();Ut();Wt();P();we();Ue();v="https://ingest.sitepong.com",yr=10,br=5e3,Xe=3,Ge=class{constructor(){this.errorQueue=[];this.flushTimer=null;this.context={};this.initialized=false;this.flushFailures=0;this.disabled=false;this.flagManager=null;this.analyticsManager=null;this.fingerprintManager=null;this.replayManager=null;this.performanceManager=null;this.cronManager=null;this.metricsManager=null;this.databaseTracker=null;this.profiler=null;this.remoteConfigManager=null;this.config={apiKey:"",endpoint:v,environment:"production",release:"",autoCapture:true,maxBatchSize:yr,flushInterval:br,debug:false};}init(e){if(!e.apiKey){console.error("[SitePong] API key is required");return}if(this.config={...this.config,...e},this.initialized=true,this.config.autoCapture&&this.setupAutoCapture(),this.startFlushTimer(),this.log("Initialized with endpoint:",this.config.endpoint),e.enableFlags&&(this.flagManager=new M({apiKey:e.apiKey,endpoint:e.flagsEndpoint||e.endpoint||v,debug:e.debug}),this.flagManager.init().catch(t=>{this.log("Failed to initialize flags:",t);})),e.analytics?.enabled&&(this.analyticsManager&&this.analyticsManager.destroy(),this.analyticsManager=new I({apiKey:e.apiKey,endpoint:e.endpoint||v,enabled:true,autocapturePageviews:e.analytics.autocapturePageviews,autocaptureClicks:e.analytics.autocaptureClicks,autocaptureForms:e.analytics.autocaptureForms,autocapture:e.analytics.autocapture,maxBatchSize:e.analytics.maxBatchSize,flushInterval:e.analytics.flushInterval,eventsEndpoint:e.analytics.eventsEndpoint,debug:e.debug}),this.analyticsManager.init()),e.fingerprint?.enabled&&(this.fingerprintManager=new U({apiKey:e.apiKey,endpoint:e.endpoint||v,enabled:true,extendedSignals:e.fingerprint.extendedSignals,visitorEndpoint:e.fingerprint.visitorEndpoint,debug:e.debug})),e.performance?.enabled&&(this.performanceManager&&this.performanceManager.destroy(),this.performanceManager=new X({apiKey:e.apiKey,endpoint:e.endpoint||v,enabled:true,webVitals:e.performance.webVitals,navigationTiming:e.performance.navigationTiming,resourceTiming:e.performance.resourceTiming,sampleRate:e.performance.sampleRate,flushInterval:e.performance.flushInterval,performanceEndpoint:e.performance.performanceEndpoint,debug:e.debug}),this.performanceManager.init()),e.replay?.enabled&&(this.replayManager&&this.replayManager.stop(),this.replayManager=new W({apiKey:e.apiKey,endpoint:e.endpoint||v,enabled:true,maskInputs:e.replay.maskInputs,blockSelector:e.replay.blockSelector,maskSelector:e.replay.maskSelector,sampleRate:e.replay.sampleRate,maxSessionDuration:e.replay.maxSessionDuration,flushInterval:e.replay.flushInterval,replayEndpoint:e.replay.replayEndpoint,recordNetwork:e.replay.recordNetwork,captureNetworkHeaders:e.replay.captureNetworkHeaders,recordConsole:e.replay.recordConsole,consoleLevels:e.replay.consoleLevels,bufferDuration:e.replay.bufferDuration,debug:e.debug}),this.replayManager.start()),e.crons?.enabled&&(this.cronManager=new G({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug})),e.database?.enabled&&(this.databaseTracker=new Q({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,slowQueryThreshold:e.database.slowQueryThreshold,redactParams:e.database.redactParams})),e.metrics?.enabled&&(this.metricsManager=new j({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,flushInterval:e.metrics.flushInterval,maxBatchSize:e.metrics.maxBatchSize})),e.profiling?.enabled&&(this.profiler=new Y({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,sampleRate:e.profiling.sampleRate,maxDuration:e.profiling.maxDuration,flushInterval:e.profiling.flushInterval})),e.remoteConfig?.enabled!==false){let t=e._storageAdapter||oe();this.remoteConfigManager=new D({apiKey:e.apiKey,endpoint:e.endpoint||v,storage:t,debug:e.debug}),this.remoteConfigManager.init().catch(n=>{this.log("Failed to initialize remote config:",n);});}}initRN(e){if(!e.apiKey){console.error("[SitePong] API key is required");return}if(this.config={...this.config,...e},this.initialized=true,this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval),this.log("Initialized (React Native) with endpoint:",this.config.endpoint),e.enableFlags&&(this.flagManager=new M({apiKey:e.apiKey,endpoint:e.flagsEndpoint||e.endpoint||v,debug:e.debug}),this.flagManager.init().catch(t=>{this.log("Failed to initialize flags:",t);})),e.analytics?.enabled&&(this.analyticsManager&&this.analyticsManager.destroy(),this.analyticsManager=new I({apiKey:e.apiKey,endpoint:e.endpoint||v,enabled:true,maxBatchSize:e.analytics.maxBatchSize,flushInterval:e.analytics.flushInterval,eventsEndpoint:e.analytics.eventsEndpoint,debug:e.debug}),this.analyticsManager.initHeadless()),e.crons?.enabled&&(this.cronManager=new G({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug})),e.metrics?.enabled&&(this.metricsManager=new j({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,flushInterval:e.metrics.flushInterval,maxBatchSize:e.metrics.maxBatchSize})),e.database?.enabled&&(this.databaseTracker=new Q({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,slowQueryThreshold:e.database.slowQueryThreshold,redactParams:e.database.redactParams})),e.profiling?.enabled&&(this.profiler=new Y({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,sampleRate:e.profiling.sampleRate,maxDuration:e.profiling.maxDuration,flushInterval:e.profiling.flushInterval})),e.remoteConfig?.enabled!==false){let t=e._storageAdapter||oe();this.remoteConfigManager=new D({apiKey:e.apiKey,endpoint:e.endpoint||v,storage:t,debug:e.debug}),this.remoteConfigManager.init().catch(n=>{this.log("Failed to initialize remote config:",n);});}}isInitialized(){return this.initialized}getFlag(e,t=false){return this.flagManager?this.flagManager.getFlag(e,t):(this.log("Flags not enabled. Set enableFlags: true in init()"),t)}getAllFlags(){return this.flagManager?this.flagManager.getAllFlags():{}}async waitForFlags(){this.flagManager&&await this.flagManager.waitForInit();}areFlagsReady(){return this.flagManager?.isInitialized()??false}getVariant(e,t=null){return this.flagManager?this.flagManager.getVariant(e,t):(this.log("Flags not enabled. Set enableFlags: true in init()"),t)}getVariantPayload(e,t=null){return this.flagManager?this.flagManager.getVariantPayload(e,t):t}async refreshFlags(){this.flagManager&&await this.flagManager.refresh();}track(e,t){if(!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.track(e,t);}trackPageView(e,t){if(!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.trackPageView(e,t);}identify(e,t){this.replayManager&&this.replayManager.setUser({id:e});try{let{reRegisterTokensWithUserId:n}=(Qt(),Qe(jt));n(e);}catch{}if(!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.identify(e,t);}group(e,t){if(!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.group(e,t);}resetAnalytics(){this.analyticsManager&&this.analyticsManager.reset();}async getVisitorId(){if(!this.fingerprintManager)throw new Error("Fingerprint not enabled. Set fingerprint.enabled: true in init()");return this.fingerprintManager.getVisitorId()}async getDeviceSignals(){if(!this.fingerprintManager)throw new Error("Fingerprint not enabled. Set fingerprint.enabled: true in init()");return this.fingerprintManager.getDeviceSignals()}async getFraudCheck(){if(!this.fingerprintManager)throw new Error("Fingerprint not enabled. Set fingerprint.enabled: true in init()");return this.fingerprintManager.getFraudCheck()}startReplay(){return this.replayManager?this.replayManager.start():(this.log("Replay not enabled. Set replay.enabled: true in init()"),false)}stopReplay(){this.replayManager&&this.replayManager.stop();}isReplayRecording(){return this.replayManager?.isRecording()??false}getReplaySessionId(){return this.replayManager?.getSessionId()??null}startTransaction(e,t){return this.performanceManager?this.performanceManager.startTransaction(e,t):(this.log("Performance not enabled. Set performance.enabled: true in init()"),"")}endTransaction(e,t="ok"){this.performanceManager&&this.performanceManager.endTransaction(e,t);}startSpan(e,t,n){return this.performanceManager?this.performanceManager.startSpan(e,t,n):""}endSpan(e,t,n="ok"){this.performanceManager&&this.performanceManager.endSpan(e,t,n);}getWebVitals(){return this.performanceManager?this.performanceManager.getVitals():{}}cronCheckin(e,t){return this.cronManager?this.cronManager.checkin(e,t):(this.log("Cron monitoring not enabled. Set crons.enabled: true in init()"),Promise.resolve())}cronStart(e,t){return this.cronManager?this.cronManager.start(e,t):(this.log("Cron monitoring not enabled. Set crons.enabled: true in init()"),{ok:()=>Promise.resolve(),error:()=>Promise.resolve()})}cronWrap(e,t,n){return this.cronManager?this.cronManager.wrap(e,t,n):t()}metricIncrement(e,t,n){if(!this.metricsManager){this.log("Metrics not enabled. Set metrics.enabled: true in init()");return}this.metricsManager.increment(e,t,n);}metricGauge(e,t,n){this.metricsManager&&this.metricsManager.gauge(e,t,n);}metricHistogram(e,t,n){this.metricsManager&&this.metricsManager.histogram(e,t,n);}metricDistribution(e,t,n){this.metricsManager&&this.metricsManager.distribution(e,t,n);}async metricTime(e,t,n){return this.metricsManager?this.metricsManager.time(e,t,n):t()}metricStartTimer(e,t){return this.metricsManager?this.metricsManager.startTimer(e,t):{stop:()=>{}}}async flushMetrics(){if(this.metricsManager)return this.metricsManager.flush()}async dbTrack(e,t,n){return this.databaseTracker?this.databaseTracker.track(e,t,n):t()}dbTrackSync(e,t,n){return this.databaseTracker?this.databaseTracker.trackSync(e,t,n):t()}getDbQueryCount(){return this.databaseTracker?this.databaseTracker.getQueryCount():0}resetDbQueryCount(){this.databaseTracker&&this.databaseTracker.resetQueryCount();}getDbNPlusOnePatterns(){return this.databaseTracker?this.databaseTracker.getNPlusOnePatterns():[]}async profile(e,t,n){return this.profiler?this.profiler.profile(e,t,n):t()}startProfileSpan(e,t){return this.profiler?this.profiler.startSpan(e,t):()=>{}}getProfiles(){return this.profiler?this.profiler.getProfiles():[]}getLatestProfile(){return this.profiler?this.profiler.getLatestProfile():null}async flushProfiles(){if(this.profiler)return this.profiler.flush()}getRemoteConfig(){return this.remoteConfigManager?.getConfig()??null}isRemoteConfigFeatureEnabled(e,t=true){return this.remoteConfigManager?.isFeatureEnabled(e,t)??t}onRemoteConfigChange(e){return this.remoteConfigManager?this.remoteConfigManager.onChange(e):()=>{}}setContext(e){this.context={...this.context,...e};}setUser(e){this.context.user=e,this.replayManager&&this.replayManager.setUser(e?{id:e.id}:null);}setTags(e){this.context.tags={...this.context.tags,...e};}clearUser(){this.context.user=void 0,this.replayManager&&this.replayManager.setUser(null);}addBreadcrumb(e){this.log("Breadcrumb added:",e);}captureError(e,t){if(!this.initialized){console.warn("[SitePong] SDK not initialized. Call init() first.");return}let n=this.formatError(e,t);this.errorQueue.push(n),this.log("Captured error:",n.message),this.replayManager?.isRecording()&&this.replayManager.flushOnError().catch(i=>{this.log("Failed to flush replay on error:",i);}),this.errorQueue.length>=this.config.maxBatchSize&&this.flush();}captureMessage(e,t="info",n){if(!this.initialized){console.warn("[SitePong] SDK not initialized. Call init() first.");return}let i={message:e,type:t,timestamp:new Date().toISOString(),url:this.getUrl(),userAgent:this.getUserAgent(),environment:this.config.environment,release:this.config.release,context:{...this.context,...n},replaySessionId:this.replayManager?.isRecording()&&this.replayManager.getSessionId()||void 0};this.errorQueue.push(i),this.log("Captured message:",e),this.errorQueue.length>=this.config.maxBatchSize&&this.flush();}async flush(){if(this.errorQueue.length===0)return;if(this.disabled){this.errorQueue=[];return}let e=[...this.errorQueue];this.errorQueue=[];try{let t=await fetch(`${this.config.endpoint}/api/errors/batch`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({errors:e})});if(!t.ok)throw new Error(`HTTP ${t.status}`);this.flushFailures=0,this.log(`Flushed ${e.length} errors`);}catch(t){if(this.flushFailures++,this.flushFailures>=Xe){this.disabled=true,console.warn(`[SitePong] SDK disabled after ${Xe} consecutive failures. Events will no longer be sent. This may be due to CORS issues or network problems. Check that ${this.config.endpoint} is accessible and has proper CORS headers.`);return}this.errorQueue.unshift(...e),this.log(`Failed to flush errors (attempt ${this.flushFailures}/${Xe}):`,t);}}formatError(e,t){let n=e instanceof Error,i=n?e.message:String(e),o=n?e.stack:new Error(i).stack,s=n?e.name:"Error";return {message:i,stack:o,type:s,timestamp:new Date().toISOString(),url:this.getUrl(),userAgent:this.getUserAgent(),environment:this.config.environment,release:this.config.release,context:{...this.context,...t},fingerprint:this.generateFingerprint(i,o,s),replaySessionId:this.replayManager?.isRecording()&&this.replayManager.getSessionId()||void 0}}generateFingerprint(e,t,n){let i=n||"Error",o=this.normalizeMessage(e),s=t?this.extractTopFrame(t):"",c=[i,o,s].join(`
|
|
6
|
-
`),
|
|
7
|
-
`);for(let n=1;n<t.length;n++){let i=t[n].trim();if(i&&(i.startsWith("at ")||/^\w+@/.test(i)))return i.replace(/:\d+\)?\s*$/,")")}return ""}setupAutoCapture(){typeof window<"u"&&typeof window.addEventListener=="function"?(window.addEventListener("error",e=>{this.captureError(e.error||e.message);}),window.addEventListener("unhandledrejection",e=>{let t=e.reason instanceof Error?e.reason:new Error(String(e.reason));this.captureError(t);}),this.log("Auto-capture enabled for browser")):typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",e=>{this.captureError(e),this.flush().finally(()=>process.exit(1));}),process.on("unhandledRejection",e=>{let t=e instanceof Error?e:new Error(String(e));this.captureError(t);}),this.log("Auto-capture enabled for Node.js"));}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval),typeof window<"u"&&typeof window.addEventListener=="function"&&(window.addEventListener("beforeunload",()=>{this.flush();}),window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushWithBeacon();}));}flushWithBeacon(){if(this.errorQueue.length===0||typeof navigator?.sendBeacon!="function")return;let e=[...this.errorQueue];this.errorQueue=[];let t=new Blob([JSON.stringify({errors:e,apiKey:this.config.apiKey})],{type:"application/json"});navigator.sendBeacon(`${this.config.endpoint}/api/errors/batch`,t),this.log(`Flushed ${e.length} errors via beacon`);}getUrl(){if(typeof window<"u")return window.location.href}getUserAgent(){if(typeof navigator<"u")return navigator.userAgent}log(...e){this.config.debug&&console.log("[SitePong]",...e);}},
|
|
5
|
+
`)||void 0}catch{return}}};var Zt="https://ingest.sitepong.com",en=2e4,tn=3600*1e3,me=3,nn=5e3,H=class{constructor(e){this.recording=false;this.sessionId=null;this.events=[];this.trimTimer=null;this.flushFailures=0;this.disabled=false;this.sessionStartTime=0;this.observer=null;this.mouseMoveBuffer=[];this.mouseMoveFlushTimer=null;this.cleanupFns=[];this.networkRecorder=null;this.consoleRecorder=null;this.lastSnapshotTime=0;this.snapshotCooldown=500;this.userContext=null;this.mutationBuffer=null;this.mutationFlushTimer=null;this.lastScrollTime=0;this.latestSnapshot=null;this.config={endpoint:Zt,enabled:true,maskInputs:true,maxSessionDuration:tn,flushInterval:5e3,maxBatchSize:100,sampleRate:1,debug:false,bufferDuration:en,...e};}start(){if(typeof window>"u"||typeof document>"u"||typeof window.addEventListener!="function")return false;if(this.recording)return true;if(!this.config.enabled)return false;if(Math.random()>this.config.sampleRate)return this.log("Session not sampled"),false;this.sessionId=this.getOrCreateSessionId(),this.sessionStartTime=this.getOrCreateStartTime(),this.recording=true,this.events=[],this.prefetchCrossOriginStylesheets();let e=J({maskInputs:this.config.maskInputs,blockSelector:this.config.blockSelector,maskSelector:this.config.maskSelector});return e&&this.addEvent("snapshot",e),this.setupMutationObserver(),this.setupEventListeners(),this.setupNetworkRecording(),this.setupConsoleRecording(),this.startTrimTimer(),this.log("Recording started (rolling buffer mode):",this.sessionId),true}stop(){if(this.recording){this.recording=false,this.observer&&(this.observer.disconnect(),this.observer=null),this.trimTimer&&(clearInterval(this.trimTimer),this.trimTimer=null),this.mouseMoveFlushTimer&&(clearTimeout(this.mouseMoveFlushTimer),this.mouseMoveFlushTimer=null),this.mutationFlushTimer&&this.flushMutationBuffer(),this.networkRecorder&&(this.networkRecorder.stop(),this.networkRecorder=null),this.consoleRecorder&&(this.consoleRecorder.stop(),this.consoleRecorder=null);for(let e of this.cleanupFns)e();this.cleanupFns=[],Ge(),this.log("Recording stopped:",this.sessionId),this.sessionId=null;}}isRecording(){return this.recording}getSessionId(){return this.sessionId}setUser(e){this.userContext=e;}async flushOnError(){if(!this.recording||!this.sessionId||this.disabled)return;this.flushMutationBuffer();let e=[];if(this.latestSnapshot&&e.push(this.latestSnapshot),e.push(...this.events),e.length===0)return;this.events=[],this.latestSnapshot=null;let t=J({maskInputs:this.config.maskInputs,blockSelector:this.config.blockSelector,maskSelector:this.config.maskSelector});t&&this.addEvent("snapshot",t);let n=this.config.replayEndpoint||`${this.config.endpoint}/api/replays`;try{let i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({sessionId:this.sessionId,events:e,startedAt:new Date(this.sessionStartTime).toISOString(),pageUrl:typeof location<"u"?location.href:void 0,pageTitle:typeof document<"u"?document.title:void 0,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,userId:this.userContext?.id,trigger:"error"})});if(!i.ok)throw new Error(`HTTP ${i.status}`);this.flushFailures=0,this.log(`Flushed ${e.length} replay events (error-triggered)`);}catch(i){if(this.flushFailures++,this.flushFailures>=me){this.disabled=true,console.warn(`[SitePong Replay] Disabled after ${me} consecutive failures. Check that ${n} is accessible and has proper CORS headers.`);return}this.log(`Failed to flush replay events (attempt ${this.flushFailures}/${me}):`,i);}}async flush(){return this.flushOnError()}addEvent(e,t){if(!this.recording)return;if(Date.now()-this.sessionStartTime>this.config.maxSessionDuration){this.stop();return}let n={type:e,timestamp:Date.now()-this.sessionStartTime,data:t};e==="snapshot"&&(this.latestSnapshot=n),this.events.push(n);}trimBuffer(){if(this.events.length===0)return;let t=Date.now()-this.sessionStartTime-this.config.bufferDuration,n=0;for(let i=0;i<this.events.length;i++){if(this.events[i].timestamp>=t){n=i;break}this.events[i].type==="snapshot"&&(this.latestSnapshot=this.events[i]),n=i+1;}n>0&&(this.events=this.events.slice(n));}flushMutationBuffer(){this.mutationBuffer&&(this.mutationBuffer.adds.length||this.mutationBuffer.removes.length||this.mutationBuffer.attributes.length||this.mutationBuffer.texts.length)&&this.addEvent("mutation",this.mutationBuffer),this.mutationBuffer=null,this.mutationFlushTimer&&clearTimeout(this.mutationFlushTimer),this.mutationFlushTimer=null;}setupMutationObserver(){typeof MutationObserver>"u"||(this.observer=new MutationObserver(e=>{this.mutationBuffer||(this.mutationBuffer={adds:[],removes:[],attributes:[],texts:[]});for(let t of e)switch(t.type){case "childList":{for(let n of Array.from(t.addedNodes)){let i=Y(n,{maskInputs:this.config.maskInputs,blockSelector:this.config.blockSelector,maskSelector:this.config.maskSelector});i&&this.mutationBuffer.adds.push({parentId:y(t.target),nextId:t.nextSibling?y(t.nextSibling):null,node:i});}for(let n of Array.from(t.removedNodes))this.mutationBuffer.removes.push({parentId:y(t.target),id:y(n)});break}case "attributes":{let n=t.target,i=t.attributeName||"",o=n.getAttribute(i),s={[i]:o},l=n.tagName?.toLowerCase();if(l==="style"||l==="link"&&n.getAttribute("rel")==="stylesheet"){let c=Q(n);c&&(s._cssText=c);}if(i==="class"||i==="style"){let c=ge(n);c&&(s._computedStyle=c);}this.mutationBuffer.attributes.push({id:y(t.target),attributes:s});break}case "characterData":{let n=t.target.textContent||"",i=t.target.parentElement;if(i&&this.config.maskSelector&&i.matches(this.config.maskSelector)&&(n=n.replace(/\S/g,"*")),this.mutationBuffer.texts.push({id:y(t.target),value:n}),i&&i.tagName?.toLowerCase()==="style"){let o=Q(i);o&&this.mutationBuffer.attributes.push({id:y(i),attributes:{_cssText:o}});}break}}this.mutationFlushTimer||(this.mutationFlushTimer=setTimeout(()=>this.flushMutationBuffer(),1e3));}),this.observer.observe(document.documentElement,{childList:true,subtree:true,attributes:true,characterData:true,attributeOldValue:false}));}setupEventListeners(){let e=u=>{this.mouseMoveBuffer.push({x:u.clientX,y:u.clientY,t:Date.now()-this.sessionStartTime}),this.mouseMoveFlushTimer||(this.mouseMoveFlushTimer=setTimeout(()=>{if(this.mouseMoveBuffer.length>0){let p={positions:[...this.mouseMoveBuffer]};this.addEvent("mouse_move",p),this.mouseMoveBuffer=[];}this.mouseMoveFlushTimer=null;},1e3));},t=u=>{let p=u.target;this.addEvent("mouse_click",{x:u.clientX,y:u.clientY,targetId:y(p),button:u.button}),this.takeInteractionSnapshot();},n=u=>{let p=u.target;this.addEvent("mouse_click",{x:u.clientX,y:u.clientY,targetId:y(p),button:2}),this.takeInteractionSnapshot();},i=()=>{this.addEvent("mouse_leave",{});},o=u=>{let p=u.touches[0];if(!p)return;let g=u.target;this.addEvent("touch",{x:p.clientX,y:p.clientY,targetId:y(g)}),this.takeInteractionSnapshot();},s=null,l=()=>{s&&clearTimeout(s),s=setTimeout(()=>{let u={id:0,x:window.scrollX,y:window.scrollY};this.addEvent("scroll",u),this.takeInteractionSnapshot();},1e3);},c=u=>{let p=u.target;if(!p)return;let g={id:y(p),value:this.config.maskInputs?"***":p.value};"checked"in p&&(g.isChecked=p.checked),this.addEvent("input",g);},d=()=>{this.addEvent("resize",{width:window.innerWidth,height:window.innerHeight});},f=u=>{u.target&&u.target!==document&&this.addEvent("focus",{id:y(u.target)});},h=u=>{u.target&&u.target!==document&&this.addEvent("blur",{id:y(u.target)});};document.addEventListener("mousemove",e,{passive:true}),document.addEventListener("click",t,{passive:true}),document.addEventListener("contextmenu",n,{passive:true}),document.documentElement.addEventListener("mouseleave",i,{passive:true}),document.addEventListener("touchstart",o,{passive:true}),window.addEventListener("scroll",l,{passive:true}),document.addEventListener("input",c,{passive:true}),window.addEventListener("resize",d,{passive:true}),document.addEventListener("focus",f,{passive:true,capture:true}),document.addEventListener("blur",h,{passive:true,capture:true}),this.cleanupFns.push(()=>document.removeEventListener("mousemove",e),()=>document.removeEventListener("click",t),()=>document.removeEventListener("contextmenu",n),()=>document.documentElement.removeEventListener("mouseleave",i),()=>document.removeEventListener("touchstart",o),()=>window.removeEventListener("scroll",l),()=>document.removeEventListener("input",c),()=>window.removeEventListener("resize",d),()=>document.removeEventListener("focus",f,{capture:true}),()=>document.removeEventListener("blur",h,{capture:true}));}setupNetworkRecording(){if(!this.config.recordNetwork)return;let e=this.config.replayEndpoint||this.config.endpoint;this.networkRecorder=new O(t=>{this.addEvent("network",t.data);},{captureHeaders:this.config.captureNetworkHeaders,urlFilter:t=>!t.startsWith(e)}),this.networkRecorder.start();}setupConsoleRecording(){this.config.recordConsole&&(this.consoleRecorder=new N(e=>{this.addEvent("console",e.data);},{levels:this.config.consoleLevels}),this.consoleRecorder.start());}startTrimTimer(){this.trimTimer=setInterval(()=>{this.trimBuffer();},nn);}takeInteractionSnapshot(){let e=Date.now();if(e-this.lastSnapshotTime<this.snapshotCooldown)return;this.lastSnapshotTime=e;let t=J({maskInputs:this.config.maskInputs,blockSelector:this.config.blockSelector,maskSelector:this.config.maskSelector});t&&this.addEvent("snapshot",t);}getOrCreateSessionId(){let e="__sp_replay_session";try{let n=sessionStorage.getItem(e);if(n)return n}catch{}let t=`rep_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`;try{sessionStorage.setItem(e,t);}catch{}return t}getOrCreateStartTime(){let e="__sp_replay_start";try{let n=sessionStorage.getItem(e);if(n)return parseInt(n,10)}catch{}let t=Date.now();try{sessionStorage.setItem(e,String(t));}catch{}return t}prefetchCrossOriginStylesheets(){if(typeof document>"u")return;let e=document.querySelectorAll('link[rel="stylesheet"]');for(let t of Array.from(e)){let n=t;if(n.href&&n.sheet)try{n.sheet.cssRules;}catch{Xe(n.href).catch(()=>{});}}}log(...e){this.config.debug&&console.log("[SitePong Replay]",...e);}};var rn="https://ingest.sitepong.com";var B=class{constructor(e){this.metrics=[];this.flushTimer=null;this.flushFailures=0;this.disabled=false;this.vitals={};this.activeTransactions=new Map;this.config={endpoint:rn,enabled:true,webVitals:true,navigationTiming:true,resourceTiming:false,flushInterval:1e4,sampleRate:1,debug:false,...e},this.sampled=Math.random()<=this.config.sampleRate;}init(){!this.config.enabled||!this.sampled||typeof window>"u"||typeof window.addEventListener!="function"||(this.config.webVitals&&this.observeWebVitals(),this.config.navigationTiming&&this.collectNavigationTiming(),this.startFlushTimer(),this.log("Performance monitoring initialized"));}startTransaction(e,t){let n=`txn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,i={id:n,name:e,startTime:performance.now(),status:"running",spans:[],data:t};return this.activeTransactions.set(n,i),this.log("Transaction started:",e,n),n}endTransaction(e,t="ok"){let n=this.activeTransactions.get(e);if(!n){this.log("Transaction not found:",e);return}n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.status=t;for(let i of n.spans)i.status==="running"&&(i.endTime=n.endTime,i.duration=i.endTime-i.startTime,i.status=t);this.activeTransactions.delete(e),this.addMetric({type:"transaction",name:n.name,value:n.duration,unit:"ms",timestamp:new Date().toISOString(),url:typeof window<"u"?window.location.href:void 0,transaction:n}),this.log("Transaction ended:",n.name,`${n.duration.toFixed(1)}ms`);}startSpan(e,t,n){let i=this.activeTransactions.get(e);if(!i)return this.log("Transaction not found for span:",e),"";let o={id:`span_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,name:t,startTime:performance.now(),status:"running",data:n};return i.spans.push(o),o.id}endSpan(e,t,n="ok"){let i=this.activeTransactions.get(e);if(!i)return;let o=i.spans.find(s=>s.id===t);o&&(o.endTime=performance.now(),o.duration=o.endTime-o.startTime,o.status=n);}getVitals(){return {...this.vitals}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush();}observeWebVitals(){if(!(typeof PerformanceObserver>"u")){try{new PerformanceObserver(t=>{let n=t.getEntries(),i=n[n.length-1];i&&(this.vitals.lcp=i.startTime,this.reportVital("LCP",i.startTime));}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{new PerformanceObserver(t=>{let n=t.getEntries()[0];if(n){let i=n.processingStart-n.startTime;this.vitals.fid=i,this.reportVital("FID",i);}}).observe({type:"first-input",buffered:!0});}catch{}try{let e=0;new PerformanceObserver(n=>{for(let i of n.getEntries()){let o=i;o.hadRecentInput||(e+=o.value);}this.vitals.cls=e;}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e>0&&this.reportVital("CLS",e,"score");});}catch{}try{new PerformanceObserver(t=>{let n=t.getEntries().find(i=>i.name==="first-contentful-paint");n&&(this.vitals.fcp=n.startTime,this.reportVital("FCP",n.startTime));}).observe({type:"paint",buffered:!0});}catch{}try{let e=0;new PerformanceObserver(n=>{for(let i of n.getEntries()){let o=i.duration;o>e&&(e=o,this.vitals.inp=e);}}).observe({type:"event",buffered:!0});}catch{}}}collectNavigationTiming(){if(typeof window>"u"||!window.performance)return;let e=()=>{let t=performance.getEntriesByType("navigation")[0];if(!t)return;let n=t.responseStart-t.requestStart;this.vitals.ttfb=n,this.reportVital("TTFB",n),this.addMetric({type:"navigation",name:"page_load",value:t.loadEventEnd-t.startTime,unit:"ms",timestamp:new Date().toISOString(),url:window.location.href,data:{dns:t.domainLookupEnd-t.domainLookupStart,tcp:t.connectEnd-t.connectStart,ttfb:n,domContentLoaded:t.domContentLoadedEventEnd-t.startTime,domComplete:t.domComplete-t.startTime,transferSize:t.transferSize,encodedBodySize:t.encodedBodySize,decodedBodySize:t.decodedBodySize}});};document.readyState==="complete"?setTimeout(e,0):window.addEventListener("load",()=>setTimeout(e,0));}reportVital(e,t,n="ms"){this.addMetric({type:"web_vital",name:e,value:t,unit:n,timestamp:new Date().toISOString(),url:typeof window<"u"?window.location.href:void 0});}addMetric(e){this.metrics.push(e);}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flush();});}async flush(){if(this.metrics.length===0)return;if(this.disabled){this.metrics=[];return}let e=[...this.metrics];this.metrics=[];let t=this.config.performanceEndpoint||`${this.config.endpoint}/api/performance`;try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({metrics:e})});if(!n.ok)throw new Error(`HTTP ${n.status}`);this.flushFailures=0,this.log(`Flushed ${e.length} performance metrics`);}catch(n){if(this.flushFailures++,this.flushFailures>=3){this.disabled=true,console.warn(`[SitePong Performance] Disabled after 3 consecutive failures. Check that ${t} is accessible and has proper CORS headers.`);return}this.metrics.unshift(...e),this.log(`Failed to flush metrics (attempt ${this.flushFailures}/3):`,n);}}log(...e){this.config.debug&&console.log("[SitePong Performance]",...e);}};function Qe(r){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint8Array(r);return crypto.getRandomValues(t),Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}}catch{}let e="";for(let t=0;t<r;t++)e+=Math.floor(Math.random()*256).toString(16).padStart(2,"0");return e}function ve(){return Qe(16)}function ne(){return Qe(8)}function ye(){return {traceId:ve(),spanId:ne(),parentSpanId:null,sampled:true}}function ee(r){let e=r.sampled?"01":"00";return {traceparent:`00-${r.traceId}-${r.spanId}-${e}`,tracestate:`sitepong=${r.spanId}`}}function Ye(r){let e=r.traceparent||r.Traceparent;if(!e)return null;let t=e.split("-");if(t.length!==4)return null;let[n,i,o,s]=t;if(n!=="00"||i.length!==32||!/^[0-9a-f]{32}$/.test(i)||o.length!==16||!/^[0-9a-f]{16}$/.test(o)||s.length!==2||!/^[0-9a-f]{2}$/.test(s))return null;let l=(parseInt(s,16)&1)===1;return {traceId:i,spanId:ne(),parentSpanId:o,sampled:l}}var te=class{constructor(e){this.originalFetch=null;this.targets=e;}shouldPropagate(e){return this.targets.some(t=>{if(t.includes("*")){let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}return e.startsWith(t)})}injectHeaders(e,t,n){if(!this.shouldPropagate(e))return t;let i=ee(n);return {...t,...i}}start(){if(typeof window>"u"||!window.fetch||this.originalFetch)return;this.originalFetch=window.fetch;let e=this;window.fetch=function(t,n){let i=typeof t=="string"?t:t instanceof URL?t.toString():t.url;if(e.shouldPropagate(i)){let o=ye(),s=ee(o),l={};if(n?.headers)if(n.headers instanceof Headers)n.headers.forEach((f,h)=>{l[h]=f;});else if(Array.isArray(n.headers))for(let[f,h]of n.headers)l[f]=h;else Object.assign(l,n.headers);let c={...l,...s},d={...n,headers:c};return e.originalFetch.call(window,t,d)}return e.originalFetch.call(window,t,n)};}stop(){typeof window>"u"||this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null);}};var V=class{constructor(e){this.apiKey=e.apiKey,this.endpoint=e.endpoint,this.debug=e.debug||false;}async checkin(e,t={}){try{let n=await fetch(`${this.endpoint}/api/sdk/crons`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify({slug:e,status:t.status||"ok",duration_ms:t.duration_ms,message:t.message,environment:t.environment})});if(!n.ok)throw new Error(`HTTP ${n.status}`);this.log(`Check-in sent for "${e}" (${t.status||"ok"})`);}catch(n){this.log("Failed to send check-in:",n);}}start(e,t){let n=Date.now();return this.checkin(e,{status:"in_progress",environment:t}),{ok:async i=>{let o=Date.now()-n;await this.checkin(e,{status:"ok",duration_ms:o,message:i,environment:t});},error:async i=>{let o=Date.now()-n;await this.checkin(e,{status:"error",duration_ms:o,message:i,environment:t});}}}wrap(e,t,n){let i=this.start(e,n);return t().then(async o=>(await i.ok(),o),async o=>{throw await i.error(o?.message||String(o)),o})}log(...e){this.debug&&console.log("[SitePong:Cron]",...e);}};var U=class{constructor(e){this.queue=[];this.flushTimer=null;this.apiKey=e.apiKey,this.endpoint=e.endpoint,this.debug=e.debug||false,this.flushInterval=e.flushInterval||1e4,this.maxBatchSize=e.maxBatchSize||100,this.startFlushTimer();}increment(e,t=1,n){this.enqueue(e,t,"counter",n);}decrement(e,t=1,n){this.enqueue(e,-t,"counter",n);}gauge(e,t,n){this.enqueue(e,t,"gauge",n);}histogram(e,t,n){this.enqueue(e,t,"histogram",n);}distribution(e,t,n){this.enqueue(e,t,"distribution",n);}async time(e,t,n){let i=Date.now();try{let o=await t();return this.distribution(e,Date.now()-i,{...n,unit:n?.unit||"ms"}),o}catch(o){throw this.distribution(e,Date.now()-i,{...n,unit:n?.unit||"ms",tags:{...n?.tags,error:"true"}}),o}}startTimer(e,t){let n=Date.now();return {stop:()=>{this.distribution(e,Date.now()-n,{...t,unit:t?.unit||"ms"});}}}async flush(){if(this.queue.length===0)return;let e=[...this.queue];this.queue=[];try{let t=await fetch(`${this.endpoint}/api/sdk/metrics`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify({metrics:e})});if(!t.ok)throw new Error(`HTTP ${t.status}`);this.log(`Flushed ${e.length} metrics`);}catch(t){this.queue.unshift(...e),this.log("Failed to flush metrics:",t);}}async destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush();}enqueue(e,t,n,i){this.queue.push({name:e,value:t,type:n,unit:i?.unit,tags:i?.tags,timestamp:i?.timestamp||new Date().toISOString()}),this.queue.length>=this.maxBatchSize&&this.flush();}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.flushInterval),typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushWithBeacon();});}flushWithBeacon(){if(this.queue.length===0||typeof navigator?.sendBeacon!="function")return;let e=[...this.queue];this.queue=[];let t=new Blob([JSON.stringify({metrics:e,apiKey:this.apiKey})],{type:"application/json"});navigator.sendBeacon(`${this.endpoint}/api/sdk/metrics`,t),this.log(`Flushed ${e.length} metrics via beacon`);}log(...e){this.debug&&console.log("[SitePong:Metrics]",...e);}};var $=class{constructor(e){this.queue=[];this.flushTimer=null;this.queryCounter=0;this.nPlusOneDetector=new Map;this.config={slowQueryThreshold:1e3,maxBatchSize:50,flushInterval:1e4,redactParams:true,...e},this.startFlushTimer();}async track(e,t,n){let i=Date.now();this.queryCounter++;try{let o=await t(),s=Date.now()-i;return this.recordQuery({query:this.config.redactParams?this.redactQuery(e):e,duration_ms:s,timestamp:new Date().toISOString(),source:n,is_slow:s>=(this.config.slowQueryThreshold||1e3)}),this.detectNPlusOne(e),o}catch(o){let s=Date.now()-i;throw this.recordQuery({query:this.config.redactParams?this.redactQuery(e):e,duration_ms:s,timestamp:new Date().toISOString(),source:n,error:o instanceof Error?o.message:String(o)}),o}}trackSync(e,t,n){let i=Date.now();this.queryCounter++;try{let o=t(),s=Date.now()-i;return this.recordQuery({query:this.config.redactParams?this.redactQuery(e):e,duration_ms:s,timestamp:new Date().toISOString(),source:n,is_slow:s>=(this.config.slowQueryThreshold||1e3)}),o}catch(o){let s=Date.now()-i;throw this.recordQuery({query:this.config.redactParams?this.redactQuery(e):e,duration_ms:s,timestamp:new Date().toISOString(),source:n,error:o instanceof Error?o.message:String(o)}),o}}getQueryCount(){return this.queryCounter}resetQueryCount(){this.queryCounter=0,this.nPlusOneDetector.clear();}getNPlusOnePatterns(){let e=[];for(let[t,{count:n}]of this.nPlusOneDetector.entries())n>=5&&e.push({query:t,count:n});return e}async flush(){if(this.queue.length===0)return;let e=[...this.queue];this.queue=[];try{let t=await fetch(`${this.config.endpoint}/api/sdk/metrics`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({metrics:e.map(n=>({name:"db.query",value:n.duration_ms,type:"distribution",unit:"ms",tags:{query:n.query.substring(0,200),source:n.source||"unknown",is_slow:String(n.is_slow||!1),...n.error?{error:"true"}:{}},timestamp:n.timestamp}))})});if(!t.ok)throw new Error(`HTTP ${t.status}`);this.log(`Flushed ${e.length} query events`);}catch(t){this.queue.unshift(...e),this.log("Failed to flush query events:",t);}}async destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush();}recordQuery(e){this.queue.push(e),this.queue.length>=(this.config.maxBatchSize||50)&&this.flush(),e.is_slow&&this.log(`Slow query (${e.duration_ms}ms):`,e.query.substring(0,100));}detectNPlusOne(e){let t=this.normalizeQuery(e),n=Date.now(),i=this.nPlusOneDetector.get(t);if(i?n-i.since<1e3?(i.count++,i.count===5&&this.log(`N+1 query detected! Pattern repeated ${i.count} times:`,t.substring(0,100))):this.nPlusOneDetector.set(t,{count:1,since:n}):this.nPlusOneDetector.set(t,{count:1,since:n}),this.nPlusOneDetector.size>100){let o=[...this.nPlusOneDetector.entries()];o.sort((s,l)=>s[1].since-l[1].since);for(let s=0;s<50;s++)this.nPlusOneDetector.delete(o[s][0]);}}normalizeQuery(e){return e.replace(/\s+/g," ").replace(/'[^']*'/g,"?").replace(/\b\d+\b/g,"?").trim().substring(0,300)}redactQuery(e){return e.replace(/'[^']*'/g,"'***'").replace(/\b\d{4,}\b/g,"***")}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval||1e4);}log(...e){this.config.debug&&console.log("[SitePong:DB]",...e);}};var z=class{constructor(e){this.profiles=[];this.activeProfile=null;this.frameStack=[];this.flushTimer=null;this.config={sampleRate:.1,maxDuration:3e4,flushInterval:3e4,...e},this.startFlushTimer();}async profile(e,t,n){if(Math.random()>(this.config.sampleRate||.1))return t();let i=this.generateId(),o=performance.now();this.activeProfile={id:i,name:e,startTime:o,duration_ms:0,frames:[],metadata:n},this.frameStack=[];let s={name:e,start_ms:0,duration_ms:0,children:[],metadata:n};this.frameStack.push(s);try{let l=await t();return s.duration_ms=performance.now()-o,this.activeProfile.duration_ms=s.duration_ms,this.activeProfile.frames=[s],s.duration_ms<=(this.config.maxDuration||3e4)&&this.profiles.push(this.activeProfile),this.activeProfile=null,this.frameStack=[],l}catch(l){throw s.duration_ms=performance.now()-o,s.metadata={...s.metadata,error:true},this.activeProfile&&(this.activeProfile.duration_ms=s.duration_ms,this.activeProfile.frames=[s],this.profiles.push(this.activeProfile)),this.activeProfile=null,this.frameStack=[],l}}startSpan(e,t){if(!this.activeProfile)return ()=>{};let n=performance.now()-this.activeProfile.startTime,i={name:e,start_ms:n,duration_ms:0,children:[],metadata:t},o=this.frameStack[this.frameStack.length-1];return o&&o.children.push(i),this.frameStack.push(i),()=>{i.duration_ms=performance.now()-this.activeProfile.startTime-i.start_ms,this.frameStack.pop();}}getProfiles(){return [...this.profiles]}getLatestProfile(){return this.profiles.length>0?this.profiles[this.profiles.length-1]:null}async flush(){if(this.profiles.length===0)return;let e=[...this.profiles];this.profiles=[];try{let t=await fetch(`${this.config.endpoint}/api/sdk/metrics`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({metrics:e.map(n=>({name:`profile.${n.name}`,value:n.duration_ms,type:"distribution",unit:"ms",tags:{profile_id:n.id,frame_count:String(Je(n.frames)),...n.metadata||{}},timestamp:new Date(Date.now()-n.duration_ms).toISOString()}))})});if(!t.ok)throw new Error(`HTTP ${t.status}`);this.log(`Flushed ${e.length} profiles`);}catch(t){this.profiles.unshift(...e),this.log("Failed to flush profiles:",t);}}async destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush();}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval||3e4);}generateId(){return `prof_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,8)}`}log(...e){this.config.debug&&console.log("[SitePong:Profiler]",...e);}};function Je(r){let e=r.length;for(let t of r)e+=Je(t.children);return e}var be={features:{},sampling:{errors:1,analytics:1,replay:1,performance:1},transport:{flushInterval:1e4,maxBatchSize:20,maxRetries:3},autocapture:{clicks:true,forms:true,pageviews:true,appState:true,screenViews:true},ttl:300};var Ze="sitepong_remote_config",et="sitepong_remote_config_ts",P=class{constructor(e){this.listeners=[];this.refreshTimer=null;this.initialized=false;this.options=e,this.config={...be};}async init(){await this.loadFromCache(),this.initialized=true,this.fetchAndApply().catch(e=>{this.log("Failed to fetch remote config:",e);});}getConfig(){return this.config}isFeatureEnabled(e,t=true){return this.config.features[e]??t}onChange(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e);}}isInitialized(){return this.initialized}destroy(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),this.listeners=[];}async loadFromCache(){let e=this.options.storage;if(e)try{let t=await e.getItem(Ze),n=await e.getItem(et);if(t&&n){let i=Date.now()-parseInt(n,10),o=this.config.ttl*1e3;if(i<o){let s=JSON.parse(t);this.config=s,this.log("Loaded config from cache (age:",Math.round(i/1e3),"s)");}}}catch{this.log("Failed to load cached config");}}async fetchAndApply(){try{let e=le(),t=new URLSearchParams({platform:e,...this.options.sdkVersion?{sdkVersion:this.options.sdkVersion}:{}}),n=await fetch(`${this.options.endpoint}/api/sdk/config?${t}`,{method:"GET",headers:{"X-API-Key":this.options.apiKey}});if(!n.ok)throw new Error(`HTTP ${n.status}`);let i=await n.json();this.config=i.config;for(let o of this.listeners)try{o(this.config);}catch{}await this.saveToCache(),this.scheduleRefresh(),i.config.minSdkVersion&&this.options.sdkVersion&&this.compareVersions(this.options.sdkVersion,i.config.minSdkVersion)<0&&console.warn(`[SitePong] SDK version ${this.options.sdkVersion} is outdated. Minimum recommended: ${i.config.minSdkVersion}. Please update.`),this.log("Remote config fetched successfully");}catch(e){throw this.scheduleRefresh(),e}}async saveToCache(){let e=this.options.storage;if(e)try{await e.setItem(Ze,JSON.stringify(this.config)),await e.setItem(et,String(Date.now()));}catch{this.log("Failed to cache remote config");}}scheduleRefresh(){this.refreshTimer&&clearTimeout(this.refreshTimer);let e=this.config.ttl*1e3;this.refreshTimer=setTimeout(()=>{this.fetchAndApply().catch(t=>{this.log("Refresh failed:",t);});},e);}compareVersions(e,t){let n=e.split(".").map(Number),i=t.split(".").map(Number);for(let o=0;o<3;o++){let s=n[o]||0,l=i[o]||0;if(s>l)return 1;if(s<l)return -1}return 0}log(...e){this.options.debug&&console.log("[SitePong RemoteConfig]",...e);}};var m="https://ingest.sitepong.com",on=10,sn=5e3,we=3,Se=class{constructor(){this.errorQueue=[];this.flushTimer=null;this.context={};this.initialized=false;this.flushFailures=0;this.disabled=false;this.flagManager=null;this.analyticsManager=null;this.fingerprintManager=null;this.replayManager=null;this.performanceManager=null;this.cronManager=null;this.metricsManager=null;this.databaseTracker=null;this.profiler=null;this.remoteConfigManager=null;this.config={apiKey:"",endpoint:m,environment:"production",release:"",autoCapture:true,maxBatchSize:on,flushInterval:sn,debug:false};}init(e){if(!e.apiKey){console.error("[SitePong] API key is required");return}if(this.config={...this.config,...e},this.initialized=true,this.config.autoCapture&&this.setupAutoCapture(),this.startFlushTimer(),this.log("Initialized with endpoint:",this.config.endpoint),e.enableFlags&&(this.flagManager=new C({apiKey:e.apiKey,endpoint:e.flagsEndpoint||e.endpoint||m,debug:e.debug}),this.flagManager.init().catch(t=>{this.log("Failed to initialize flags:",t);})),e.analytics?.enabled&&(this.analyticsManager&&this.analyticsManager.destroy(),this.analyticsManager=new M({apiKey:e.apiKey,endpoint:e.endpoint||m,enabled:true,autocapturePageviews:e.analytics.autocapturePageviews,autocaptureClicks:e.analytics.autocaptureClicks,autocaptureForms:e.analytics.autocaptureForms,autocapture:e.analytics.autocapture,maxBatchSize:e.analytics.maxBatchSize,flushInterval:e.analytics.flushInterval,eventsEndpoint:e.analytics.eventsEndpoint,debug:e.debug}),this.analyticsManager.init()),e.fingerprint?.enabled&&(this.fingerprintManager=new _({apiKey:e.apiKey,endpoint:e.endpoint||m,enabled:true,extendedSignals:e.fingerprint.extendedSignals,visitorEndpoint:e.fingerprint.visitorEndpoint,debug:e.debug})),e.performance?.enabled&&(this.performanceManager&&this.performanceManager.destroy(),this.performanceManager=new B({apiKey:e.apiKey,endpoint:e.endpoint||m,enabled:true,webVitals:e.performance.webVitals,navigationTiming:e.performance.navigationTiming,resourceTiming:e.performance.resourceTiming,sampleRate:e.performance.sampleRate,flushInterval:e.performance.flushInterval,performanceEndpoint:e.performance.performanceEndpoint,debug:e.debug}),this.performanceManager.init()),e.replay?.enabled&&(this.replayManager&&this.replayManager.stop(),this.replayManager=new H({apiKey:e.apiKey,endpoint:e.endpoint||m,enabled:true,maskInputs:e.replay.maskInputs,blockSelector:e.replay.blockSelector,maskSelector:e.replay.maskSelector,sampleRate:e.replay.sampleRate,maxSessionDuration:e.replay.maxSessionDuration,flushInterval:e.replay.flushInterval,replayEndpoint:e.replay.replayEndpoint,recordNetwork:e.replay.recordNetwork,captureNetworkHeaders:e.replay.captureNetworkHeaders,recordConsole:e.replay.recordConsole,consoleLevels:e.replay.consoleLevels,bufferDuration:e.replay.bufferDuration,debug:e.debug}),this.replayManager.start()),e.crons?.enabled&&(this.cronManager=new V({apiKey:e.apiKey,endpoint:e.endpoint||m,debug:e.debug})),e.database?.enabled&&(this.databaseTracker=new $({apiKey:e.apiKey,endpoint:e.endpoint||m,debug:e.debug,slowQueryThreshold:e.database.slowQueryThreshold,redactParams:e.database.redactParams})),e.metrics?.enabled&&(this.metricsManager=new U({apiKey:e.apiKey,endpoint:e.endpoint||m,debug:e.debug,flushInterval:e.metrics.flushInterval,maxBatchSize:e.metrics.maxBatchSize})),e.profiling?.enabled&&(this.profiler=new z({apiKey:e.apiKey,endpoint:e.endpoint||m,debug:e.debug,sampleRate:e.profiling.sampleRate,maxDuration:e.profiling.maxDuration,flushInterval:e.profiling.flushInterval})),e.remoteConfig?.enabled!==false){let t=e._storageAdapter||ce();this.remoteConfigManager=new P({apiKey:e.apiKey,endpoint:e.endpoint||m,storage:t,debug:e.debug}),this.remoteConfigManager.init().catch(n=>{this.log("Failed to initialize remote config:",n);});}}initRN(e){if(!e.apiKey){console.error("[SitePong] API key is required");return}if(this.config={...this.config,...e},this.initialized=true,this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval),this.log("Initialized (React Native) with endpoint:",this.config.endpoint),e.enableFlags&&(this.flagManager=new C({apiKey:e.apiKey,endpoint:e.flagsEndpoint||e.endpoint||m,debug:e.debug}),this.flagManager.init().catch(t=>{this.log("Failed to initialize flags:",t);})),e.analytics?.enabled&&(this.analyticsManager&&this.analyticsManager.destroy(),this.analyticsManager=new M({apiKey:e.apiKey,endpoint:e.endpoint||m,enabled:true,maxBatchSize:e.analytics.maxBatchSize,flushInterval:e.analytics.flushInterval,eventsEndpoint:e.analytics.eventsEndpoint,debug:e.debug}),this.analyticsManager.initHeadless()),e.crons?.enabled&&(this.cronManager=new V({apiKey:e.apiKey,endpoint:e.endpoint||m,debug:e.debug})),e.metrics?.enabled&&(this.metricsManager=new U({apiKey:e.apiKey,endpoint:e.endpoint||m,debug:e.debug,flushInterval:e.metrics.flushInterval,maxBatchSize:e.metrics.maxBatchSize})),e.database?.enabled&&(this.databaseTracker=new $({apiKey:e.apiKey,endpoint:e.endpoint||m,debug:e.debug,slowQueryThreshold:e.database.slowQueryThreshold,redactParams:e.database.redactParams})),e.profiling?.enabled&&(this.profiler=new z({apiKey:e.apiKey,endpoint:e.endpoint||m,debug:e.debug,sampleRate:e.profiling.sampleRate,maxDuration:e.profiling.maxDuration,flushInterval:e.profiling.flushInterval})),e.remoteConfig?.enabled!==false){let t=e._storageAdapter||ce();this.remoteConfigManager=new P({apiKey:e.apiKey,endpoint:e.endpoint||m,storage:t,debug:e.debug}),this.remoteConfigManager.init().catch(n=>{this.log("Failed to initialize remote config:",n);});}}isInitialized(){return this.initialized}getFlag(e,t=false){return this.flagManager?this.flagManager.getFlag(e,t):(this.log("Flags not enabled. Set enableFlags: true in init()"),t)}getAllFlags(){return this.flagManager?this.flagManager.getAllFlags():{}}async waitForFlags(){this.flagManager&&await this.flagManager.waitForInit();}areFlagsReady(){return this.flagManager?.isInitialized()??false}getVariant(e,t=null){return this.flagManager?this.flagManager.getVariant(e,t):(this.log("Flags not enabled. Set enableFlags: true in init()"),t)}getVariantPayload(e,t=null){return this.flagManager?this.flagManager.getVariantPayload(e,t):t}async refreshFlags(){this.flagManager&&await this.flagManager.refresh();}track(e,t){if(!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.track(e,t);}trackPageView(e,t){if(!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.trackPageView(e,t);}identify(e,t){this.replayManager&&this.replayManager.setUser({id:e});try{let n="./react-native/push",{reRegisterTokensWithUserId:i}=Te(n);i(e);}catch{}if(!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.identify(e,t);}group(e,t){if(!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.group(e,t);}resetAnalytics(){this.analyticsManager&&this.analyticsManager.reset();}async getVisitorId(){if(!this.fingerprintManager)throw new Error("Fingerprint not enabled. Set fingerprint.enabled: true in init()");return this.fingerprintManager.getVisitorId()}async getDeviceSignals(){if(!this.fingerprintManager)throw new Error("Fingerprint not enabled. Set fingerprint.enabled: true in init()");return this.fingerprintManager.getDeviceSignals()}async getFraudCheck(){if(!this.fingerprintManager)throw new Error("Fingerprint not enabled. Set fingerprint.enabled: true in init()");return this.fingerprintManager.getFraudCheck()}startReplay(){return this.replayManager?this.replayManager.start():(this.log("Replay not enabled. Set replay.enabled: true in init()"),false)}stopReplay(){this.replayManager&&this.replayManager.stop();}isReplayRecording(){return this.replayManager?.isRecording()??false}getReplaySessionId(){return this.replayManager?.getSessionId()??null}startTransaction(e,t){return this.performanceManager?this.performanceManager.startTransaction(e,t):(this.log("Performance not enabled. Set performance.enabled: true in init()"),"")}endTransaction(e,t="ok"){this.performanceManager&&this.performanceManager.endTransaction(e,t);}startSpan(e,t,n){return this.performanceManager?this.performanceManager.startSpan(e,t,n):""}endSpan(e,t,n="ok"){this.performanceManager&&this.performanceManager.endSpan(e,t,n);}getWebVitals(){return this.performanceManager?this.performanceManager.getVitals():{}}cronCheckin(e,t){return this.cronManager?this.cronManager.checkin(e,t):(this.log("Cron monitoring not enabled. Set crons.enabled: true in init()"),Promise.resolve())}cronStart(e,t){return this.cronManager?this.cronManager.start(e,t):(this.log("Cron monitoring not enabled. Set crons.enabled: true in init()"),{ok:()=>Promise.resolve(),error:()=>Promise.resolve()})}cronWrap(e,t,n){return this.cronManager?this.cronManager.wrap(e,t,n):t()}metricIncrement(e,t,n){if(!this.metricsManager){this.log("Metrics not enabled. Set metrics.enabled: true in init()");return}this.metricsManager.increment(e,t,n);}metricGauge(e,t,n){this.metricsManager&&this.metricsManager.gauge(e,t,n);}metricHistogram(e,t,n){this.metricsManager&&this.metricsManager.histogram(e,t,n);}metricDistribution(e,t,n){this.metricsManager&&this.metricsManager.distribution(e,t,n);}async metricTime(e,t,n){return this.metricsManager?this.metricsManager.time(e,t,n):t()}metricStartTimer(e,t){return this.metricsManager?this.metricsManager.startTimer(e,t):{stop:()=>{}}}async flushMetrics(){if(this.metricsManager)return this.metricsManager.flush()}async dbTrack(e,t,n){return this.databaseTracker?this.databaseTracker.track(e,t,n):t()}dbTrackSync(e,t,n){return this.databaseTracker?this.databaseTracker.trackSync(e,t,n):t()}getDbQueryCount(){return this.databaseTracker?this.databaseTracker.getQueryCount():0}resetDbQueryCount(){this.databaseTracker&&this.databaseTracker.resetQueryCount();}getDbNPlusOnePatterns(){return this.databaseTracker?this.databaseTracker.getNPlusOnePatterns():[]}async profile(e,t,n){return this.profiler?this.profiler.profile(e,t,n):t()}startProfileSpan(e,t){return this.profiler?this.profiler.startSpan(e,t):()=>{}}getProfiles(){return this.profiler?this.profiler.getProfiles():[]}getLatestProfile(){return this.profiler?this.profiler.getLatestProfile():null}async flushProfiles(){if(this.profiler)return this.profiler.flush()}getRemoteConfig(){return this.remoteConfigManager?.getConfig()??null}isRemoteConfigFeatureEnabled(e,t=true){return this.remoteConfigManager?.isFeatureEnabled(e,t)??t}onRemoteConfigChange(e){return this.remoteConfigManager?this.remoteConfigManager.onChange(e):()=>{}}setContext(e){this.context={...this.context,...e};}setUser(e){this.context.user=e,this.replayManager&&this.replayManager.setUser(e?{id:e.id}:null);}setTags(e){this.context.tags={...this.context.tags,...e};}clearUser(){this.context.user=void 0,this.replayManager&&this.replayManager.setUser(null);}addBreadcrumb(e){this.log("Breadcrumb added:",e);}captureError(e,t){if(!this.initialized){console.warn("[SitePong] SDK not initialized. Call init() first.");return}let n=this.formatError(e,t);this.errorQueue.push(n),this.log("Captured error:",n.message),this.replayManager?.isRecording()&&this.replayManager.flushOnError().catch(i=>{this.log("Failed to flush replay on error:",i);}),this.errorQueue.length>=this.config.maxBatchSize&&this.flush();}captureMessage(e,t="info",n){if(!this.initialized){console.warn("[SitePong] SDK not initialized. Call init() first.");return}let i={message:e,type:t,timestamp:new Date().toISOString(),url:this.getUrl(),userAgent:this.getUserAgent(),environment:this.config.environment,release:this.config.release,context:{...this.context,...n},replaySessionId:this.replayManager?.isRecording()&&this.replayManager.getSessionId()||void 0};this.errorQueue.push(i),this.log("Captured message:",e),this.errorQueue.length>=this.config.maxBatchSize&&this.flush();}async flush(){if(this.errorQueue.length===0)return;if(this.disabled){this.errorQueue=[];return}let e=[...this.errorQueue];this.errorQueue=[];try{let t=await fetch(`${this.config.endpoint}/api/errors/batch`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey},body:JSON.stringify({errors:e})});if(!t.ok)throw new Error(`HTTP ${t.status}`);this.flushFailures=0,this.log(`Flushed ${e.length} errors`);}catch(t){if(this.flushFailures++,this.flushFailures>=we){this.disabled=true,console.warn(`[SitePong] SDK disabled after ${we} consecutive failures. Events will no longer be sent. This may be due to CORS issues or network problems. Check that ${this.config.endpoint} is accessible and has proper CORS headers.`);return}this.errorQueue.unshift(...e),this.log(`Failed to flush errors (attempt ${this.flushFailures}/${we}):`,t);}}formatError(e,t){let n=e instanceof Error,i=n?e.message:String(e),o=n?e.stack:new Error(i).stack,s=n?e.name:"Error";return {message:i,stack:o,type:s,timestamp:new Date().toISOString(),url:this.getUrl(),userAgent:this.getUserAgent(),environment:this.config.environment,release:this.config.release,context:{...this.context,...t},fingerprint:this.generateFingerprint(i,o,s),replaySessionId:this.replayManager?.isRecording()&&this.replayManager.getSessionId()||void 0}}generateFingerprint(e,t,n){let i=n||"Error",o=this.normalizeMessage(e),s=t?this.extractTopFrame(t):"",l=[i,o,s].join(`
|
|
6
|
+
`),c=2166136261;for(let d=0;d<l.length;d++)c^=l.charCodeAt(d),c=Math.imul(c,16777619);return (c>>>0).toString(16).padStart(8,"0")}normalizeMessage(e){return e.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"<uuid>").replace(/\b0x[0-9a-f]{4,}\b/gi,"<hex>").replace(/\b[0-9a-f]{8,}\b/gi,"<hex>").replace(/https?:\/\/[^\s)"']+/g,"<url>").replace(/\b\d+(\.\d+)?\b/g,"<n>").replace(/\s+/g," ").trim()}extractTopFrame(e){let t=e.split(`
|
|
7
|
+
`);for(let n=1;n<t.length;n++){let i=t[n].trim();if(i&&(i.startsWith("at ")||/^\w+@/.test(i)))return i.replace(/:\d+\)?\s*$/,")")}return ""}setupAutoCapture(){typeof window<"u"&&typeof window.addEventListener=="function"?(window.addEventListener("error",e=>{this.captureError(e.error||e.message);}),window.addEventListener("unhandledrejection",e=>{let t=e.reason instanceof Error?e.reason:new Error(String(e.reason));this.captureError(t);}),this.log("Auto-capture enabled for browser")):typeof process<"u"&&typeof process.on=="function"&&(process.on("uncaughtException",e=>{this.captureError(e),this.flush().finally(()=>process.exit(1));}),process.on("unhandledRejection",e=>{let t=e instanceof Error?e:new Error(String(e));this.captureError(t);}),this.log("Auto-capture enabled for Node.js"));}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval),typeof window<"u"&&typeof window.addEventListener=="function"&&(window.addEventListener("beforeunload",()=>{this.flush();}),window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushWithBeacon();}));}flushWithBeacon(){if(this.errorQueue.length===0||typeof navigator?.sendBeacon!="function")return;let e=[...this.errorQueue];this.errorQueue=[];let t=new Blob([JSON.stringify({errors:e,apiKey:this.config.apiKey})],{type:"application/json"});navigator.sendBeacon(`${this.config.endpoint}/api/errors/batch`,t),this.log(`Flushed ${e.length} errors via beacon`);}getUrl(){if(typeof window<"u")return window.location.href}getUserAgent(){if(typeof navigator<"u")return navigator.userAgent}log(...e){this.config.debug&&console.log("[SitePong]",...e);}},a=new Se,Br=a.init.bind(a),Vr=a.initRN.bind(a),Ur=a.captureError.bind(a),$r=a.captureMessage.bind(a),zr=a.setContext.bind(a),Kr=a.setUser.bind(a),qr=a.setTags.bind(a),Wr=a.flush.bind(a),Xr=a.isInitialized.bind(a),Gr=a.clearUser.bind(a),jr=a.addBreadcrumb.bind(a);var Qr=a.getFlag.bind(a),Yr=a.getAllFlags.bind(a),Jr=a.getVariant.bind(a),Zr=a.getVariantPayload.bind(a),ei=a.waitForFlags.bind(a),ti=a.areFlagsReady.bind(a),ni=a.refreshFlags.bind(a),ri=a.track.bind(a),ii=a.trackPageView.bind(a),oi=a.identify.bind(a),si=a.group.bind(a),ai=a.resetAnalytics.bind(a),li=a.getVisitorId.bind(a),ci=a.getDeviceSignals.bind(a),ui=a.getFraudCheck.bind(a),di=a.startReplay.bind(a),fi=a.stopReplay.bind(a),pi=a.isReplayRecording.bind(a),hi=a.getReplaySessionId.bind(a),gi=a.startTransaction.bind(a),mi=a.endTransaction.bind(a),vi=a.startSpan.bind(a),yi=a.endSpan.bind(a),bi=a.getWebVitals.bind(a),wi=a.dbTrack.bind(a),Si=a.dbTrackSync.bind(a),Ti=a.getDbQueryCount.bind(a),xi=a.resetDbQueryCount.bind(a),ki=a.getDbNPlusOnePatterns.bind(a),Ci=a.cronCheckin.bind(a),Ei=a.cronStart.bind(a),Mi=a.cronWrap.bind(a),Ri=a.metricIncrement.bind(a),Pi=a.metricGauge.bind(a),Ii=a.metricHistogram.bind(a),Di=a.metricDistribution.bind(a),Fi=a.metricTime.bind(a),Ai=a.metricStartTimer.bind(a),_i=a.flushMetrics.bind(a),Li=a.profile.bind(a),Oi=a.startProfileSpan.bind(a),Ni=a.getProfiles.bind(a),Hi=a.getLatestProfile.bind(a),Bi=a.flushProfiles.bind(a),Vi=a.getRemoteConfig.bind(a),Ui=a.isRemoteConfigFeatureEnabled.bind(a),$i=a.onRemoteConfigChange.bind(a),zi=a;exports.TracePropagator=te;exports.addBreadcrumb=jr;exports.areFlagsReady=ti;exports.captureError=Ur;exports.captureMessage=$r;exports.clearAnonymousId=xe;exports.clearUser=Gr;exports.client=a;exports.createTraceContext=ye;exports.cronCheckin=Ci;exports.cronStart=Ei;exports.cronWrap=Mi;exports.dbTrack=wi;exports.dbTrackSync=Si;exports.default=zi;exports.endSpan=yi;exports.endTransaction=mi;exports.extractTrace=Ye;exports.flush=Wr;exports.flushMetrics=_i;exports.flushProfiles=Bi;exports.generateSpanId=ne;exports.generateTraceId=ve;exports.getAllFlags=Yr;exports.getAnonymousId=k;exports.getDbNPlusOnePatterns=ki;exports.getDbQueryCount=Ti;exports.getDeviceSignals=ci;exports.getFlag=Qr;exports.getFraudCheck=ui;exports.getLatestProfile=Hi;exports.getProfiles=Ni;exports.getRemoteConfig=Vi;exports.getReplaySessionId=hi;exports.getVariant=Jr;exports.getVariantPayload=Zr;exports.getVisitorId=li;exports.getWebVitals=bi;exports.group=si;exports.identify=oi;exports.init=Br;exports.initRN=Vr;exports.isInitialized=Xr;exports.isRemoteConfigFeatureEnabled=Ui;exports.isReplayRecording=pi;exports.metricDistribution=Di;exports.metricGauge=Pi;exports.metricHistogram=Ii;exports.metricIncrement=Ri;exports.metricStartTimer=Ai;exports.metricTime=Fi;exports.onRemoteConfigChange=$i;exports.profile=Li;exports.propagateTrace=ee;exports.refreshFlags=ni;exports.resetAnalytics=ai;exports.resetDbQueryCount=xi;exports.setAnonymousId=ke;exports.setContext=zr;exports.setTags=qr;exports.setUser=Kr;exports.startProfileSpan=Oi;exports.startReplay=di;exports.startSpan=vi;exports.startTransaction=gi;exports.stopReplay=fi;exports.track=ri;exports.trackPageView=ii;exports.waitForFlags=ei;Object.defineProperty(exports,'__esModule',{value:true});return exports;})({});//# sourceMappingURL=sitepong.min.js.map
|
|
8
8
|
//# sourceMappingURL=sitepong.min.js.map
|