sitepong 0.2.13 → 0.2.15
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/entries/rn.d.ts +28 -1
- package/dist/entries/rn.js +44 -5
- package/dist/entries/rn.js.map +1 -1
- package/dist/entries/web.js +30 -2
- package/dist/entries/web.js.map +1 -1
- package/dist/entries/web.mjs +30 -2
- package/dist/entries/web.mjs.map +1 -1
- package/dist/index.d.mts +25 -2
- package/dist/index.d.ts +25 -2
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +5 -1
- package/dist/index.mjs.map +1 -1
- package/dist/react/index.js +5 -1
- package/dist/react/index.js.map +1 -1
- package/dist/react/index.mjs +5 -1
- package/dist/react/index.mjs.map +1 -1
- package/ios/ScreenRecorder/ScreenRecorderModule.swift +9 -3
- package/ios/WatchtowerCore/StructuralRecorder.swift +163 -19
- package/ios/WatchtowerCore/TapEvent.swift +5 -0
- package/ios/WatchtowerCore/Watchtower.swift +48 -3
- package/ios/WatchtowerCore/WatchtowerEngine.swift +26 -1
- package/package.json +1 -1
package/dist/cdn/sitepong.min.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var SitePong=(function(exports){'use strict';function Kn(){try{return typeof localStorage>"u"?null:{getItem:async r=>localStorage.getItem(r),setItem:async(r,e)=>{localStorage.setItem(r,e);},removeItem:async r=>{localStorage.removeItem(r);}}}catch{return null}}function St(){return {platform:"browser",storage:Kn(),getDeviceInfo(){let e={platform:"browser"};return typeof navigator<"u"&&(e.userAgent=navigator.userAgent),typeof window<"u"&&window.screen&&(e.screenWidth=window.screen.width,e.screenHeight=window.screen.height),e},getCurrentUrl(){if(!(typeof window>"u"||!window.location))return window.location.href},getReferrer(){if(!(typeof document>"u"))return document.referrer||void 0},getUserAgent(){if(!(typeof navigator>"u"))return navigator.userAgent},onUncaughtError(e){if(typeof window>"u"||!window.addEventListener)return ()=>{};let t=n=>{e(n.error||n.message);};return window.addEventListener("error",t),()=>window.removeEventListener("error",t)},onUnhandledRejection(e){if(typeof window>"u"||!window.addEventListener)return ()=>{};let t=n=>{e(n.reason);};return window.addEventListener("unhandledrejection",t),()=>window.removeEventListener("unhandledrejection",t)},onBeforeTerminate(e){return typeof window>"u"||!window.addEventListener?()=>{}:(window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e))},onVisibilityHidden(e){if(typeof document>"u"||!document.addEventListener)return ()=>{};let t=()=>{document.visibilityState==="hidden"&&e();};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)},sendBeacon(e,t){if(typeof navigator>"u"||typeof navigator.sendBeacon!="function")return false;try{let n=new Blob([t],{type:"application/json"});return navigator.sendBeacon(e,n)}catch{return false}}}}var R=null;function z(r){R=r;}function S(){return R}function Pe(){if(R)return R.platform;let r=globalThis;return r.navigator&&r.navigator.product==="ReactNative"?"react-native":r.process&&r.process.versions&&r.process.versions.node?"node":r.window&&r.document?"browser":"unknown"}function _(){return Pe()==="react-native"}var Wn=null;function qn(){return R&&R.platform==="react-native"?R:null}function Le(r){let e=qn();e&&e._setGetCurrentScreen(r);}function ce(){return Wn}function _e(){return R?R.storage:null}var le="sitepong_anonymous_id";function De(){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 I=null;function D(){if(typeof window<"u"&&typeof localStorage<"u")try{let r=localStorage.getItem(le);return r||(r=De(),localStorage.setItem(le,r)),r}catch{return I||(I=De()),I}return I||(I=De()),I}function Tt(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(le);}catch{}I=null;}function kt(r){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.setItem(le,r);}catch{I=r;}else I=r;}function xt(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 Ct(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 Fe(){let r=S()?.getUserAgent()??"";return {anonymous_id:D(),device_type:r?xt(r):void 0,browser:r?Et(r):void 0,os:r?Ct(r):void 0,user_agent:r||void 0,timestamp:new Date}}function Mt(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e^r.charCodeAt(t);return e>>>0}function jn(r){return Math.random()*100<r.percentage}function Gn(r,e,t){let n=`${e.anonymous_id}:${t}`;return Mt(n)%100<r.percentage}function ue(r){let[e,t]=r.split(":").map(Number);return e*60+t}function Xn(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(u=>u.type==="weekday")?.value||""),s=parseInt(i.find(u=>u.type==="hour")?.value||"0",10),a=parseInt(i.find(u=>u.type==="minute")?.value||"0",10),c=s*60+a;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 u=ue(r.start_time),p=ue(r.end_time);if(u>p){if(c<u&&c>=p)return false}else if(c<u||c>=p)return false}else if(r.start_time){let u=ue(r.start_time);if(c<u)return false}else if(r.end_time){let u=ue(r.end_time);if(c>=u)return false}return true}function Qn(r,e){return e.device_type?r.types.includes(e.device_type):false}function Yn(r,e){return e.browser?r.browsers.includes(e.browser):false}function Jn(r,e){return e.os?r.operating_systems.includes(e.os):false}function Zn(r,e,t,n){switch(r){case "percentage_rollout":return jn(e);case "userbase_percentage":return Gn(e,t,n);case "time_based":return Xn(e,t);case "device_type":return Qn(e,t);case "browser":return Yn(e,t);case "os":return Jn(e,t);default:return false}}function de(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(!Zn(t.rule_type,t.config,e,r.key))return false;return true}function Rt(r,e){if(!de(r,e)||r.flag_type!=="multivariate"||!r.variants||r.variants.length===0)return null;let t=`${e.anonymous_id}:${r.key}:variant`,n=Mt(t),i=r.variants.reduce((a,c)=>a+c.weight,0),o=n%i,s=0;for(let a of r.variants)if(s+=a.weight,o<s)return a.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 er="https://api.sitepong.com",F=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:er,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=Fe(),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=de(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 Ae="sitepong_session_id",pe="sitepong_session_ts";var V=null,K=null;function Lt(){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 _t(r){return Date.now()-r>18e5}function Ne(){if(typeof window<"u"&&typeof sessionStorage<"u")try{let r=sessionStorage.getItem(Ae),e=sessionStorage.getItem(pe);if(r&&e&&!_t(parseInt(e,10)))return sessionStorage.setItem(pe,String(Date.now())),r;let t=Lt();return sessionStorage.setItem(Ae,t),sessionStorage.setItem(pe,String(Date.now())),t}catch{return Pt()}return Pt()}function Pt(){return V&&K&&!_t(K)?(K=Date.now(),V):(V=Lt(),K=Date.now(),V)}function Oe(){if(typeof window<"u"&&typeof sessionStorage<"u")try{sessionStorage.removeItem(Ae),sessionStorage.removeItem(pe);}catch{}V=null,K=null;}var Dt="sp_utm",tr=[["source","utm_source"],["medium","utm_medium"],["campaign","utm_campaign"],["term","utm_term"],["content","utm_content"]];function nr(){if(typeof window>"u"||!window.location||!window.location.search)return null;let r;try{r=new URLSearchParams(window.location.search);}catch{return null}let e={},t=false;for(let[n,i]of tr){let o=r.get(i);o&&(e[n]=o,t=true);}return t?e:null}function rr(){if(typeof sessionStorage>"u")return null;try{let r=sessionStorage.getItem(Dt);if(!r)return null;let e=JSON.parse(r);return e&&typeof e=="object"?e:null}catch{return null}}function ir(r){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(Dt,JSON.stringify(r));}catch{}}function Ft(){let r=rr();if(r)return r;let e=nr();return e&&ir(e),e}var At=["[data-sp-no-capture]",".sp-no-capture"];var P=class{constructor(e,t){this.listeners=[];this.clickHandler=null;this.submitHandler=null;this.active=false;this.config={clicks:true,forms:true,pageviews:true,blockSelectors:At,maxTextLength:255,debug:false,...e},this.callback=t;}addListener(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1);}}emit(e){this.callback(e);for(let t of this.listeners)try{t(e);}catch{}}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.emit({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.emit({type:"form_submit",timestamp:new Date().toISOString(),properties:n});},document.addEventListener("submit",this.submitHandler,true);}shouldCapture(e){let t=this.config.blockSelectors||At;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),typeof window<"u"&&window.location&&(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 a=Array.from(s.children).filter(c=>c.tagName===n.tagName);if(a.length>1){let c=a.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);}};var or="https://ingest.sitepong.com",sr=20,ar=1e4,He=3,A=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:or,enabled:true,autocapturePageviews:false,maxBatchSize:sr,flushInterval:ar,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,a;e===true?(i=true,o=true):e&&typeof e=="object"&&(i=e.clicks!==false,o=e.forms!==false,s=e.blockSelectors,a=e.allowSelectors,e.pageviews!==false&&!this.config.autocapturePageviews&&this.setupSPATracking()),!(!i&&!o)&&(this.autocaptureModule=new P({clicks:i,forms:o,pageviews:false,blockSelectors:s,allowSelectors:a,debug:this.config.debug},c=>{let u=c.type==="click"?"$autocapture_click":c.type==="form_submit"?"$autocapture_form_submit":"$autocapture";this.track(u,c.properties);}),this.autocaptureModule.start());}getAutocaptureModule(){return this.autocaptureModule}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?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,Oe(),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>=He){this.disabled=true,console.warn(`[SitePong Analytics] Disabled after ${He} 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}/${He}):`,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:D(),deviceId:void 0,groupId:this.groupId||void 0,traits:t.traits,sessionId:Ne(),timestamp:new Date().toISOString(),url:typeof window<"u"&&window.location?window.location.href:void 0,referrer:typeof document<"u"&&typeof document.referrer=="string"?document.referrer:void 0,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,utm:Ft()||void 0,appVersion:this.config.appVersion||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"||_()||typeof window.addEventListener!="function"||window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushWithBeacon();});}flushWithBeacon(){if(this.eventQueue.length===0||_()||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"||_()||!window.location||typeof window.addEventListener!="function")return;this.lastUrl=window.location.href,this.trackPageView(),this.popstateHandler=()=>{if(!window.location)return;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"||!window.location)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 W=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 q=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);let e=S();e&&e.onVisibilityHidden(()=>this.flushWithBeacon());}flushWithBeacon(){if(this.queue.length===0)return;let e=S();if(!e||!e.sendBeacon)return;let t=[...this.queue];this.queue=[];let n=JSON.stringify({metrics:t,apiKey:this.apiKey});e.sendBeacon(`${this.endpoint}/api/sdk/metrics`,n)?this.log(`Flushed ${t.length} metrics via beacon`):this.queue.unshift(...t);}log(...e){this.debug&&console.log("[SitePong:Metrics]",...e);}};var j=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,a)=>s[1].since-a[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 G=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 a=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=[],a}catch(a){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=[],a}}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(Nt(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 Nt(r){let e=r.length;for(let t of r)e+=Nt(t.children);return e}var Ue={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 Ot="sitepong_remote_config",Ht="sitepong_remote_config_ts",N=class{constructor(e){this.listeners=[];this.refreshTimer=null;this.initialized=false;this.options=e,this.config={...Ue};}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(Ot),n=await e.getItem(Ht);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=Pe(),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(Ot,JSON.stringify(this.config)),await e.setItem(Ht,String(Date.now()));}catch{this.log("Failed to cache remote config");}}scheduleRefresh(){this.refreshTimer&&clearTimeout(this.refreshTimer);let t=(typeof this.config.ttl=="number"&&this.config.ttl>0?this.config.ttl:300)*1e3;this.refreshTimer=setTimeout(()=>{this.fetchAndApply().catch(n=>{this.log("Refresh failed:",n);});},t);}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,a=i[o]||0;if(s>a)return 1;if(s<a)return -1}return 0}log(...e){this.options.debug&&console.log("[SitePong RemoteConfig]",...e);}};function Ut(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 Ut(16)}function ge(){return Ut(8)}function $e(){return {traceId:Be(),spanId:ge(),parentSpanId:null,sampled:true}}function fe(r){let e=r.sampled?"01":"00";return {traceparent:`00-${r.traceId}-${r.spanId}-${e}`,tracestate:`sitepong=${r.spanId}`}}function Bt(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 a=(parseInt(s,16)&1)===1;return {traceId:i,spanId:ge(),parentSpanId:o,sampled:a}}var he=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=fe(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=fe(o),a={};if(n?.headers)if(n.headers instanceof Headers)n.headers.forEach((p,h)=>{a[h]=p;});else if(Array.isArray(n.headers))for(let[p,h]of n.headers)a[p]=h;else Object.assign(a,n.headers);let c={...a,...s},u={...n,headers:c};return e.originalFetch.call(window,t,u)}return e.originalFetch.call(window,t,n)};}stop(){typeof window>"u"||this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null);}};var ze="https://pongl.ink",X=class{constructor(e={}){this.config={endpoint:$t(e.endpoint||ze),appId:e.appId,installId:e.installId,debug:e.debug??false};}configure(e){e.endpoint&&(this.config.endpoint=$t(e.endpoint)),e.appId!==void 0&&(this.config.appId=e.appId),e.installId!==void 0&&(this.config.installId=e.installId),e.debug!==void 0&&(this.config.debug=e.debug);}log(...e){this.config.debug&&console.warn("[SuperLink]",...e);}async match(e){let t={...e,install_id:e.install_id??this.config.installId};try{let n=await fetch(`${this.config.endpoint}/match`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return n.ok?await n.json()??{matched:!1}:(this.log("match failed",n.status),{matched:!1})}catch(n){return this.log("match error",n),{matched:false}}}async reportEvent(e){try{let t=await fetch(`${this.config.endpoint}/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:this.config.appId,install_id:this.config.installId,...e})});return t.ok||this.log("event failed",e.type,t.status),t.ok}catch(t){return this.log("event error",t),false}}};function $t(r){return r.endsWith("/")?r.slice(0,-1):r}var T=new X;var cr=[["source","utm_source"],["medium","utm_medium"],["campaign","utm_campaign"],["term","utm_term"],["content","utm_content"]];function me(r){let e;try{e=new URL(r);}catch{return null}let t=e.searchParams,n={};for(let[c,u]of cr){let p=t.get(u);p&&(n[c]=p);}let i={},o={};return t.forEach((c,u)=>{u.startsWith("r_")?i[u.slice(2)]=c:u.startsWith("~")&&(o[u.slice(1)]=c);}),{deep_link_path:t.get("$deep_link_path")??t.get("dlp")??(e.pathname&&e.pathname!=="/"?e.pathname:null),deep_link_data:o,utm:n,referral:i,click_id:t.get("click_id"),match_type:"none",confidence:1}}var Ve=new Set,ve=null;function Ke(r){return {deep_link_path:r.deep_link_path??null,deep_link_data:r.deep_link_data??{},utm:r.utm??{},referral:r.referral??{},click_id:r.click_id??null,match_type:r.match_type??"fingerprint",confidence:r.confidence??(r.match_type&&r.match_type!=="none"?1:0)}}function We(r){ve=r;for(let e of Ve)try{e(r);}catch(t){T.config.debug&&console.warn("[SuperLink] handler threw",t);}}function zt(r){if(Ve.add(r),ve)try{r(ve);}catch{}return ()=>{Ve.delete(r);}}function Vt(){return ve}var Kt="sp_superlink",O=null,qe=false;function lr(){if(typeof sessionStorage>"u")return null;try{let r=sessionStorage.getItem(Kt);if(!r)return null;let e=JSON.parse(r);return e&&typeof e=="object"?e:null}catch{return null}}function ur(r){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(Kt,JSON.stringify(r));}catch{}}function dr(r){return !!(r.deep_link_path||r.click_id||Object.keys(r.deep_link_data).length>0||Object.keys(r.referral).length>0||Object.keys(r.utm).length>0)}function Wt(r){if(typeof navigator>"u"||!navigator.clipboard)return;let e=`${T.config.endpoint}/c/${r}`;navigator.clipboard.writeText(e).catch(()=>{});}function qt(r){let e=r??(typeof window<"u"&&window.location?window.location.href:null);if(!e)return;let t;try{t=new URL(e);}catch{return}let n=t.searchParams.get("email"),i=t.searchParams.get("phone"),o=t.searchParams.get("user_id"),s=t.searchParams.get("id"),a=t.searchParams.get("custom"),c={};if(n&&(c.email=n),i&&(c.phone=i),o&&(c.user_id=o),s&&(c.id=s),a)try{let u=JSON.parse(decodeURIComponent(a));typeof u=="object"&&u!==null&&(c.custom=u);}catch{}return Object.keys(c).length>0?c:void 0}function Q(){if(qe)return O;qe=true;let r=lr();if(r)return O=r,O;if(typeof window>"u"||!window.location)return null;let e=me(window.location.href);return e&&dr(e)&&(O=e,ur(e),T.reportEvent({type:"opened",click_id:e.click_id,platform:"desktop",properties:{surface:"web"}})),O}function jt(){return qe?O:Q()}function Gt(){let r={platform:"desktop"};if(typeof navigator<"u"){navigator.userAgent&&(r.user_agent=navigator.userAgent);let e=navigator.language||navigator.languages&&navigator.languages[0];e&&(r.language=e);}return r}async function Xt(r){if(!r||Object.keys(r).length===0)return null;let e=await T.match({identity:r,fingerprint:Gt()});if(!e.matched)return null;let t=Ke(e);return We(t),t}async function Qt(r){if(!r)return null;let e=await T.match({qr_token:r,fingerprint:Gt()});if(!e.matched)return null;let t=Ke(e);return We(t),t}function pr(r={}){T.configure(r),Q();}function fr(){if(S())return;let r=globalThis,e=typeof r.window<"u"&&typeof r.document<"u",t=!e&&!!r.process?.versions?.node,n=e?"browser":"node";z({platform:n,storage:null,getDeviceInfo(){let o={platform:n};return r.navigator?.userAgent&&(o.userAgent=r.navigator.userAgent),e&&r.window?.screen&&(o.screenWidth=r.window.screen.width,o.screenHeight=r.window.screen.height),t&&r.process&&(o.osName=r.process.platform,o.osVersion=r.process.versions?.node),o},getCurrentUrl(){return r.window?.location?.href??void 0},getReferrer(){return r.document?.referrer||void 0},getUserAgent(){if(r.navigator?.userAgent)return r.navigator.userAgent;if(t&&r.process)return `SitePong-Node/${r.process.versions?.node} (${r.process.platform})`},onUncaughtError(o){if(e&&r.window?.addEventListener){let s=a=>o(a.error||a.message);return r.window.addEventListener("error",s),()=>r.window?.removeEventListener?.("error",s)}if(t&&r.process?.on&&r.process.off){let s=a=>o(a);return r.process.on("uncaughtException",s),()=>r.process?.off?.("uncaughtException",s)}return ()=>{}},onUnhandledRejection(o){if(e&&r.window?.addEventListener){let s=a=>o(a.reason);return r.window.addEventListener("unhandledrejection",s),()=>r.window?.removeEventListener?.("unhandledrejection",s)}if(t&&r.process?.on&&r.process.off){let s=a=>o(a);return r.process.on("unhandledRejection",s),()=>r.process?.off?.("unhandledRejection",s)}return ()=>{}},onBeforeTerminate(o){return e&&r.window?.addEventListener?(r.window.addEventListener("beforeunload",o),()=>r.window?.removeEventListener?.("beforeunload",o)):t&&r.process?.on&&r.process.off?(r.process.on("beforeExit",o),r.process.on("SIGINT",o),r.process.on("SIGTERM",o),()=>{r.process?.off?.("beforeExit",o),r.process?.off?.("SIGINT",o),r.process?.off?.("SIGTERM",o);}):()=>{}},onVisibilityHidden(o){if(r.document?.addEventListener){let s=()=>{r.document?.visibilityState==="hidden"&&o();};return r.document.addEventListener("visibilitychange",s),()=>r.document?.removeEventListener?.("visibilitychange",s)}return ()=>{}},sendBeacon(o,s){if(typeof r.navigator?.sendBeacon!="function")return false;try{return r.navigator.sendBeacon(o,new Blob([s],{type:"application/json"}))}catch{return false}}});}fr();var k={};function Yt(r){k={...k,...r};}var v="https://ingest.sitepong.com",hr=10,gr=5e3,je=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.watchtowerCapture=null;this.watchtowerOptions=void 0;this.envUnsubs=[];this.identifyHooks=[];this.config={apiKey:"",endpoint:v,environment:"production",release:"",autoCapture:true,maxBatchSize:hr,flushInterval:gr,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 F({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 A({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&&k.createFingerprint?this.fingerprintManager=k.createFingerprint({apiKey:e.apiKey,endpoint:e.endpoint||v,enabled:true,extendedSignals:e.fingerprint.extendedSignals,visitorEndpoint:e.fingerprint.visitorEndpoint,debug:e.debug}):e.fingerprint?.enabled&&this.log("Fingerprint requested but not available on this platform (web only)."),e.performance?.enabled&&k.createPerformance?(this.performanceManager&&this.performanceManager.destroy(),this.performanceManager=k.createPerformance({apiKey:e.apiKey,endpoint:e.endpoint||v,enabled:true,webVitals:e.performance.webVitals,navigationTiming:e.performance.navigationTiming,resourceTiming:e.performance.resourceTiming,capturePageLoadTimings:e.performance.capturePageLoadTimings,capturePageRenderTimings:e.performance.capturePageRenderTimings,excludedResourceUrls:e.performance.excludedResourceUrls,resourceNameSanitizer:e.performance.resourceNameSanitizer,sampleRate:e.performance.sampleRate,flushInterval:e.performance.flushInterval,performanceEndpoint:e.performance.performanceEndpoint,debug:e.debug}),this.performanceManager.init()):e.performance?.enabled&&this.log("Performance requested but not available on this platform (web only)."),e.replay?.enabled&&k.createReplay?(this.replayManager&&this.replayManager.stop(),this.replayManager=k.createReplay({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.replay?.enabled&&this.log("Replay requested but not available on this platform (web only)."),this.watchtowerOptions=e.watchtower,e.watchtower?.enabled&&k.createWatchtowerCapture?this.startWatchtowerCapture():e.watchtower?.enabled&&this.log("Watchtower capture requested but not available on this platform (web only)."),e.crons?.enabled&&(this.cronManager=new W({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug})),e.database?.enabled&&(this.databaseTracker=new j({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,slowQueryThreshold:e.database.slowQueryThreshold,redactParams:e.database.redactParams})),e.metrics?.enabled&&(this.metricsManager=new q({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,flushInterval:e.metrics.flushInterval,maxBatchSize:e.metrics.maxBatchSize})),e.profiling?.enabled&&(this.profiler=new G({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||_e();this.remoteConfigManager=new N({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 F({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 A({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 W({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug})),e.metrics?.enabled&&(this.metricsManager=new q({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,flushInterval:e.metrics.flushInterval,maxBatchSize:e.metrics.maxBatchSize})),e.database?.enabled&&(this.databaseTracker=new j({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,slowQueryThreshold:e.database.slowQueryThreshold,redactParams:e.database.redactParams})),e.profiling?.enabled&&(this.profiler=new G({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||_e();this.remoteConfigManager=new N({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});for(let n of this.identifyHooks)try{n(e);}catch(i){this.log("identify hook failed:",i);}if(this.watchtowerCapture?.setDistinctId(e),!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.identify(e,t);}registerIdentifyHook(e){return this.identifyHooks.push(e),()=>{let t=this.identifyHooks.indexOf(e);t>=0&&this.identifyHooks.splice(t,1);}}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}startWatchtowerCapture(e){if(!k.createWatchtowerCapture)return this.log("Watchtower capture not available on this platform (web only)."),false;if(!this.initialized||!this.config.apiKey)return this.log("Watchtower capture requires init() to be called first."),false;let t={...this.watchtowerOptions,...e};return t.projectId?(this.watchtowerCapture&&(this.watchtowerCapture.stop(),this.watchtowerCapture=null),this.watchtowerCapture=k.createWatchtowerCapture({apiKey:this.config.apiKey,projectId:t.projectId,endpoint:t.endpoint||this.config.endpoint||v,appVersion:this.config.release||void 0,maxBatchSize:t.maxBatchSize,flushInterval:t.flushInterval,blockSelector:t.blockSelector,maskSelector:t.maskSelector,debug:this.config.debug}),this.watchtowerCapture.start(this.analyticsManager?.getAutocaptureModule()??null),true):(this.log("Watchtower capture requires watchtower.projectId."),false)}stopWatchtowerCapture(){this.watchtowerCapture&&(this.watchtowerCapture.stop(),this.watchtowerCapture=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),this.watchtowerCapture?.setDistinctId(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>=je){this.disabled=true,console.warn(`[SitePong] SDK disabled after ${je} 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}/${je}):`,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):"",a=[i,o,s].join(`
|
|
1
|
+
var SitePong=(function(exports){'use strict';function jn(){try{return typeof localStorage>"u"?null:{getItem:async r=>localStorage.getItem(r),setItem:async(r,e)=>{localStorage.setItem(r,e);},removeItem:async r=>{localStorage.removeItem(r);}}}catch{return null}}function St(){return {platform:"browser",storage:jn(),getDeviceInfo(){let e={platform:"browser"};return typeof navigator<"u"&&(e.userAgent=navigator.userAgent),typeof window<"u"&&window.screen&&(e.screenWidth=window.screen.width,e.screenHeight=window.screen.height),e},getCurrentUrl(){if(!(typeof window>"u"||!window.location))return window.location.href},getReferrer(){if(!(typeof document>"u"))return document.referrer||void 0},getUserAgent(){if(!(typeof navigator>"u"))return navigator.userAgent},onUncaughtError(e){if(typeof window>"u"||!window.addEventListener)return ()=>{};let t=n=>{e(n.error||n.message);};return window.addEventListener("error",t),()=>window.removeEventListener("error",t)},onUnhandledRejection(e){if(typeof window>"u"||!window.addEventListener)return ()=>{};let t=n=>{e(n.reason);};return window.addEventListener("unhandledrejection",t),()=>window.removeEventListener("unhandledrejection",t)},onBeforeTerminate(e){return typeof window>"u"||!window.addEventListener?()=>{}:(window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e))},onVisibilityHidden(e){if(typeof document>"u"||!document.addEventListener)return ()=>{};let t=()=>{document.visibilityState==="hidden"&&e();};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)},sendBeacon(e,t){if(typeof navigator>"u"||typeof navigator.sendBeacon!="function")return false;try{let n=new Blob([t],{type:"application/json"});return navigator.sendBeacon(e,n)}catch{return false}}}}var R=null;function z(r){R=r;}function S(){return R}function Pe(){if(R)return R.platform;let r=globalThis;return r.navigator&&r.navigator.product==="ReactNative"?"react-native":r.process&&r.process.versions&&r.process.versions.node?"node":r.window&&r.document?"browser":"unknown"}function _(){return Pe()==="react-native"}var Gn=null;function Xn(){return R&&R.platform==="react-native"?R:null}function Le(r){let e=Xn();e&&e._setGetCurrentScreen(r);}function ce(){return Gn}function _e(){return R?R.storage:null}var le="sitepong_anonymous_id";function De(){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 I=null;function D(){if(typeof window<"u"&&typeof localStorage<"u")try{let r=localStorage.getItem(le);return r||(r=De(),localStorage.setItem(le,r)),r}catch{return I||(I=De()),I}return I||(I=De()),I}function Tt(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(le);}catch{}I=null;}function kt(r){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.setItem(le,r);}catch{I=r;}else I=r;}function xt(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 Ct(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 Fe(){let r=S()?.getUserAgent()??"";return {anonymous_id:D(),device_type:r?xt(r):void 0,browser:r?Et(r):void 0,os:r?Ct(r):void 0,user_agent:r||void 0,timestamp:new Date}}function Mt(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e^r.charCodeAt(t);return e>>>0}function Qn(r){return Math.random()*100<r.percentage}function Yn(r,e,t){let n=`${e.anonymous_id}:${t}`;return Mt(n)%100<r.percentage}function ue(r){let[e,t]=r.split(":").map(Number);return e*60+t}function Jn(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(u=>u.type==="weekday")?.value||""),s=parseInt(i.find(u=>u.type==="hour")?.value||"0",10),a=parseInt(i.find(u=>u.type==="minute")?.value||"0",10),c=s*60+a;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 u=ue(r.start_time),p=ue(r.end_time);if(u>p){if(c<u&&c>=p)return false}else if(c<u||c>=p)return false}else if(r.start_time){let u=ue(r.start_time);if(c<u)return false}else if(r.end_time){let u=ue(r.end_time);if(c>=u)return false}return true}function Zn(r,e){return e.device_type?r.types.includes(e.device_type):false}function er(r,e){return e.browser?r.browsers.includes(e.browser):false}function tr(r,e){return e.os?r.operating_systems.includes(e.os):false}function nr(r,e,t,n){switch(r){case "percentage_rollout":return Qn(e);case "userbase_percentage":return Yn(e,t,n);case "time_based":return Jn(e,t);case "device_type":return Zn(e,t);case "browser":return er(e,t);case "os":return tr(e,t);default:return false}}function de(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(!nr(t.rule_type,t.config,e,r.key))return false;return true}function Rt(r,e){if(!de(r,e)||r.flag_type!=="multivariate"||!r.variants||r.variants.length===0)return null;let t=`${e.anonymous_id}:${r.key}:variant`,n=Mt(t),i=r.variants.reduce((a,c)=>a+c.weight,0),o=n%i,s=0;for(let a of r.variants)if(s+=a.weight,o<s)return a.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 rr="https://api.sitepong.com",F=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:rr,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=Fe(),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=de(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 Ae="sitepong_session_id",pe="sitepong_session_ts";var V=null,K=null;function Lt(){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 _t(r){return Date.now()-r>18e5}function Ne(){if(typeof window<"u"&&typeof sessionStorage<"u")try{let r=sessionStorage.getItem(Ae),e=sessionStorage.getItem(pe);if(r&&e&&!_t(parseInt(e,10)))return sessionStorage.setItem(pe,String(Date.now())),r;let t=Lt();return sessionStorage.setItem(Ae,t),sessionStorage.setItem(pe,String(Date.now())),t}catch{return Pt()}return Pt()}function Pt(){return V&&K&&!_t(K)?(K=Date.now(),V):(V=Lt(),K=Date.now(),V)}function Oe(){if(typeof window<"u"&&typeof sessionStorage<"u")try{sessionStorage.removeItem(Ae),sessionStorage.removeItem(pe);}catch{}V=null,K=null;}var Dt="sp_utm",ir=[["source","utm_source"],["medium","utm_medium"],["campaign","utm_campaign"],["term","utm_term"],["content","utm_content"]];function or(){if(typeof window>"u"||!window.location||!window.location.search)return null;let r;try{r=new URLSearchParams(window.location.search);}catch{return null}let e={},t=false;for(let[n,i]of ir){let o=r.get(i);o&&(e[n]=o,t=true);}return t?e:null}function sr(){if(typeof sessionStorage>"u")return null;try{let r=sessionStorage.getItem(Dt);if(!r)return null;let e=JSON.parse(r);return e&&typeof e=="object"?e:null}catch{return null}}function ar(r){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(Dt,JSON.stringify(r));}catch{}}function Ft(){let r=sr();if(r)return r;let e=or();return e&&ar(e),e}var At=["[data-sp-no-capture]",".sp-no-capture"];var P=class{constructor(e,t){this.listeners=[];this.clickHandler=null;this.submitHandler=null;this.active=false;this.config={clicks:true,forms:true,pageviews:true,blockSelectors:At,maxTextLength:255,debug:false,...e},this.callback=t;}addListener(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1);}}emit(e){this.callback(e);for(let t of this.listeners)try{t(e);}catch{}}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.emit({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.emit({type:"form_submit",timestamp:new Date().toISOString(),properties:n});},document.addEventListener("submit",this.submitHandler,true);}shouldCapture(e){let t=this.config.blockSelectors||At;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),typeof window<"u"&&window.location&&(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 a=Array.from(s.children).filter(c=>c.tagName===n.tagName);if(a.length>1){let c=a.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);}};var cr="https://ingest.sitepong.com",lr=20,ur=1e4,He=3,A=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:cr,enabled:true,autocapturePageviews:false,maxBatchSize:lr,flushInterval:ur,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,a;e===true?(i=true,o=true):e&&typeof e=="object"&&(i=e.clicks!==false,o=e.forms!==false,s=e.blockSelectors,a=e.allowSelectors,e.pageviews!==false&&!this.config.autocapturePageviews&&this.setupSPATracking()),!(!i&&!o)&&(this.autocaptureModule=new P({clicks:i,forms:o,pageviews:false,blockSelectors:s,allowSelectors:a,debug:this.config.debug},c=>{let u=c.type==="click"?"$autocapture_click":c.type==="form_submit"?"$autocapture_form_submit":"$autocapture";this.track(u,c.properties);}),this.autocaptureModule.start());}getAutocaptureModule(){return this.autocaptureModule}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?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,Oe(),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>=He){this.disabled=true,console.warn(`[SitePong Analytics] Disabled after ${He} 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}/${He}):`,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:D(),deviceId:void 0,groupId:this.groupId||void 0,traits:t.traits,sessionId:Ne(),timestamp:new Date().toISOString(),url:typeof window<"u"&&window.location?window.location.href:void 0,referrer:typeof document<"u"&&typeof document.referrer=="string"?document.referrer:void 0,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,utm:Ft()||void 0,appVersion:this.config.appVersion||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"||_()||typeof window.addEventListener!="function"||window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushWithBeacon();});}flushWithBeacon(){if(this.eventQueue.length===0||_()||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"||_()||!window.location||typeof window.addEventListener!="function")return;this.lastUrl=window.location.href,this.trackPageView(),this.popstateHandler=()=>{if(!window.location)return;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"||!window.location)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 W=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 q=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);let e=S();e&&e.onVisibilityHidden(()=>this.flushWithBeacon());}flushWithBeacon(){if(this.queue.length===0)return;let e=S();if(!e||!e.sendBeacon)return;let t=[...this.queue];this.queue=[];let n=JSON.stringify({metrics:t,apiKey:this.apiKey});e.sendBeacon(`${this.endpoint}/api/sdk/metrics`,n)?this.log(`Flushed ${t.length} metrics via beacon`):this.queue.unshift(...t);}log(...e){this.debug&&console.log("[SitePong:Metrics]",...e);}};var j=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,a)=>s[1].since-a[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 G=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 a=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=[],a}catch(a){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=[],a}}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(Nt(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 Nt(r){let e=r.length;for(let t of r)e+=Nt(t.children);return e}var Ue={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 Ot="sitepong_remote_config",Ht="sitepong_remote_config_ts",N=class{constructor(e){this.listeners=[];this.refreshTimer=null;this.initialized=false;this.options=e,this.config={...Ue};}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(Ot),n=await e.getItem(Ht);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=Pe(),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(Ot,JSON.stringify(this.config)),await e.setItem(Ht,String(Date.now()));}catch{this.log("Failed to cache remote config");}}scheduleRefresh(){this.refreshTimer&&clearTimeout(this.refreshTimer);let t=(typeof this.config.ttl=="number"&&this.config.ttl>0?this.config.ttl:300)*1e3;this.refreshTimer=setTimeout(()=>{this.fetchAndApply().catch(n=>{this.log("Refresh failed:",n);});},t);}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,a=i[o]||0;if(s>a)return 1;if(s<a)return -1}return 0}log(...e){this.options.debug&&console.log("[SitePong RemoteConfig]",...e);}};function Ut(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 Ut(16)}function ge(){return Ut(8)}function $e(){return {traceId:Be(),spanId:ge(),parentSpanId:null,sampled:true}}function fe(r){let e=r.sampled?"01":"00";return {traceparent:`00-${r.traceId}-${r.spanId}-${e}`,tracestate:`sitepong=${r.spanId}`}}function Bt(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 a=(parseInt(s,16)&1)===1;return {traceId:i,spanId:ge(),parentSpanId:o,sampled:a}}var he=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=fe(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=fe(o),a={};if(n?.headers)if(n.headers instanceof Headers)n.headers.forEach((p,h)=>{a[h]=p;});else if(Array.isArray(n.headers))for(let[p,h]of n.headers)a[p]=h;else Object.assign(a,n.headers);let c={...a,...s},u={...n,headers:c};return e.originalFetch.call(window,t,u)}return e.originalFetch.call(window,t,n)};}stop(){typeof window>"u"||this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null);}};var ze="https://pongl.ink",X=class{constructor(e={}){this.config={endpoint:$t(e.endpoint||ze),appId:e.appId,installId:e.installId,debug:e.debug??false};}configure(e){e.endpoint&&(this.config.endpoint=$t(e.endpoint)),e.appId!==void 0&&(this.config.appId=e.appId),e.installId!==void 0&&(this.config.installId=e.installId),e.debug!==void 0&&(this.config.debug=e.debug);}log(...e){this.config.debug&&console.warn("[SuperLink]",...e);}async match(e){let t={...e,install_id:e.install_id??this.config.installId};try{let n=await fetch(`${this.config.endpoint}/match`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return n.ok?await n.json()??{matched:!1}:(this.log("match failed",n.status),{matched:!1})}catch(n){return this.log("match error",n),{matched:false}}}async reportEvent(e){try{let t=await fetch(`${this.config.endpoint}/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:this.config.appId,install_id:this.config.installId,...e})});return t.ok||this.log("event failed",e.type,t.status),t.ok}catch(t){return this.log("event error",t),false}}};function $t(r){return r.endsWith("/")?r.slice(0,-1):r}var T=new X;var dr=[["source","utm_source"],["medium","utm_medium"],["campaign","utm_campaign"],["term","utm_term"],["content","utm_content"]];function me(r){let e;try{e=new URL(r);}catch{return null}let t=e.searchParams,n={};for(let[c,u]of dr){let p=t.get(u);p&&(n[c]=p);}let i={},o={};return t.forEach((c,u)=>{u.startsWith("r_")?i[u.slice(2)]=c:u.startsWith("~")&&(o[u.slice(1)]=c);}),{deep_link_path:t.get("$deep_link_path")??t.get("dlp")??(e.pathname&&e.pathname!=="/"?e.pathname:null),deep_link_data:o,utm:n,referral:i,click_id:t.get("click_id"),match_type:"none",confidence:1}}var Ve=new Set,ve=null;function Ke(r){return {deep_link_path:r.deep_link_path??null,deep_link_data:r.deep_link_data??{},utm:r.utm??{},referral:r.referral??{},click_id:r.click_id??null,match_type:r.match_type??"fingerprint",confidence:r.confidence??(r.match_type&&r.match_type!=="none"?1:0)}}function We(r){ve=r;for(let e of Ve)try{e(r);}catch(t){T.config.debug&&console.warn("[SuperLink] handler threw",t);}}function zt(r){if(Ve.add(r),ve)try{r(ve);}catch{}return ()=>{Ve.delete(r);}}function Vt(){return ve}var Kt="sp_superlink",O=null,qe=false;function pr(){if(typeof sessionStorage>"u")return null;try{let r=sessionStorage.getItem(Kt);if(!r)return null;let e=JSON.parse(r);return e&&typeof e=="object"?e:null}catch{return null}}function fr(r){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(Kt,JSON.stringify(r));}catch{}}function hr(r){return !!(r.deep_link_path||r.click_id||Object.keys(r.deep_link_data).length>0||Object.keys(r.referral).length>0||Object.keys(r.utm).length>0)}function Wt(r){if(typeof navigator>"u"||!navigator.clipboard)return;let e=`${T.config.endpoint}/c/${r}`;navigator.clipboard.writeText(e).catch(()=>{});}function qt(r){let e=r??(typeof window<"u"&&window.location?window.location.href:null);if(!e)return;let t;try{t=new URL(e);}catch{return}let n=t.searchParams.get("email"),i=t.searchParams.get("phone"),o=t.searchParams.get("user_id"),s=t.searchParams.get("id"),a=t.searchParams.get("custom"),c={};if(n&&(c.email=n),i&&(c.phone=i),o&&(c.user_id=o),s&&(c.id=s),a)try{let u=JSON.parse(decodeURIComponent(a));typeof u=="object"&&u!==null&&(c.custom=u);}catch{}return Object.keys(c).length>0?c:void 0}function Q(){if(qe)return O;qe=true;let r=pr();if(r)return O=r,O;if(typeof window>"u"||!window.location)return null;let e=me(window.location.href);return e&&hr(e)&&(O=e,fr(e),T.reportEvent({type:"opened",click_id:e.click_id,platform:"desktop",properties:{surface:"web"}})),O}function jt(){return qe?O:Q()}function Gt(){let r={platform:"desktop"};if(typeof navigator<"u"){navigator.userAgent&&(r.user_agent=navigator.userAgent);let e=navigator.language||navigator.languages&&navigator.languages[0];e&&(r.language=e);}return r}async function Xt(r){if(!r||Object.keys(r).length===0)return null;let e=await T.match({identity:r,fingerprint:Gt()});if(!e.matched)return null;let t=Ke(e);return We(t),t}async function Qt(r){if(!r)return null;let e=await T.match({qr_token:r,fingerprint:Gt()});if(!e.matched)return null;let t=Ke(e);return We(t),t}function gr(r={}){T.configure(r),Q();}function mr(){if(S())return;let r=globalThis,e=typeof r.window<"u"&&typeof r.document<"u",t=!e&&!!r.process?.versions?.node,n=e?"browser":"node";z({platform:n,storage:null,getDeviceInfo(){let o={platform:n};return r.navigator?.userAgent&&(o.userAgent=r.navigator.userAgent),e&&r.window?.screen&&(o.screenWidth=r.window.screen.width,o.screenHeight=r.window.screen.height),t&&r.process&&(o.osName=r.process.platform,o.osVersion=r.process.versions?.node),o},getCurrentUrl(){return r.window?.location?.href??void 0},getReferrer(){return r.document?.referrer||void 0},getUserAgent(){if(r.navigator?.userAgent)return r.navigator.userAgent;if(t&&r.process)return `SitePong-Node/${r.process.versions?.node} (${r.process.platform})`},onUncaughtError(o){if(e&&r.window?.addEventListener){let s=a=>o(a.error||a.message);return r.window.addEventListener("error",s),()=>r.window?.removeEventListener?.("error",s)}if(t&&r.process?.on&&r.process.off){let s=a=>o(a);return r.process.on("uncaughtException",s),()=>r.process?.off?.("uncaughtException",s)}return ()=>{}},onUnhandledRejection(o){if(e&&r.window?.addEventListener){let s=a=>o(a.reason);return r.window.addEventListener("unhandledrejection",s),()=>r.window?.removeEventListener?.("unhandledrejection",s)}if(t&&r.process?.on&&r.process.off){let s=a=>o(a);return r.process.on("unhandledRejection",s),()=>r.process?.off?.("unhandledRejection",s)}return ()=>{}},onBeforeTerminate(o){return e&&r.window?.addEventListener?(r.window.addEventListener("beforeunload",o),()=>r.window?.removeEventListener?.("beforeunload",o)):t&&r.process?.on&&r.process.off?(r.process.on("beforeExit",o),r.process.on("SIGINT",o),r.process.on("SIGTERM",o),()=>{r.process?.off?.("beforeExit",o),r.process?.off?.("SIGINT",o),r.process?.off?.("SIGTERM",o);}):()=>{}},onVisibilityHidden(o){if(r.document?.addEventListener){let s=()=>{r.document?.visibilityState==="hidden"&&o();};return r.document.addEventListener("visibilitychange",s),()=>r.document?.removeEventListener?.("visibilitychange",s)}return ()=>{}},sendBeacon(o,s){if(typeof r.navigator?.sendBeacon!="function")return false;try{return r.navigator.sendBeacon(o,new Blob([s],{type:"application/json"}))}catch{return false}}});}mr();var k={};function Yt(r){k={...k,...r};}var v="https://ingest.sitepong.com",vr=10,yr=5e3,je=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.watchtowerCapture=null;this.watchtowerOptions=void 0;this.envUnsubs=[];this.identifyHooks=[];this.config={apiKey:"",endpoint:v,environment:"production",release:"",autoCapture:true,maxBatchSize:vr,flushInterval:yr,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 F({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 A({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&&k.createFingerprint?this.fingerprintManager=k.createFingerprint({apiKey:e.apiKey,endpoint:e.endpoint||v,enabled:true,extendedSignals:e.fingerprint.extendedSignals,visitorEndpoint:e.fingerprint.visitorEndpoint,debug:e.debug}):e.fingerprint?.enabled&&this.log("Fingerprint requested but not available on this platform (web only)."),e.performance?.enabled&&k.createPerformance?(this.performanceManager&&this.performanceManager.destroy(),this.performanceManager=k.createPerformance({apiKey:e.apiKey,endpoint:e.endpoint||v,enabled:true,webVitals:e.performance.webVitals,navigationTiming:e.performance.navigationTiming,resourceTiming:e.performance.resourceTiming,capturePageLoadTimings:e.performance.capturePageLoadTimings,capturePageRenderTimings:e.performance.capturePageRenderTimings,excludedResourceUrls:e.performance.excludedResourceUrls,resourceNameSanitizer:e.performance.resourceNameSanitizer,sampleRate:e.performance.sampleRate,flushInterval:e.performance.flushInterval,performanceEndpoint:e.performance.performanceEndpoint,debug:e.debug}),this.performanceManager.init()):e.performance?.enabled&&this.log("Performance requested but not available on this platform (web only)."),e.replay?.enabled&&k.createReplay?(this.replayManager&&this.replayManager.stop(),this.replayManager=k.createReplay({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.replay?.enabled&&this.log("Replay requested but not available on this platform (web only)."),this.watchtowerOptions=e.watchtower,e.watchtower?.enabled&&k.createWatchtowerCapture?this.startWatchtowerCapture():e.watchtower?.enabled&&this.log("Watchtower capture requested but not available on this platform (web only)."),e.crons?.enabled&&(this.cronManager=new W({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug})),e.database?.enabled&&(this.databaseTracker=new j({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,slowQueryThreshold:e.database.slowQueryThreshold,redactParams:e.database.redactParams})),e.metrics?.enabled&&(this.metricsManager=new q({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,flushInterval:e.metrics.flushInterval,maxBatchSize:e.metrics.maxBatchSize})),e.profiling?.enabled&&(this.profiler=new G({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||_e();this.remoteConfigManager=new N({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 F({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 A({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 W({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug})),e.metrics?.enabled&&(this.metricsManager=new q({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,flushInterval:e.metrics.flushInterval,maxBatchSize:e.metrics.maxBatchSize})),e.database?.enabled&&(this.databaseTracker=new j({apiKey:e.apiKey,endpoint:e.endpoint||v,debug:e.debug,slowQueryThreshold:e.database.slowQueryThreshold,redactParams:e.database.redactParams})),e.profiling?.enabled&&(this.profiler=new G({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||_e();this.remoteConfigManager=new N({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});for(let n of this.identifyHooks)try{n(e,t);}catch(i){this.log("identify hook failed:",i);}if(this.watchtowerCapture?.setDistinctId(e),!this.analyticsManager){this.log("Analytics not enabled. Set analytics.enabled: true in init()");return}this.analyticsManager.identify(e,t);}registerIdentifyHook(e){return this.identifyHooks.push(e),()=>{let t=this.identifyHooks.indexOf(e);t>=0&&this.identifyHooks.splice(t,1);}}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}startWatchtowerCapture(e){if(!k.createWatchtowerCapture)return this.log("Watchtower capture not available on this platform (web only)."),false;if(!this.initialized||!this.config.apiKey)return this.log("Watchtower capture requires init() to be called first."),false;let t={...this.watchtowerOptions,...e};return t.projectId?(this.watchtowerCapture&&(this.watchtowerCapture.stop(),this.watchtowerCapture=null),this.watchtowerCapture=k.createWatchtowerCapture({apiKey:this.config.apiKey,projectId:t.projectId,endpoint:t.endpoint||this.config.endpoint||v,appVersion:this.config.release||void 0,maxBatchSize:t.maxBatchSize,flushInterval:t.flushInterval,blockSelector:t.blockSelector,maskSelector:t.maskSelector,channel:t.channel??this.config.environment,ignoreChannels:t.ignoreChannels,debug:this.config.debug}),this.watchtowerCapture.start(this.analyticsManager?.getAutocaptureModule()??null),true):(this.log("Watchtower capture requires watchtower.projectId."),false)}stopWatchtowerCapture(){this.watchtowerCapture&&(this.watchtowerCapture.stop(),this.watchtowerCapture=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),this.watchtowerCapture?.setDistinctId(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>=je){this.disabled=true,console.warn(`[SitePong] SDK disabled after ${je} 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}/${je}):`,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):"",a=[i,o,s].join(`
|
|
2
2
|
`),c=2166136261;for(let u=0;u<a.length;u++)c^=a.charCodeAt(u),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(`
|
|
3
|
-
`);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(){let e=S();e&&(this.envUnsubs.push(e.onUncaughtError(t=>{let n=t instanceof Error?t:new Error(String(t));this.captureError(n);})),this.envUnsubs.push(e.onUnhandledRejection(t=>{let n=t instanceof Error?t:new Error(String(t));this.captureError(n);})),this.log("Auto-capture enabled for",e.platform));}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval);let e=S();e&&(this.envUnsubs.push(e.onBeforeTerminate(()=>this.flush())),this.envUnsubs.push(e.onVisibilityHidden(()=>this.flushWithBeacon())));}flushWithBeacon(){if(this.errorQueue.length===0)return;let e=S();if(!e||!e.sendBeacon)return;let t=[...this.errorQueue];this.errorQueue=[];let n=JSON.stringify({errors:t,apiKey:this.config.apiKey});e.sendBeacon(`${this.config.endpoint}/api/errors/batch`,n)?this.log(`Flushed ${t.length} errors via beacon`):this.errorQueue.unshift(...t);}setCurrentScreen(e){this.currentScreen=e,Le(()=>this.currentScreen);}getUrl(){let e=S();return e?e.getCurrentUrl()??this.currentScreen??void 0:this.currentScreen??void 0}getUserAgent(){let e=S();if(e)return e.getUserAgent()}log(...e){this.config.debug&&console.log("[SitePong]",...e);}},l=new Ge,
|
|
4
|
-
`;return t}catch{return null}}function be(r){let e=r.tagName.toLowerCase(),t=location.href;if(e==="style"){let n=r;if(n.sheet){let o=Zt(n.sheet);if(o!==null)return ye(o,t)}let i=r.textContent||"";return i?ye(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=Zt(n.sheet);if(o!==null)return ye(o,i)}if(n.href){let o=
|
|
3
|
+
`);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(){let e=S();e&&(this.envUnsubs.push(e.onUncaughtError(t=>{let n=t instanceof Error?t:new Error(String(t));this.captureError(n);})),this.envUnsubs.push(e.onUnhandledRejection(t=>{let n=t instanceof Error?t:new Error(String(t));this.captureError(n);})),this.log("Auto-capture enabled for",e.platform));}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval);let e=S();e&&(this.envUnsubs.push(e.onBeforeTerminate(()=>this.flush())),this.envUnsubs.push(e.onVisibilityHidden(()=>this.flushWithBeacon())));}flushWithBeacon(){if(this.errorQueue.length===0)return;let e=S();if(!e||!e.sendBeacon)return;let t=[...this.errorQueue];this.errorQueue=[];let n=JSON.stringify({errors:t,apiKey:this.config.apiKey});e.sendBeacon(`${this.config.endpoint}/api/errors/batch`,n)?this.log(`Flushed ${t.length} errors via beacon`):this.errorQueue.unshift(...t);}setCurrentScreen(e){this.currentScreen=e,Le(()=>this.currentScreen);}getUrl(){let e=S();return e?e.getCurrentUrl()??this.currentScreen??void 0:this.currentScreen??void 0}getUserAgent(){let e=S();if(e)return e.getUserAgent()}log(...e){this.config.debug&&console.log("[SitePong]",...e);}},l=new Ge,Wo=l.init.bind(l),qo=l.initRN.bind(l),jo=l.captureError.bind(l),Go=l.captureMessage.bind(l),Xo=l.setContext.bind(l),Qo=l.setUser.bind(l),Yo=l.setTags.bind(l),Jo=l.flush.bind(l),Zo=l.isInitialized.bind(l),es=l.clearUser.bind(l),ts=l.addBreadcrumb.bind(l),ns=l.setCurrentScreen.bind(l);var rs=l.getFlag.bind(l),is=l.getAllFlags.bind(l),os=l.getVariant.bind(l),ss=l.getVariantPayload.bind(l),as=l.waitForFlags.bind(l),cs=l.areFlagsReady.bind(l),ls=l.refreshFlags.bind(l),us=l.track.bind(l),ds=l.trackPageView.bind(l),ps=l.identify.bind(l),fs=l.group.bind(l),hs=l.resetAnalytics.bind(l),gs=l.getVisitorId.bind(l),ms=l.getDeviceSignals.bind(l),vs=l.getFraudCheck.bind(l),ys=l.startReplay.bind(l),bs=l.stopReplay.bind(l),ws=l.startWatchtowerCapture.bind(l),Ss=l.stopWatchtowerCapture.bind(l),Ts=l.isReplayRecording.bind(l),ks=l.getReplaySessionId.bind(l),xs=l.startTransaction.bind(l),Es=l.endTransaction.bind(l),Cs=l.startSpan.bind(l),Ms=l.endSpan.bind(l),Rs=l.getWebVitals.bind(l),Is=l.dbTrack.bind(l),Ps=l.dbTrackSync.bind(l),Ls=l.getDbQueryCount.bind(l),_s=l.resetDbQueryCount.bind(l),Ds=l.getDbNPlusOnePatterns.bind(l),Fs=l.cronCheckin.bind(l),As=l.cronStart.bind(l),Ns=l.cronWrap.bind(l),Os=l.metricIncrement.bind(l),Hs=l.metricGauge.bind(l),Us=l.metricHistogram.bind(l),Bs=l.metricDistribution.bind(l),$s=l.metricTime.bind(l),zs=l.metricStartTimer.bind(l),Vs=l.flushMetrics.bind(l),Ks=l.profile.bind(l),Ws=l.startProfileSpan.bind(l),qs=l.getProfiles.bind(l),js=l.getLatestProfile.bind(l),Gs=l.flushProfiles.bind(l),Xs=l.getRemoteConfig.bind(l),Qs=l.isRemoteConfigFeatureEnabled.bind(l),Ys=l.onRemoteConfigChange.bind(l),Js=l.registerIdentifyHook.bind(l),br=l;var en=0,Jt=new WeakMap;function Xe(){en=0;}function y(r){let e=Jt.get(r);return e===void 0&&(e=++en,Jt.set(r,e)),e}var tn=new Set(["script","noscript"]),wr=new Set(["src","href","action","poster"]),nn=["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"],Y=null,x=null;function Sr(r){if(typeof document>"u")return {};Y||(Y=new Map);let e=Y.get(r);if(e)return e;try{x||(x=document.createElement("iframe"),x.style.cssText="position:fixed;top:-9999px;left:-9999px;width:0;height:0;border:none;visibility:hidden;",document.body.appendChild(x));let t=x.contentDocument;if(!t)return {};let n=t.createElement(r);t.body.appendChild(n);let i=t.defaultView.getComputedStyle(n),o={};for(let s of nn)o[s]=i.getPropertyValue(s);return t.body.removeChild(n),Y.set(r,o),o}catch{return {}}}function Qe(r){if(typeof window>"u")return null;try{let e=r.tagName.toLowerCase();if(tn.has(e)||e==="head"||e==="html"||e==="meta"||e==="link"||e==="title")return null;let t=window.getComputedStyle(r),n=Sr(e),i=[];for(let o of nn){let s=t.getPropertyValue(o);s&&s!==n[o]&&i.push(`${o}:${s}`);}return i.length>0?i.join(";"):null}catch{return null}}var L=new Map;async function rn(r){if(L.has(r))return L.get(r)??null;try{let e=await fetch(r,{mode:"cors"});if(!e.ok)return L.set(r,null),null;let t=await e.text(),n=ye(t,r);return L.set(r,n),n}catch{return L.set(r,null),null}}function Tr(r){return L.get(r)??null}function on(){x&&x.parentNode&&x.parentNode.removeChild(x),x=null,Y=null,L.clear();}function sn(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 ye(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 Zt(r){try{let e=r.cssRules,t="";for(let n=0;n<e.length;n++)t+=e[n].cssText+`
|
|
4
|
+
`;return t}catch{return null}}function be(r){let e=r.tagName.toLowerCase(),t=location.href;if(e==="style"){let n=r;if(n.sheet){let o=Zt(n.sheet);if(o!==null)return ye(o,t)}let i=r.textContent||"";return i?ye(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=Zt(n.sheet);if(o!==null)return ye(o,i)}if(n.href){let o=Tr(n.href);if(o)return o}return null}return null}function kr(r,e){return r.split(",").map(t=>{let n=t.trim().split(/\s+/);return n[0]&&(n[0]=sn(n[0],e)),n.join(" ")}).join(", ")}function H(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(tn.has(s))return null;let a=t||s==="svg"||i instanceof SVGElement,c={},u=location.href;for(let d=0;d<i.attributes.length;d++){let f=i.attributes[d],g=f.name,m=f.value;g.startsWith("on")||m&&m.toLowerCase().startsWith("javascript:")||(wr.has(g)&&(m=sn(m,u)),g==="srcset"&&(m=kr(m,u)),c[g]=m);}if(s==="style"||s==="link"&&i.getAttribute("rel")==="stylesheet"){let d=be(i);d&&(c._cssText=d);}if(!a&&s!=="style"&&s!=="link"){let d=Qe(i);d&&(c._computedStyle=d);}if(s==="input"){let d=i,f=(d.type||"").toLowerCase();if(f==="checkbox"||f==="radio")c._checked=String(d.checked);else {let g=e.maskInputs?"***":d.value;g&&(c._value=g);}}else if(s==="textarea"){let d=i,f=e.maskInputs?"***":d.value;f&&(c._value=f);}else if(s==="select"){let d=i;c._selectedIndex=String(d.selectedIndex);}if(s==="canvas")try{let f=i.toDataURL("image/webp",.4);f&&f!=="data:,"&&(c._canvasDataUrl=f);}catch{}e.maskSelector&&i.matches(e.maskSelector);let p=[];for(let d of Array.from(i.childNodes)){let f=H(d,e,a);f&&p.push(f);}let h={id:n,type:"element",tagName:s,attributes:Object.keys(c).length>0?c:void 0,children:p.length>0?p:void 0};return a&&(h.isSVG=true),h}return null}function we(r){if(typeof document>"u")return null;Xe();let e=H(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 Se=["authorization","cookie","set-cookie","x-api-key","x-auth-token"],J=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"),a;n?.body&&(typeof n.body=="string"?a=n.body.length:n.body instanceof Blob&&(a=n.body.size));try{let c=await e.originalFetch.call(window,t,n),u=Date.now()-o,p={method:s.toUpperCase(),url:e.truncateUrl(i),status:c.status,statusText:c.statusText,duration:u,requestSize:a,initiator:"fetch"};return e.captureHeaders&&(p.requestHeaders=e.safeHeaders(n?.headers),p.responseHeaders=e.headersToObject(c.headers)),e.emit(p),c}catch(c){let u=Date.now()-o;throw e.emit({method:s.toUpperCase(),url:e.truncateUrl(i),duration:u,requestSize:a,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 a=()=>{let c=Date.now()-o,u;try{n.responseType===""||n.responseType==="text"?u=n.responseText?.length:n.responseType==="json"&&n.response!=null?u=JSON.stringify(n.response).length:n.responseType==="arraybuffer"&&n.response?u=n.response.byteLength:n.responseType==="blob"&&n.response&&(u=n.response.size);}catch{}let p={method:(n._spMethod||"GET").toUpperCase(),url:e.truncateUrl(i),status:n.status,statusText:n.statusText,duration:c,requestSize:s,responseSize:u,initiator:"xhr"};n.status===0&&(p.error="Network error"),e.emit(p),n.removeEventListener("loadend",a);};return n.addEventListener("loadend",a),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]=Se.includes(i.toLowerCase())?"[REDACTED]":n;});else if(Array.isArray(e))for(let[n,i]of e)t[n]=Se.includes(n.toLowerCase())?"[REDACTED]":i;else for(let[n,i]of Object.entries(e))t[n]=Se.includes(n.toLowerCase())?"[REDACTED]":i;return t}headersToObject(e){let t={};return e.forEach((n,i)=>{t[i]=Se.includes(i.toLowerCase())?"[REDACTED]":n;}),t}};var Z=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?`
|
|
5
5
|
`+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(`
|
|
6
6
|
`).slice(4).join(`
|
|
7
|
-
`)||void 0}catch{return}}};var Sr="https://ingest.sitepong.com",Tr=2e4,kr=3600*1e3,Ye=3,xr=5e3,ee=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:kr,flushInterval:5e3,maxBatchSize:100,sampleRate:1,debug:false,bufferDuration:Tr,...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=we({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=[],on(),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=we({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?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>=Ye){this.disabled=true,console.warn(`[SitePong Replay] Disabled after ${Ye} consecutive failures. Check that ${n} is accessible and has proper CORS headers.`);return}this.log(`Failed to flush replay events (attempt ${this.flushFailures}/${Ye}):`,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=H(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},a=n.tagName?.toLowerCase();if(a==="style"||a==="link"&&n.getAttribute("rel")==="stylesheet"){let c=be(n);c&&(s._cssText=c);}if(i==="class"||i==="style"){let c=Qe(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=be(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=d=>{this.mouseMoveBuffer.push({x:d.clientX,y:d.clientY,t:Date.now()-this.sessionStartTime}),this.mouseMoveFlushTimer||(this.mouseMoveFlushTimer=setTimeout(()=>{if(this.mouseMoveBuffer.length>0){let f={positions:[...this.mouseMoveBuffer]};this.addEvent("mouse_move",f),this.mouseMoveBuffer=[];}this.mouseMoveFlushTimer=null;},1e3));},t=d=>{let f=d.target;this.addEvent("mouse_click",{x:d.clientX,y:d.clientY,targetId:y(f),button:d.button}),this.takeInteractionSnapshot();},n=d=>{let f=d.target;this.addEvent("mouse_click",{x:d.clientX,y:d.clientY,targetId:y(f),button:2}),this.takeInteractionSnapshot();},i=()=>{this.addEvent("mouse_leave",{});},o=d=>{let f=d.touches[0];if(!f)return;let g=d.target;this.addEvent("touch",{x:f.clientX,y:f.clientY,targetId:y(g)}),this.takeInteractionSnapshot();},s=null,a=()=>{s&&clearTimeout(s),s=setTimeout(()=>{let d={id:0,x:window.scrollX,y:window.scrollY};this.addEvent("scroll",d),this.takeInteractionSnapshot();},1e3);},c=d=>{let f=d.target;if(!f)return;let g={id:y(f),value:this.config.maskInputs?"***":f.value};"checked"in f&&(g.isChecked=f.checked),this.addEvent("input",g);},u=()=>{this.addEvent("resize",{width:window.innerWidth,height:window.innerHeight});},p=d=>{d.target&&d.target!==document&&this.addEvent("focus",{id:y(d.target)});},h=d=>{d.target&&d.target!==document&&this.addEvent("blur",{id:y(d.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",a,{passive:true}),document.addEventListener("input",c,{passive:true}),window.addEventListener("resize",u,{passive:true}),document.addEventListener("focus",p,{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",a),()=>document.removeEventListener("input",c),()=>window.removeEventListener("resize",u),()=>document.removeEventListener("focus",p,{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 J(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 Z(e=>{this.addEvent("console",e.data);},{levels:this.config.consoleLevels}),this.consoleRecorder.start());}startTrimTimer(){this.trimTimer=setInterval(()=>{this.trimBuffer();},xr);}takeInteractionSnapshot(){let e=Date.now();if(e-this.lastSnapshotTime<this.snapshotCooldown)return;this.lastSnapshotTime=e;let t=we({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{rn(n.href).catch(()=>{});}}}log(...e){this.config.debug&&console.log("[SitePong Replay]",...e);}};function Je(){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=Er(r);e+=t;let n=Cr(r);e+=n;let i=Mr(r);e+=i;let o=Rr(r);e+=o;let s=Ir(r);e+=s;let a=Pr(r);return e+=a,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 Er(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),a=/Win/.test(n),c=/Mac/.test(n),u=/Linux/.test(n);(i&&!a||o&&!c||s&&!u)&&(r.platformMismatch=true,r.uaSpoofed=true,e+=.3);let p=/Chrome\/\d+/.test(t)&&!/Edge|OPR|Brave/.test(t);p&&!("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 d=navigator;if(d.userAgentData?.brands){let m=d.userAgentData.brands.map(b=>b.brand);(m.length===0||m.every(b=>b===""||b==="Not A;Brand"))&&(r.antiDetectBrowser=true,e+=.25);}/mobile|android|iphone|ipad/i.test(t)||(navigator.plugins?.length||0)===0&&p&&(r.pluginAnomaly=true,e+=.1);let f=navigator.hardwareConcurrency||0,g=navigator.deviceMemory||0;return f>0&&g>0&&f>=16&&g<=1&&(r.featureAnomaly=true,e+=.15),Math.min(e,.5)}function Cr(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 a=n.getImageData(0,0,100,20).data,c=!0,u=!0,p=a[0];for(let d=0;d<a.length;d+=4)(a[d]!==0||a[d+1]!==0||a[d+2]!==0)&&(c=!1),a[d]!==p&&(u=!1);(c||u)&&(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 Mr(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),a=["Brian Paul","Mesa","VMware"];["llvmpipe","softpipe","Mesa","SwiftShader"].some(g=>s.includes(g))&&!a.some(g=>o.includes(g))&&(r.webglSpoofed=!0,e+=.25);let u=navigator.userAgent,p=/mobile|android|iphone|ipad/i.test(u),h=/GeForce|Radeon|Intel.*HD|GTX|RTX|Vega/i.test(s);p&&h&&(r.webglSpoofed=!0,e+=.3);let d=Object.getOwnPropertyDescriptor(WebGLRenderingContext.prototype,"getParameter");d&&typeof d.value=="function"&&(d.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 Rr(r){if(typeof navigator>"u"||typeof window>"u")return 0;let e=[],t=navigator.userAgent;try{let s=document.createElement("canvas"),a=s.getContext("webgl")||s.getContext("experimental-webgl");if(a&&a instanceof WebGLRenderingContext){let c=a.getExtension("WEBGL_debug_renderer_info");if(c){let u=a.getParameter(c.UNMASKED_RENDERER_WEBGL).toLowerCase(),p=a.getParameter(c.UNMASKED_VENDOR_WEBGL).toLowerCase(),h=["vmware","virtualbox","hyper-v","parallels","qemu","llvmpipe","mesa"],d=["vmware","innotek","microsoft basic","parallels"];for(let f of h)u.includes(f)&&e.push(`webgl_renderer:${f}`);for(let f of d)p.includes(f)&&e.push(`webgl_vendor:${f}`);}}}catch{}if(typeof screen<"u"){let s=screen.width,a=screen.height;[[800,600],[1024,768],[1280,800]].some(([u,p])=>s===u&&a===p)&&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 Ir(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 Pr(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 an(){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:Lr(),localStorage:_r(),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 cn(){let r={};r.canvasFingerprint=Dr();let e=Fr();return r.webglVendor=e.vendor,r.webglRenderer=e.renderer,r.audioFingerprint=await Ar(),r.fontFingerprint=Kr(),r.mathFingerprint=Wr(),r.webglRenderHash=qr(),r.cssFeatureHash=jr(),r.localIps=await Gr(),r}async function Ze(r){let t={...an()};r&&(t.extended=await cn());let n=un();return t.smart=n,t.incognito=n.incognito,t.bot=n.bot,t}async function ln(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 un(){let r={};r.incognito=Nr(),r.bot=Or(),r.privacyBrowser=Hr(),r.devToolsOpen=Ur(),r.connectionType=Br(),r.doNotTrack=$r(),r.notificationsEnabled=zr();let e=Vr();r.deviceFirstSeen=e.firstSeen,r.deviceVisitCount=e.visitCount;let t=Je();return r.browserTampered=t.browserTampered,r.canvasTampered=t.canvasTampered,r.webglTampered=t.webglTampered,r.vmDetected=t.vmDetected,r.vmIndicators=t.signals.vmIndicators,r}function Lr(){try{let r="__sp_test__";return sessionStorage.setItem(r,"1"),sessionStorage.removeItem(r),!0}catch{return false}}function _r(){try{let r="__sp_test__";return localStorage.setItem(r,"1"),localStorage.removeItem(r),!0}catch{return false}}function Dr(){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),U(r.toDataURL())):void 0}catch{return}}function Fr(){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 Ar(){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 U(`audio:${o.toFixed(6)}`)}catch{return}}function Nr(){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 Or(){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 Hr(){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 Ur(){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 Br(){if(typeof navigator>"u")return;let r=navigator.connection;if(r)return r.effectiveType||r.type||void 0}function $r(){if(typeof navigator>"u")return false;let r=navigator.doNotTrack;return r==="1"||r==="yes"}function zr(){return typeof Notification>"u"?false:Notification.permission==="granted"}function Vr(){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 Kr(){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 a=[];for(let c of e)for(let u of r)if(o.font=`${n} '${c}', ${u}`,o.measureText(t).width!==s[u]){a.push(c);break}return U(a.join(","))}catch{return}}function Wr(){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 U(r.map(e=>e.toString()).join(","))}catch{return}}function qr(){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),U(r.toDataURL())}catch{return}}function jr(){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 U(e)}catch{return}}async function Gr(){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 U(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 te=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 u=1;u<this.mousePoints.length;u++){let p=this.mousePoints[u-1],h=this.mousePoints[u],d=h.t-p.t||1,f=h.x-p.x,g=h.y-p.y,m=Math.sqrt(f*f+g*g),b=m/d;if(e.push(b),m<3&&m>0&&o++,u>=2){let w=this.mousePoints[u-2],se=w.x+(h.x-w.x)*((p.t-w.t)/(h.t-w.t)),Ie=w.y+(h.y-w.y)*((p.t-w.t)/(h.t-w.t)),ae=Math.sqrt((p.x-se)**2+(p.y-Ie)**2);i++,ae<2&&n++;}if(u>=2){let w=e[e.length-2]||0;t.push(Math.abs(b-w)/d);}}let s=e.reduce((u,p)=>u+p,0)/e.length,a=Math.max(...e),c=t.length>0?t.reduce((u,p)=>u+p,0)/t.length:0;return {totalMovements:this.mousePoints.length,averageSpeed:Math.round(s*1e3)/1e3,maxSpeed:Math.round(a*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 a=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/a);}let n=e.reduce((s,a)=>s+a,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 a=.5;e.jitter>.05&&(a+=.15),e.straightLineRatio<.5?a+=.15:e.straightLineRatio>.9&&(a-=.2),e.averageSpeed>0&&e.maxSpeed/e.averageSpeed>3&&(a+=.1),e.averageAcceleration>0&&(a+=.1),o+=Math.max(0,Math.min(1,a))-.5;}if(t.hasKeystrokes){s++;let a=.5;t.intervalVariance>1e3?a+=.2:t.intervalVariance<100&&(a-=.2),(t.averageInterval>0?Math.sqrt(t.intervalVariance)/t.averageInterval:0)>.3&&(a+=.15),t.holdTimeVariance>500&&(a+=.1),o+=Math.max(0,Math.min(1,a))-.5;}if(n.hasScroll){s++;let a=.5;n.smoothness>.3&&n.smoothness<.9&&(a+=.2),o+=Math.max(0,Math.min(1,a))-.5;}if(i.hasClicks){s++;let a=.5;i.intervalVariance>5e4?a+=.15:i.intervalVariance<100&&(a-=.2),o+=Math.max(0,Math.min(1,a))-.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 et(){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=Xr(),r.torBrowser&&(i=true,e+=.9);try{r.webrtcLeak=await Qr(),r.webrtcLeak&&(t=!0,e+=.3);}catch{r.webrtcLeak=null;}r.connectionType=Yr(),(r.connectionType==="unknown"||r.connectionType===null)&&(e+=.05),r.knownVPNExtension=Jr(),r.knownVPNExtension&&(t=true,e+=.4);let o=Intl.DateTimeFormat().resolvedOptions().timeZone,s=navigator.language;if(o&&s){let a=Zr(o),c=s.split("-")[1]?.toUpperCase();a&&c&&a!==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 Xr(){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 Qr(){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 Yr(){if(typeof navigator>"u")return null;let r=navigator;return r.connection&&(r.connection.type||r.connection.effectiveType)||null}function Jr(){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 Zr(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 ei="https://ingest.sitepong.com",tt="sitepong_visitor",dn=720*60*60*1e3,pn="__sp_vid",ti=63072e3,ne=class{constructor(e){this.cachedVisitor=null;this.pendingRequest=null;this.config={endpoint:ei,enabled:true,debug:false,...e},this.behaviorAnalyzer=new te,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");_()?ce():null;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 Ze(this.config.extendedSignals??false)}async getFraudCheck(){let[e,t,n]=await Promise.all([this.getVisitorId(),this.getDeviceSignals(),et().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 ln(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>dn:true}loadFromStorage(){if(!(typeof window>"u"||typeof localStorage>"u"))try{let e=localStorage.getItem(tt);if(!e)return;let t=JSON.parse(e);this.isCacheExpiredAt(t.cachedAt)?localStorage.removeItem(tt):(this.cachedVisitor=t,this.log("Loaded cached visitor from storage"));}catch{}}saveToStorage(){if(!(typeof window>"u"||typeof localStorage>"u")&&this.cachedVisitor)try{localStorage.setItem(tt,JSON.stringify(this.cachedVisitor));}catch{}}isCacheExpiredAt(e){return Date.now()-e>dn}getCookieVisitorId(){if(!(typeof document>"u"))try{return document.cookie.match(new RegExp(`(?:^|; )${pn}=([^;]*)`))?.[1]||void 0}catch{return}}setCookieVisitorId(e){if(!(typeof document>"u"))try{document.cookie=`${pn}=${e}; path=/; max-age=${ti}; SameSite=Lax`;}catch{}}log(...e){this.config.debug&&console.log("[SitePong Fingerprint]",...e);}};var it;var wn=-1,$=function(r){addEventListener("pageshow",(function(e){e.persisted&&(wn=e.timeStamp,r(e));}),true);},ot=function(){var r=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},Ee=function(){var r=ot();return r&&r.activationStart||0},C=function(r,e){var t=ot(),n="navigate";return wn>=0?n="back-forward-cache":t&&(document.prerendering||Ee()>0?n="prerender":document.wasDiscarded?n="restore":t.type&&(n=t.type.replace(/_/g,"-"))),{name:r,value:e===void 0?-1:e,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:n}},re=function(r,e,t){try{if(PerformanceObserver.supportedEntryTypes.includes(r)){var n=new PerformanceObserver((function(i){Promise.resolve().then((function(){e(i.getEntries());}));}));return n.observe(Object.assign({type:r,buffered:!0},t||{})),n}}catch{}},M=function(r,e,t,n){var i,o;return function(s){e.value>=0&&(s||n)&&((o=e.value-(i||0))||i===void 0)&&(i=e.value,e.delta=o,e.rating=(function(a,c){return a>c[1]?"poor":a>c[0]?"needs-improvement":"good"})(e.value,t),r(e));}},st=function(r){requestAnimationFrame((function(){return requestAnimationFrame((function(){return r()}))}));},Ce=function(r){document.addEventListener("visibilitychange",(function(){document.visibilityState==="hidden"&&r();}));},at=function(r){var e=false;return function(){e||(r(),e=true);}},B=-1,fn=function(){return document.visibilityState!=="hidden"||document.prerendering?1/0:0},xe=function(r){document.visibilityState==="hidden"&&B>-1&&(B=r.type==="visibilitychange"?r.timeStamp:0,ni());},hn=function(){addEventListener("visibilitychange",xe,true),addEventListener("prerenderingchange",xe,true);},ni=function(){removeEventListener("visibilitychange",xe,true),removeEventListener("prerenderingchange",xe,true);},Sn=function(){return B<0&&(B=fn(),hn(),$((function(){setTimeout((function(){B=fn(),hn();}),0);}))),{get firstHiddenTime(){return B}}},Me=function(r){document.prerendering?addEventListener("prerenderingchange",(function(){return r()}),true):r();},gn=[1800,3e3],ct=function(r,e){e=e||{},Me((function(){var t,n=Sn(),i=C("FCP"),o=re("paint",(function(s){s.forEach((function(a){a.name==="first-contentful-paint"&&(o.disconnect(),a.startTime<n.firstHiddenTime&&(i.value=Math.max(a.startTime-Ee(),0),i.entries.push(a),t(true)));}));}));o&&(t=M(r,i,gn,e.reportAllChanges),$((function(s){i=C("FCP"),t=M(r,i,gn,e.reportAllChanges),st((function(){i.value=performance.now()-s.timeStamp,t(true);}));})));}));},mn=[.1,.25],Tn=function(r,e){e=e||{},ct(at((function(){var t,n=C("CLS",0),i=0,o=[],s=function(c){c.forEach((function(u){if(!u.hadRecentInput){var p=o[0],h=o[o.length-1];i&&u.startTime-h.startTime<1e3&&u.startTime-p.startTime<5e3?(i+=u.value,o.push(u)):(i=u.value,o=[u]);}})),i>n.value&&(n.value=i,n.entries=o,t());},a=re("layout-shift",s);a&&(t=M(r,n,mn,e.reportAllChanges),Ce((function(){s(a.takeRecords()),t(true);})),$((function(){i=0,n=C("CLS",0),t=M(r,n,mn,e.reportAllChanges),st((function(){return t()}));})),setTimeout(t,0));})));},kn=0,nt=1/0,Te=0,ri=function(r){r.forEach((function(e){e.interactionId&&(nt=Math.min(nt,e.interactionId),Te=Math.max(Te,e.interactionId),kn=Te?(Te-nt)/7+1:0);}));},xn=function(){return it?kn:performance.interactionCount||0},ii=function(){"interactionCount"in performance||it||(it=re("event",ri,{type:"event",buffered:true,durationThreshold:0}));},E=[],ke=new Map,En=0,oi=function(){var r=Math.min(E.length-1,Math.floor((xn()-En)/50));return E[r]},si=[],ai=function(r){if(si.forEach((function(i){return i(r)})),r.interactionId||r.entryType==="first-input"){var e=E[E.length-1],t=ke.get(r.interactionId);if(t||E.length<10||r.duration>e.latency){if(t)r.duration>t.latency?(t.entries=[r],t.latency=r.duration):r.duration===t.latency&&r.startTime===t.entries[0].startTime&&t.entries.push(r);else {var n={id:r.interactionId,latency:r.duration,entries:[r]};ke.set(n.id,n),E.push(n);}E.sort((function(i,o){return o.latency-i.latency})),E.length>10&&E.splice(10).forEach((function(i){return ke.delete(i.id)}));}}},Cn=function(r){var e=self.requestIdleCallback||self.setTimeout,t=-1;return r=at(r),document.visibilityState==="hidden"?r():(t=e(r),Ce(r)),t},vn=[200,500],Mn=function(r,e){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(e=e||{},Me((function(){var t;ii();var n,i=C("INP"),o=function(a){Cn((function(){a.forEach(ai);var c=oi();c&&c.latency!==i.value&&(i.value=c.latency,i.entries=c.entries,n());}));},s=re("event",o,{durationThreshold:(t=e.durationThreshold)!==null&&t!==void 0?t:40});n=M(r,i,vn,e.reportAllChanges),s&&(s.observe({type:"first-input",buffered:true}),Ce((function(){o(s.takeRecords()),n(true);})),$((function(){En=xn(),E.length=0,ke.clear(),i=C("INP"),n=M(r,i,vn,e.reportAllChanges);})));})));},yn=[2500,4e3],rt={},Rn=function(r,e){e=e||{},Me((function(){var t,n=Sn(),i=C("LCP"),o=function(c){e.reportAllChanges||(c=c.slice(-1)),c.forEach((function(u){u.startTime<n.firstHiddenTime&&(i.value=Math.max(u.startTime-Ee(),0),i.entries=[u],t());}));},s=re("largest-contentful-paint",o);if(s){t=M(r,i,yn,e.reportAllChanges);var a=at((function(){rt[i.id]||(o(s.takeRecords()),s.disconnect(),rt[i.id]=true,t(true));}));["keydown","click"].forEach((function(c){addEventListener(c,(function(){return Cn(a)}),{once:true,capture:true});})),Ce(a),$((function(c){i=C("LCP"),t=M(r,i,yn,e.reportAllChanges),st((function(){i.value=performance.now()-c.timeStamp,rt[i.id]=true,t(true);}));}));}}));},bn=[800,1800],ci=function r(e){document.prerendering?Me((function(){return r(e)})):document.readyState!=="complete"?addEventListener("load",(function(){return r(e)}),true):setTimeout(e,0);},In=function(r,e){e=e||{};var t=C("TTFB"),n=M(r,t,bn,e.reportAllChanges);ci((function(){var i=ot();i&&(t.value=Math.max(i.responseStart-Ee(),0),t.entries=[i],n(true),$((function(){t=C("TTFB",0),(n=M(r,t,bn,e.reportAllChanges))(true);})));}));};var li="https://ingest.sitepong.com",ui=1e4,lt=3,di=200,Pn=200,Ln=3e4;function pi(r){let e=[],t=document.getElementsByTagName("*"),n=/url\(("[^"]*"|'[^']*'|[^)]*)\)/i;for(let i=0;i<t.length;i++){let o=t[i],s="";if(o.tagName==="IMG"&&(s=o.currentSrc||o.src),!s){let g=getComputedStyle(o).getPropertyValue("background-image");if(g){let m=n.exec(g);m!==null&&(s=m[1],(s.startsWith('"')||s.startsWith("'"))&&(s=s.substr(1,s.length-2)));}}if(!s)continue;let a=s.substr(0,10)==="data:image"?0:r[s];if(a===void 0)continue;let c=o.getBoundingClientRect(),u=Math.max(c.top,0),p=Math.max(c.left,0),h=Math.min(c.bottom,window.innerHeight||document.documentElement&&document.documentElement.clientHeight||0),d=Math.min(c.right,window.innerWidth||document.documentElement&&document.documentElement.clientWidth||0);if(h<=u||d<=p)continue;let f=(h-u)*(d-p);e.push({time:a,area:f});}return e}function fi(r,e){let t=Math.max(document.documentElement&&document.documentElement.clientWidth||0,window.innerWidth||0)*Math.max(document.documentElement&&document.documentElement.clientHeight||0,window.innerHeight||0)/10,n=t*r;for(let i=0;i<e.length;i++){let{time:o,area:s}=e[i];t+=s,n+=s*(o>r?o:r);}return t===0?0:n/t}var ie=class{constructor(e){this.metrics=[];this.flushTimer=null;this.flushFailures=0;this.disabled=false;this.vitals={};this.activeTransactions=new Map;this.resourceObserver=null;this.resourceTimeMap={};this.resourceCount=0;this.pageLoadTimer=null;this.pageRenderTimer=null;this.config={endpoint:li,enabled:true,webVitals:true,navigationTiming:true,resourceTiming:true,capturePageLoadTimings:true,capturePageRenderTimings:true,excludedResourceUrls:[],flushInterval:ui,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!==false&&this.initWebVitals(),this.config.resourceTiming!==false&&this.initResourceTiming(),this.config.capturePageLoadTimings!==false&&this.initPageLoadTiming(),this.config.capturePageRenderTimings!==false&&this.initPageRenderTiming(),this.startFlushTimer(),this.log("Performance monitoring initialized"));}initWebVitals(){Tn(e=>{this.vitals.cls=e.value,this.reportVital("CLS",e.value,"score");}),Mn(e=>{this.vitals.inp=e.value,this.reportVital("INP",e.value);}),Rn(e=>{this.vitals.lcp=e.value,this.reportVital("LCP",e.value);}),In(e=>{this.vitals.ttfb=e.value,this.reportVital("TTFB",e.value);}),ct(e=>{this.vitals.fcp=e.value,this.reportVital("FCP",e.value);});}initResourceTiming(){if(!(typeof PerformanceObserver>"u"))try{this.resourceObserver=new PerformanceObserver(e=>{for(let t of e.getEntries())this.processResourceEntry(t);}),this.resourceObserver.observe({type:"resource",buffered:!0});}catch{this.log("PerformanceObserver for resource timing not supported");}}isServiceURL(e){let t=this.config.performanceEndpoint||this.config.endpoint;return e.startsWith(t)}processResourceEntry(e){if(e.duration<0||!e.name.startsWith("http")||this.isServiceURL(e.name))return;this.resourceTimeMap!==null&&(this.resourceTimeMap[e.name]=e.startTime+e.duration);for(let c of this.config.excludedResourceUrls)if(e.name.startsWith(c))return;if(this.resourceCount>=di)return;this.resourceCount++;let t=0;e.connectEnd&&e.connectEnd>e.domainLookupEnd?t=Math.max(0,e.requestStart-e.connectEnd):t=Math.max(0,e.requestStart-e.domainLookupEnd);let n=e.responseStatus&&e.responseStatus===304||e.deliveryType&&e.deliveryType==="cache"||e.transferSize===0&&e.decodedBodySize>0,i=e.responseStatus||0,o=i>=400,s={queueing:e.requestStart-e.fetchStart,dnsLookup:e.domainLookupEnd-e.domainLookupStart,initialConnection:e.connectEnd-e.connectStart,ssl:e.secureConnectionStart>0?e.connectEnd-e.secureConnectionStart:0,ttfb:e.responseStart-e.requestStart,contentDownload:e.responseEnd-e.responseStart,total:e.duration??e.responseEnd-e.startTime,stalled:t,cached:n,failed:o,responseStatus:i,headerSize:e.transferSize>e.encodedBodySize?e.transferSize-e.encodedBodySize:0,encodedBodySize:e.encodedBodySize||0,decodedBodySize:o?-111:e.decodedBodySize||0,transferSize:e.transferSize,initiatorType:e.initiatorType},a=this.config.resourceNameSanitizer?this.config.resourceNameSanitizer(e.name):e.name;this.addMetric({type:"resource",name:a,value:e.duration,unit:"ms",timestamp:new Date().toISOString(),url:typeof window<"u"&&window.location?window.location.href:void 0,data:s});}initPageLoadTiming(){if(typeof window>"u"||!window.performance)return;let e=0,t=0,n=false,i=performance.now();this.pageLoadTimer=setInterval(()=>{if(n){this.pageLoadTimer&&clearInterval(this.pageLoadTimer);return}if(e===0||t===0)for(let a of performance.getEntriesByType("paint"))a.name==="first-paint"&&(e=a.startTime),a.name==="first-contentful-paint"&&(t=a.startTime);let o=performance.getEntriesByType("navigation")[0],s=performance.now()-i>Ln;if((o&&o.loadEventEnd>0||s)&&(n=true,this.pageLoadTimer&&clearInterval(this.pageLoadTimer),o)){let a=o.startTime;this.addMetric({type:"navigation",name:"page_load",value:o.loadEventEnd-a,unit:"ms",timestamp:new Date().toISOString(),url:window.location.href,data:{requestStart:o.requestStart-a,responseStart:o.responseStart-a,responseEnd:o.responseEnd-a,domContentLoadedEventStart:o.domContentLoadedEventEnd-a,domContentLoadedEventEnd:o.domContentLoadedEventEnd-a,loadEventStart:o.loadEventStart-a,loadEventEnd:o.loadEventEnd-a,firstPaint:e,firstContentfulPaint:t,dns:o.domainLookupEnd-o.domainLookupStart,tcp:o.connectEnd-o.connectStart,ttfb:o.responseStart-o.requestStart,domComplete:o.domComplete-a,transferSize:o.transferSize,encodedBodySize:o.encodedBodySize,decodedBodySize:o.decodedBodySize}});}},Pn);}initPageRenderTiming(){if(typeof window>"u"||!window.performance)return;let e=0,t=0,n=0,i=0,o=null,s=false,a=performance.now();this.pageRenderTimer=setInterval(()=>{if(s){this.pageRenderTimer&&clearInterval(this.pageRenderTimer);return}let c=performance.now();if(e===0)for(let p of performance.getEntriesByType("paint"))p.name==="first-contentful-paint"&&(e=p.startTime);if(this.resourceTimeMap!==null){let p=Object.values(this.resourceTimeMap);p.length>0&&(t=Math.max(...p)),c-t>1e3&&(o=pi(this.resourceTimeMap),this.resourceTimeMap=null);}i!==null&&(c-i>50&&(n=c),i=c-n>5e3?null:c);let u=c-a>Ln;if(o!==null&&i===null||u){s=true,this.pageRenderTimer&&clearInterval(this.pageRenderTimer),this.resourceTimeMap=null;let p=o===null?0:fi(e||0,o),h=performance.getEntriesByType("navigation")[0],d=h?h.domContentLoadedEventEnd-h.startTime:0,f=i===null?Math.max(n,e,d):0,g=window.location.href,m=new Date().toISOString();p>0&&this.addMetric({type:"page_render",name:"speed_index",value:Math.round(p),unit:"ms",timestamp:m,url:g}),t>0&&this.addMetric({type:"page_render",name:"visually_complete",value:Math.round(t),unit:"ms",timestamp:m,url:g}),f>0&&this.addMetric({type:"page_render",name:"tti",value:Math.round(f),unit:"ms",timestamp:m,url:g});}},Pn);}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?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.pageLoadTimer&&(clearInterval(this.pageLoadTimer),this.pageLoadTimer=null),this.pageRenderTimer&&(clearInterval(this.pageRenderTimer),this.pageRenderTimer=null),this.resourceObserver&&(this.resourceObserver.disconnect(),this.resourceObserver=null),this.flush();}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?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=[],this.resourceCount=0;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>=lt){this.disabled=true,console.warn(`[SitePong Performance] Disabled after ${lt} 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}/${lt}):`,n);}}log(...e){this.config.debug&&console.log("[SitePong Performance]",...e);}};var ut=9,_n=8;function hi(r,e,t){return Math.round(.299*r+.587*e+.114*t)}function gi(r,e,t){let n=new Float64Array(e*t);for(let i=0;i<e*t;i++){let o=i*4;n[i]=hi(r[o],r[o+1],r[o+2]);}return n}function mi(r,e,t,n,i){let o=new Float64Array(n*i),s=e/n,a=t/i;for(let c=0;c<i;c++){let u=(c+.5)*a-.5;u<0&&(u=0),u>t-1&&(u=t-1);let p=Math.floor(u),h=Math.min(p+1,t-1),d=u-p;for(let f=0;f<n;f++){let g=(f+.5)*s-.5;g<0&&(g=0),g>e-1&&(g=e-1);let m=Math.floor(g),b=Math.min(m+1,e-1),w=g-m,se=r[p*e+m],Ie=r[p*e+b],ae=r[h*e+m],zn=r[h*e+b],wt=se+(Ie-se)*w,Vn=ae+(zn-ae)*w;o[c*n+f]=wt+(Vn-wt)*d;}}return o}function Dn(r,e,t){if(e<=0||t<=0)throw new Error(`dHash: invalid dimensions ${e}x${t}`);if(r.length<e*t*4)throw new Error(`dHash: rgba length ${r.length} too short for ${e}x${t} (need ${e*t*4})`);let n=gi(r,e,t),i=mi(n,e,t,ut,_n),o=new Uint8Array(8);for(let a=0;a<_n;a++){let c=0;for(let u=0;u<8;u++){let p=i[a*ut+u],h=i[a*ut+u+1],d=p<h?1:0;c|=d<<7-u;}o[a]=c;}let s="";for(let a=0;a<8;a++)s+=o[a].toString(16).padStart(2,"0");return s}function vi(r){let e=0;for(;r;)r&=r-1,e++;return e}function Fn(r,e){if(r.length!==e.length)throw new Error(`hamming: length mismatch (${r.length} vs ${e.length})`);if(r.length%2!==0)throw new Error(`hamming: hex string length must be even, got ${r.length}`);let t=0;for(let n=0;n<r.length;n+=2){let i=parseInt(r.slice(n,n+2),16),o=parseInt(e.slice(n,n+2),16);if(Number.isNaN(i)||Number.isNaN(o))throw new Error(`hamming: invalid hex at offset ${n}`);t+=vi(i^o);}return t}var An=10;function oe(r,e){return `${r}:${e}`}function Nn(r){let e=r.lastIndexOf(":");if(e<0)throw new Error(`parseFingerprint: missing ':' in "${r}"`);return {screenName:r.slice(0,e),pHashHex:r.slice(e+1)}}var dt="0000000000000000",yi=50,bi=1e4,wi=1e3,pt=3,$n=480,On="img, picture, video, canvas, iframe, [data-sp-mask]",Hn="sitepong_wt_session_id",ft="sitepong_wt_seq",Un="sitepong_wt_started_at",ht="sitepong_wt_start_sent";function Si(){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 vt=class{constructor(){this.memory={};}get(e){try{if(typeof sessionStorage<"u")return sessionStorage.getItem(e)}catch{}return this.memory[e]??null}set(e,t){try{if(typeof sessionStorage<"u"){sessionStorage.setItem(e,t);return}}catch{}this.memory[e]=t;}get sessionId(){let e=this.get(Hn);return e||(e=Si(),this.set(Hn,e),this.set(Un,String(Date.now())),this.set(ft,"0"),this.set(ht,"0")),e}get startedAt(){let e=this.get(Un),t=e?parseInt(e,10):NaN;return Number.isFinite(t)?t:Date.now()}get startSent(){return this.get(ht)==="1"}markStartSent(){this.set(ht,"1");}nextSequence(){let e=this.get(ft),t=e?parseInt(e,10):0,n=(Number.isFinite(t)?t:0)+1;return this.set(ft,String(n)),n}},Ti=async(r,e,t)=>{let n=await fetch(r,{method:"POST",headers:t.headers,body:e,keepalive:t.keepalive});return {ok:n.ok,status:n.status}},Re=class{constructor(e){this.session=new vt;this.queue=[];this.flushTimer=null;this.flushFailures=0;this.disabled=false;this.active=false;this.distinctId=null;this.currentScreen=null;this.detachAutocapture=null;this.ownAutocapture=null;this.originalPushState=null;this.originalReplaceState=null;this.popstateHandler=null;this.pagehideHandler=null;this.fpCache=new Map;this.uploadedFps=new Set;this.lastRasterAt=new Map;this.rasterInFlight=false;this.config={...e},this.transport=e.transport||Ti,this.rasterizer=e.rasterizer||null;}start(e){if(this.active||typeof window>"u")return;this.active=true,this.rasterizer||(this.rasterizer=new bt({blockSelector:this.combinedBlockSelector(),maskSelector:this.config.maskSelector,maxWidth:$n}));let t=this.session.sessionId;if(this.session.startSent||(this.enqueue(this.baseEvent("session_start")),this.session.markStartSent()),this.log("Started (session",t+")"),this.currentScreen=this.pathname(),this.currentScreen!==null){let n=this.baseEvent("screen_view");n.screen_name=this.currentScreen,this.enqueue(n),this.scheduleFingerprint(this.currentScreen);}this.setupNavigationTracking(),this.setupPagehide(),this.startFlushTimer(),e?this.detachAutocapture=e.addListener(n=>this.onAutocaptureEvent(n)):(this.ownAutocapture=new P({clicks:true,forms:false,pageviews:false,debug:this.config.debug},n=>this.onAutocaptureEvent(n)),this.ownAutocapture.start());}stop(){this.active&&(this.active=false,this.detachAutocapture&&(this.detachAutocapture(),this.detachAutocapture=null),this.ownAutocapture&&(this.ownAutocapture.stop(),this.ownAutocapture=null),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),typeof window<"u"&&(this.popstateHandler&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),this.pagehideHandler&&(window.removeEventListener("pagehide",this.pagehideHandler),this.pagehideHandler=null),this.originalPushState&&(window.history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(window.history.replaceState=this.originalReplaceState,this.originalReplaceState=null)),this.flush(),this.log("Stopped"));}isActive(){return this.active}getSessionId(){return this.session.sessionId}setDistinctId(e){this.distinctId=e;}onAutocaptureEvent(e){if(!this.active||e.type!=="click")return;let t=e.properties,n=typeof t.$x=="number"?t.$x:null,i=typeof t.$y=="number"?t.$y:null;n===null||i===null||this.recordTap({selector:typeof t.$selector=="string"?t.$selector:"",label:typeof t.$el_text=="string"&&t.$el_text||typeof t.$aria_label=="string"&&t.$aria_label||void 0,role:typeof t.$el_role=="string"&&t.$el_role||ki(typeof t.$tag_name=="string"?t.$tag_name:void 0),clientX:n,clientY:i});}recordTap(e){if(!this.active||typeof window>"u")return;let t=window.innerWidth||1,n=window.innerHeight||1,i=this.pathname()??"/",o=this.baseEvent("tap");o.screen_name=i,o.screen_fp=this.fpCache.get(i)??oe(i,dt),o.element_id=e.selector||"unknown",e.label&&(o.element_label=e.label),e.role&&(o.element_role=e.role),o.x=Bn(e.clientX/t),o.y=Bn(e.clientY/n),o.viewport_w=t,o.viewport_h=n,this.enqueue(o),this.scheduleFingerprint(i);}setupNavigationTracking(){if(typeof window>"u"||!window.history||typeof window.addEventListener!="function")return;let e=()=>this.handleRouteChange();this.popstateHandler=e,window.addEventListener("popstate",this.popstateHandler);let t=window.history.pushState.bind(window.history),n=window.history.replaceState.bind(window.history);this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState,window.history.pushState=(...i)=>{t(...i),e();},window.history.replaceState=(...i)=>{n(...i),e();};}handleRouteChange(){if(!this.active)return;let e=this.pathname();if(e===null||e===this.currentScreen)return;let t=this.currentScreen;this.currentScreen=e;let n=this.baseEvent("screen_view");n.screen_name=e,t&&(n.prev_screen_name=t),this.enqueue(n),this.scheduleFingerprint(e);}setupPagehide(){typeof window>"u"||typeof window.addEventListener!="function"||(this.pagehideHandler=()=>{if(!this.active)return;let e=this.baseEvent("session_end");e.reason="background",e.duration_ms=Math.max(0,Date.now()-this.session.startedAt),this.enqueue(e),this.flush({keepalive:true});},window.addEventListener("pagehide",this.pagehideHandler));}baseEvent(e){return {type:e,session_id:this.session.sessionId,sequence:this.session.nextSequence(),timestamp:new Date().toISOString(),platform:"web",app_version:this.config.appVersion||void 0,distinct_id:this.distinctId||void 0,os_version:typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:void 0}}enqueue(e){this.disabled||(this.queue.push(e),this.queue.length>=(this.config.maxBatchSize??yi)&&this.flush());}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval??bi);}async flush(e){if(this.queue.length===0)return;if(this.disabled){this.queue=[];return}let t=this.queue;this.queue=[];try{let n=await this.transport(`${this.config.endpoint}/api/taps`,JSON.stringify({events:t}),{headers:this.headers(),keepalive:e?.keepalive});if(!n.ok)throw new Error(`HTTP ${n.status}`);this.flushFailures=0,this.log(`Flushed ${t.length} events`);}catch(n){if(this.flushFailures++,this.flushFailures>=pt){this.disabled=true,this.queue=[],this.log(`Disabled after ${pt} consecutive flush failures`);return}this.queue.unshift(...t),this.log(`Flush failed (attempt ${this.flushFailures}/${pt}):`,n);}}headers(){return {"Content-Type":"application/json","X-Project-ID":this.config.projectId,"X-API-Key":this.config.apiKey}}scheduleFingerprint(e){if(!this.active||this.disabled||!this.rasterizer)return;let t=Date.now(),n=this.lastRasterAt.get(e)??0,i=this.config.templateThrottleMs??wi;t-n<i||this.rasterInFlight||(this.lastRasterAt.set(e,t),xi(()=>{this.captureFingerprint(e);}));}async captureFingerprint(e){if(!(!this.active||this.rasterInFlight||!this.rasterizer)){this.rasterInFlight=true;try{let t=await this.rasterizer.rasterize();if(!t){this.fpCache.has(e)||this.fpCache.set(e,oe(e,dt));return}let n=Dn(t.rgba,t.width,t.height),i=oe(e,n);this.fpCache.set(e,i),await this.maybeUploadTemplate(e,n,i,t);}catch(t){this.log("Fingerprint capture failed:",t),this.fpCache.has(e)||this.fpCache.set(e,oe(e,dt));}finally{this.rasterInFlight=false;}}}async maybeUploadTemplate(e,t,n,i){for(let o of this.uploadedFps){let s=Nn(o);if(s.screenName===e&&Fn(s.pHashHex,t)<=An)return}if(i.pngBase64)try{(await this.transport(`${this.config.endpoint}/api/taps/template`,JSON.stringify({route_name:e,p_hash:t,width:i.width,height:i.height,image_base64:i.pngBase64}),{headers:this.headers()})).ok&&(this.uploadedFps.add(n),this.log("Uploaded template for",n));}catch(o){this.log("Template upload failed:",o);}}combinedBlockSelector(){return this.config.blockSelector?`${On}, ${this.config.blockSelector}`:On}pathname(){return typeof window>"u"||!window.location?null:window.location.pathname||"/"}log(...e){this.config.debug&&console.log("[SitePong Watchtower]",...e);}};function Bn(r){return Number.isFinite(r)?Math.min(1,Math.max(0,r)):0}function ki(r){switch(r){case "a":return "link";case "button":return "button";case "input":return "input";case "select":return "select";case "textarea":return "textarea";default:return r||void 0}}function xi(r){let e=globalThis;typeof e.requestIdleCallback=="function"?e.requestIdleCallback(r,{timeout:2e3}):setTimeout(r,250);}var Ei=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function gt(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function mt(r){return r.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g,"")}function yt(r,e=false){if(r.type==="text")return gt(mt(r.textContent??""));if(r.type==="comment")return "";let t=(r.tagName||"div").toLowerCase(),n={...r.attributes||{}},i=n._cssText;if(t==="style"||t==="link"){if(typeof i=="string"&&i)return `<style>${gt(mt(i))}</style>`;if(t==="link")return ""}let o=n._computedStyle;typeof o=="string"&&o&&(n.style=n.style?`${n.style};${o}`:o);let s=n._value;typeof s=="string"&&s&&(n.value=s),n._checked==="true"&&(n.checked="checked");let a="";for(let[u,p]of Object.entries(n))u.startsWith("_")||u.startsWith("on")||/^[a-zA-Z_][\w:.-]*$/.test(u)&&(a+=` ${u}="${gt(mt(String(p)))}"`);if(e&&(a=` xmlns="http://www.w3.org/1999/xhtml"${a}`),Ei.has(t))return `<${t}${a}/>`;let c="";if(t==="style"&&typeof i!="string")for(let u of r.children||[])c+=yt(u);else for(let u of r.children||[])c+=yt(u);return `<${t}${a}>${c}</${t}>`}var bt=class{constructor(e){this.options=e;}async rasterize(){try{if(typeof document>"u"||typeof window>"u")return null;Xe();let e=H(document.documentElement,{maskInputs:!0,blockSelector:this.options.blockSelector,maskSelector:this.options.maskSelector});if(!e)return null;let t=window.innerWidth||1,n=window.innerHeight||1,i=yt(e,!0),o=`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}"><foreignObject width="100%" height="100%">${i}</foreignObject></svg>`,s=await Ci(o),a=Math.min(1,(this.options.maxWidth??$n)/t),c=Math.max(1,Math.round(t*a)),u=Math.max(1,Math.round(n*a)),p=document.createElement("canvas");p.width=c,p.height=u;let h=p.getContext("2d");if(!h)return null;h.fillStyle="#ffffff",h.fillRect(0,0,c,u),h.drawImage(s,0,0,c,u);let d=h.getImageData(0,0,c,u),f=new Uint8Array(d.data.buffer,d.data.byteOffset,d.data.byteLength),g=null;try{let m=p.toDataURL("image/png"),b="data:image/png;base64,";g=m.startsWith(b)?m.slice(b.length):null;}catch{g=null;}return {rgba:f,width:c,height:u,pngBase64:g}}catch{return null}}};function Ci(r){return new Promise((e,t)=>{let n=new Blob([r],{type:"image/svg+xml;charset=utf-8"}),i=URL.createObjectURL(n),o=new Image,s=setTimeout(()=>{URL.revokeObjectURL(i),t(new Error("SVG rasterization timed out"));},3e3);o.onload=()=>{clearTimeout(s),URL.revokeObjectURL(i),e(o);},o.onerror=()=>{clearTimeout(s),URL.revokeObjectURL(i),t(new Error("SVG rasterization failed"));},o.src=i;})}z(St());Yt({createReplay:r=>new ee(r),createFingerprint:r=>new ne(r),createPerformance:r=>new ie(r),createWatchtowerCapture:r=>new Re(r)});
|
|
8
|
-
exports.DEFAULT_SUPERLINK_ENDPOINT=ze;exports.SuperLinkClient=X;exports.TracePropagator=he;exports.addBreadcrumb=
|
|
7
|
+
`)||void 0}catch{return}}};var xr="https://ingest.sitepong.com",Er=2e4,Cr=3600*1e3,Ye=3,Mr=5e3,ee=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:xr,enabled:true,maskInputs:true,maxSessionDuration:Cr,flushInterval:5e3,maxBatchSize:100,sampleRate:1,debug:false,bufferDuration:Er,...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=we({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=[],on(),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=we({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?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>=Ye){this.disabled=true,console.warn(`[SitePong Replay] Disabled after ${Ye} consecutive failures. Check that ${n} is accessible and has proper CORS headers.`);return}this.log(`Failed to flush replay events (attempt ${this.flushFailures}/${Ye}):`,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=H(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},a=n.tagName?.toLowerCase();if(a==="style"||a==="link"&&n.getAttribute("rel")==="stylesheet"){let c=be(n);c&&(s._cssText=c);}if(i==="class"||i==="style"){let c=Qe(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=be(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=d=>{this.mouseMoveBuffer.push({x:d.clientX,y:d.clientY,t:Date.now()-this.sessionStartTime}),this.mouseMoveFlushTimer||(this.mouseMoveFlushTimer=setTimeout(()=>{if(this.mouseMoveBuffer.length>0){let f={positions:[...this.mouseMoveBuffer]};this.addEvent("mouse_move",f),this.mouseMoveBuffer=[];}this.mouseMoveFlushTimer=null;},1e3));},t=d=>{let f=d.target;this.addEvent("mouse_click",{x:d.clientX,y:d.clientY,targetId:y(f),button:d.button}),this.takeInteractionSnapshot();},n=d=>{let f=d.target;this.addEvent("mouse_click",{x:d.clientX,y:d.clientY,targetId:y(f),button:2}),this.takeInteractionSnapshot();},i=()=>{this.addEvent("mouse_leave",{});},o=d=>{let f=d.touches[0];if(!f)return;let g=d.target;this.addEvent("touch",{x:f.clientX,y:f.clientY,targetId:y(g)}),this.takeInteractionSnapshot();},s=null,a=()=>{s&&clearTimeout(s),s=setTimeout(()=>{let d={id:0,x:window.scrollX,y:window.scrollY};this.addEvent("scroll",d),this.takeInteractionSnapshot();},1e3);},c=d=>{let f=d.target;if(!f)return;let g={id:y(f),value:this.config.maskInputs?"***":f.value};"checked"in f&&(g.isChecked=f.checked),this.addEvent("input",g);},u=()=>{this.addEvent("resize",{width:window.innerWidth,height:window.innerHeight});},p=d=>{d.target&&d.target!==document&&this.addEvent("focus",{id:y(d.target)});},h=d=>{d.target&&d.target!==document&&this.addEvent("blur",{id:y(d.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",a,{passive:true}),document.addEventListener("input",c,{passive:true}),window.addEventListener("resize",u,{passive:true}),document.addEventListener("focus",p,{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",a),()=>document.removeEventListener("input",c),()=>window.removeEventListener("resize",u),()=>document.removeEventListener("focus",p,{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 J(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 Z(e=>{this.addEvent("console",e.data);},{levels:this.config.consoleLevels}),this.consoleRecorder.start());}startTrimTimer(){this.trimTimer=setInterval(()=>{this.trimBuffer();},Mr);}takeInteractionSnapshot(){let e=Date.now();if(e-this.lastSnapshotTime<this.snapshotCooldown)return;this.lastSnapshotTime=e;let t=we({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{rn(n.href).catch(()=>{});}}}log(...e){this.config.debug&&console.log("[SitePong Replay]",...e);}};function Je(){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=Rr(r);e+=t;let n=Ir(r);e+=n;let i=Pr(r);e+=i;let o=Lr(r);e+=o;let s=_r(r);e+=s;let a=Dr(r);return e+=a,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 Rr(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),a=/Win/.test(n),c=/Mac/.test(n),u=/Linux/.test(n);(i&&!a||o&&!c||s&&!u)&&(r.platformMismatch=true,r.uaSpoofed=true,e+=.3);let p=/Chrome\/\d+/.test(t)&&!/Edge|OPR|Brave/.test(t);p&&!("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 d=navigator;if(d.userAgentData?.brands){let m=d.userAgentData.brands.map(b=>b.brand);(m.length===0||m.every(b=>b===""||b==="Not A;Brand"))&&(r.antiDetectBrowser=true,e+=.25);}/mobile|android|iphone|ipad/i.test(t)||(navigator.plugins?.length||0)===0&&p&&(r.pluginAnomaly=true,e+=.1);let f=navigator.hardwareConcurrency||0,g=navigator.deviceMemory||0;return f>0&&g>0&&f>=16&&g<=1&&(r.featureAnomaly=true,e+=.15),Math.min(e,.5)}function Ir(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 a=n.getImageData(0,0,100,20).data,c=!0,u=!0,p=a[0];for(let d=0;d<a.length;d+=4)(a[d]!==0||a[d+1]!==0||a[d+2]!==0)&&(c=!1),a[d]!==p&&(u=!1);(c||u)&&(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 Pr(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),a=["Brian Paul","Mesa","VMware"];["llvmpipe","softpipe","Mesa","SwiftShader"].some(g=>s.includes(g))&&!a.some(g=>o.includes(g))&&(r.webglSpoofed=!0,e+=.25);let u=navigator.userAgent,p=/mobile|android|iphone|ipad/i.test(u),h=/GeForce|Radeon|Intel.*HD|GTX|RTX|Vega/i.test(s);p&&h&&(r.webglSpoofed=!0,e+=.3);let d=Object.getOwnPropertyDescriptor(WebGLRenderingContext.prototype,"getParameter");d&&typeof d.value=="function"&&(d.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 Lr(r){if(typeof navigator>"u"||typeof window>"u")return 0;let e=[],t=navigator.userAgent;try{let s=document.createElement("canvas"),a=s.getContext("webgl")||s.getContext("experimental-webgl");if(a&&a instanceof WebGLRenderingContext){let c=a.getExtension("WEBGL_debug_renderer_info");if(c){let u=a.getParameter(c.UNMASKED_RENDERER_WEBGL).toLowerCase(),p=a.getParameter(c.UNMASKED_VENDOR_WEBGL).toLowerCase(),h=["vmware","virtualbox","hyper-v","parallels","qemu","llvmpipe","mesa"],d=["vmware","innotek","microsoft basic","parallels"];for(let f of h)u.includes(f)&&e.push(`webgl_renderer:${f}`);for(let f of d)p.includes(f)&&e.push(`webgl_vendor:${f}`);}}}catch{}if(typeof screen<"u"){let s=screen.width,a=screen.height;[[800,600],[1024,768],[1280,800]].some(([u,p])=>s===u&&a===p)&&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 _r(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 Dr(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 an(){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:Fr(),localStorage:Ar(),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 cn(){let r={};r.canvasFingerprint=Nr();let e=Or();return r.webglVendor=e.vendor,r.webglRenderer=e.renderer,r.audioFingerprint=await Hr(),r.fontFingerprint=jr(),r.mathFingerprint=Gr(),r.webglRenderHash=Xr(),r.cssFeatureHash=Qr(),r.localIps=await Yr(),r}async function Ze(r){let t={...an()};r&&(t.extended=await cn());let n=un();return t.smart=n,t.incognito=n.incognito,t.bot=n.bot,t}async function ln(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 un(){let r={};r.incognito=Ur(),r.bot=Br(),r.privacyBrowser=$r(),r.devToolsOpen=zr(),r.connectionType=Vr(),r.doNotTrack=Kr(),r.notificationsEnabled=Wr();let e=qr();r.deviceFirstSeen=e.firstSeen,r.deviceVisitCount=e.visitCount;let t=Je();return r.browserTampered=t.browserTampered,r.canvasTampered=t.canvasTampered,r.webglTampered=t.webglTampered,r.vmDetected=t.vmDetected,r.vmIndicators=t.signals.vmIndicators,r}function Fr(){try{let r="__sp_test__";return sessionStorage.setItem(r,"1"),sessionStorage.removeItem(r),!0}catch{return false}}function Ar(){try{let r="__sp_test__";return localStorage.setItem(r,"1"),localStorage.removeItem(r),!0}catch{return false}}function Nr(){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),U(r.toDataURL())):void 0}catch{return}}function Or(){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 Hr(){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 U(`audio:${o.toFixed(6)}`)}catch{return}}function Ur(){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 Br(){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 $r(){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 zr(){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 Vr(){if(typeof navigator>"u")return;let r=navigator.connection;if(r)return r.effectiveType||r.type||void 0}function Kr(){if(typeof navigator>"u")return false;let r=navigator.doNotTrack;return r==="1"||r==="yes"}function Wr(){return typeof Notification>"u"?false:Notification.permission==="granted"}function qr(){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 jr(){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 a=[];for(let c of e)for(let u of r)if(o.font=`${n} '${c}', ${u}`,o.measureText(t).width!==s[u]){a.push(c);break}return U(a.join(","))}catch{return}}function Gr(){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 U(r.map(e=>e.toString()).join(","))}catch{return}}function Xr(){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),U(r.toDataURL())}catch{return}}function Qr(){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 U(e)}catch{return}}async function Yr(){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 U(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 te=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 u=1;u<this.mousePoints.length;u++){let p=this.mousePoints[u-1],h=this.mousePoints[u],d=h.t-p.t||1,f=h.x-p.x,g=h.y-p.y,m=Math.sqrt(f*f+g*g),b=m/d;if(e.push(b),m<3&&m>0&&o++,u>=2){let w=this.mousePoints[u-2],se=w.x+(h.x-w.x)*((p.t-w.t)/(h.t-w.t)),Ie=w.y+(h.y-w.y)*((p.t-w.t)/(h.t-w.t)),ae=Math.sqrt((p.x-se)**2+(p.y-Ie)**2);i++,ae<2&&n++;}if(u>=2){let w=e[e.length-2]||0;t.push(Math.abs(b-w)/d);}}let s=e.reduce((u,p)=>u+p,0)/e.length,a=Math.max(...e),c=t.length>0?t.reduce((u,p)=>u+p,0)/t.length:0;return {totalMovements:this.mousePoints.length,averageSpeed:Math.round(s*1e3)/1e3,maxSpeed:Math.round(a*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 a=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/a);}let n=e.reduce((s,a)=>s+a,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 a=.5;e.jitter>.05&&(a+=.15),e.straightLineRatio<.5?a+=.15:e.straightLineRatio>.9&&(a-=.2),e.averageSpeed>0&&e.maxSpeed/e.averageSpeed>3&&(a+=.1),e.averageAcceleration>0&&(a+=.1),o+=Math.max(0,Math.min(1,a))-.5;}if(t.hasKeystrokes){s++;let a=.5;t.intervalVariance>1e3?a+=.2:t.intervalVariance<100&&(a-=.2),(t.averageInterval>0?Math.sqrt(t.intervalVariance)/t.averageInterval:0)>.3&&(a+=.15),t.holdTimeVariance>500&&(a+=.1),o+=Math.max(0,Math.min(1,a))-.5;}if(n.hasScroll){s++;let a=.5;n.smoothness>.3&&n.smoothness<.9&&(a+=.2),o+=Math.max(0,Math.min(1,a))-.5;}if(i.hasClicks){s++;let a=.5;i.intervalVariance>5e4?a+=.15:i.intervalVariance<100&&(a-=.2),o+=Math.max(0,Math.min(1,a))-.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 et(){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=Jr(),r.torBrowser&&(i=true,e+=.9);try{r.webrtcLeak=await Zr(),r.webrtcLeak&&(t=!0,e+=.3);}catch{r.webrtcLeak=null;}r.connectionType=ei(),(r.connectionType==="unknown"||r.connectionType===null)&&(e+=.05),r.knownVPNExtension=ti(),r.knownVPNExtension&&(t=true,e+=.4);let o=Intl.DateTimeFormat().resolvedOptions().timeZone,s=navigator.language;if(o&&s){let a=ni(o),c=s.split("-")[1]?.toUpperCase();a&&c&&a!==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 Jr(){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 Zr(){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 ei(){if(typeof navigator>"u")return null;let r=navigator;return r.connection&&(r.connection.type||r.connection.effectiveType)||null}function ti(){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 ni(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 ri="https://ingest.sitepong.com",tt="sitepong_visitor",dn=720*60*60*1e3,pn="__sp_vid",ii=63072e3,ne=class{constructor(e){this.cachedVisitor=null;this.pendingRequest=null;this.config={endpoint:ri,enabled:true,debug:false,...e},this.behaviorAnalyzer=new te,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");_()?ce():null;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 Ze(this.config.extendedSignals??false)}async getFraudCheck(){let[e,t,n]=await Promise.all([this.getVisitorId(),this.getDeviceSignals(),et().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 ln(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>dn:true}loadFromStorage(){if(!(typeof window>"u"||typeof localStorage>"u"))try{let e=localStorage.getItem(tt);if(!e)return;let t=JSON.parse(e);this.isCacheExpiredAt(t.cachedAt)?localStorage.removeItem(tt):(this.cachedVisitor=t,this.log("Loaded cached visitor from storage"));}catch{}}saveToStorage(){if(!(typeof window>"u"||typeof localStorage>"u")&&this.cachedVisitor)try{localStorage.setItem(tt,JSON.stringify(this.cachedVisitor));}catch{}}isCacheExpiredAt(e){return Date.now()-e>dn}getCookieVisitorId(){if(!(typeof document>"u"))try{return document.cookie.match(new RegExp(`(?:^|; )${pn}=([^;]*)`))?.[1]||void 0}catch{return}}setCookieVisitorId(e){if(!(typeof document>"u"))try{document.cookie=`${pn}=${e}; path=/; max-age=${ii}; SameSite=Lax`;}catch{}}log(...e){this.config.debug&&console.log("[SitePong Fingerprint]",...e);}};var it;var wn=-1,$=function(r){addEventListener("pageshow",(function(e){e.persisted&&(wn=e.timeStamp,r(e));}),true);},ot=function(){var r=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},Ee=function(){var r=ot();return r&&r.activationStart||0},C=function(r,e){var t=ot(),n="navigate";return wn>=0?n="back-forward-cache":t&&(document.prerendering||Ee()>0?n="prerender":document.wasDiscarded?n="restore":t.type&&(n=t.type.replace(/_/g,"-"))),{name:r,value:e===void 0?-1:e,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:n}},re=function(r,e,t){try{if(PerformanceObserver.supportedEntryTypes.includes(r)){var n=new PerformanceObserver((function(i){Promise.resolve().then((function(){e(i.getEntries());}));}));return n.observe(Object.assign({type:r,buffered:!0},t||{})),n}}catch{}},M=function(r,e,t,n){var i,o;return function(s){e.value>=0&&(s||n)&&((o=e.value-(i||0))||i===void 0)&&(i=e.value,e.delta=o,e.rating=(function(a,c){return a>c[1]?"poor":a>c[0]?"needs-improvement":"good"})(e.value,t),r(e));}},st=function(r){requestAnimationFrame((function(){return requestAnimationFrame((function(){return r()}))}));},Ce=function(r){document.addEventListener("visibilitychange",(function(){document.visibilityState==="hidden"&&r();}));},at=function(r){var e=false;return function(){e||(r(),e=true);}},B=-1,fn=function(){return document.visibilityState!=="hidden"||document.prerendering?1/0:0},xe=function(r){document.visibilityState==="hidden"&&B>-1&&(B=r.type==="visibilitychange"?r.timeStamp:0,oi());},hn=function(){addEventListener("visibilitychange",xe,true),addEventListener("prerenderingchange",xe,true);},oi=function(){removeEventListener("visibilitychange",xe,true),removeEventListener("prerenderingchange",xe,true);},Sn=function(){return B<0&&(B=fn(),hn(),$((function(){setTimeout((function(){B=fn(),hn();}),0);}))),{get firstHiddenTime(){return B}}},Me=function(r){document.prerendering?addEventListener("prerenderingchange",(function(){return r()}),true):r();},gn=[1800,3e3],ct=function(r,e){e=e||{},Me((function(){var t,n=Sn(),i=C("FCP"),o=re("paint",(function(s){s.forEach((function(a){a.name==="first-contentful-paint"&&(o.disconnect(),a.startTime<n.firstHiddenTime&&(i.value=Math.max(a.startTime-Ee(),0),i.entries.push(a),t(true)));}));}));o&&(t=M(r,i,gn,e.reportAllChanges),$((function(s){i=C("FCP"),t=M(r,i,gn,e.reportAllChanges),st((function(){i.value=performance.now()-s.timeStamp,t(true);}));})));}));},mn=[.1,.25],Tn=function(r,e){e=e||{},ct(at((function(){var t,n=C("CLS",0),i=0,o=[],s=function(c){c.forEach((function(u){if(!u.hadRecentInput){var p=o[0],h=o[o.length-1];i&&u.startTime-h.startTime<1e3&&u.startTime-p.startTime<5e3?(i+=u.value,o.push(u)):(i=u.value,o=[u]);}})),i>n.value&&(n.value=i,n.entries=o,t());},a=re("layout-shift",s);a&&(t=M(r,n,mn,e.reportAllChanges),Ce((function(){s(a.takeRecords()),t(true);})),$((function(){i=0,n=C("CLS",0),t=M(r,n,mn,e.reportAllChanges),st((function(){return t()}));})),setTimeout(t,0));})));},kn=0,nt=1/0,Te=0,si=function(r){r.forEach((function(e){e.interactionId&&(nt=Math.min(nt,e.interactionId),Te=Math.max(Te,e.interactionId),kn=Te?(Te-nt)/7+1:0);}));},xn=function(){return it?kn:performance.interactionCount||0},ai=function(){"interactionCount"in performance||it||(it=re("event",si,{type:"event",buffered:true,durationThreshold:0}));},E=[],ke=new Map,En=0,ci=function(){var r=Math.min(E.length-1,Math.floor((xn()-En)/50));return E[r]},li=[],ui=function(r){if(li.forEach((function(i){return i(r)})),r.interactionId||r.entryType==="first-input"){var e=E[E.length-1],t=ke.get(r.interactionId);if(t||E.length<10||r.duration>e.latency){if(t)r.duration>t.latency?(t.entries=[r],t.latency=r.duration):r.duration===t.latency&&r.startTime===t.entries[0].startTime&&t.entries.push(r);else {var n={id:r.interactionId,latency:r.duration,entries:[r]};ke.set(n.id,n),E.push(n);}E.sort((function(i,o){return o.latency-i.latency})),E.length>10&&E.splice(10).forEach((function(i){return ke.delete(i.id)}));}}},Cn=function(r){var e=self.requestIdleCallback||self.setTimeout,t=-1;return r=at(r),document.visibilityState==="hidden"?r():(t=e(r),Ce(r)),t},vn=[200,500],Mn=function(r,e){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(e=e||{},Me((function(){var t;ai();var n,i=C("INP"),o=function(a){Cn((function(){a.forEach(ui);var c=ci();c&&c.latency!==i.value&&(i.value=c.latency,i.entries=c.entries,n());}));},s=re("event",o,{durationThreshold:(t=e.durationThreshold)!==null&&t!==void 0?t:40});n=M(r,i,vn,e.reportAllChanges),s&&(s.observe({type:"first-input",buffered:true}),Ce((function(){o(s.takeRecords()),n(true);})),$((function(){En=xn(),E.length=0,ke.clear(),i=C("INP"),n=M(r,i,vn,e.reportAllChanges);})));})));},yn=[2500,4e3],rt={},Rn=function(r,e){e=e||{},Me((function(){var t,n=Sn(),i=C("LCP"),o=function(c){e.reportAllChanges||(c=c.slice(-1)),c.forEach((function(u){u.startTime<n.firstHiddenTime&&(i.value=Math.max(u.startTime-Ee(),0),i.entries=[u],t());}));},s=re("largest-contentful-paint",o);if(s){t=M(r,i,yn,e.reportAllChanges);var a=at((function(){rt[i.id]||(o(s.takeRecords()),s.disconnect(),rt[i.id]=true,t(true));}));["keydown","click"].forEach((function(c){addEventListener(c,(function(){return Cn(a)}),{once:true,capture:true});})),Ce(a),$((function(c){i=C("LCP"),t=M(r,i,yn,e.reportAllChanges),st((function(){i.value=performance.now()-c.timeStamp,rt[i.id]=true,t(true);}));}));}}));},bn=[800,1800],di=function r(e){document.prerendering?Me((function(){return r(e)})):document.readyState!=="complete"?addEventListener("load",(function(){return r(e)}),true):setTimeout(e,0);},In=function(r,e){e=e||{};var t=C("TTFB"),n=M(r,t,bn,e.reportAllChanges);di((function(){var i=ot();i&&(t.value=Math.max(i.responseStart-Ee(),0),t.entries=[i],n(true),$((function(){t=C("TTFB",0),(n=M(r,t,bn,e.reportAllChanges))(true);})));}));};var pi="https://ingest.sitepong.com",fi=1e4,lt=3,hi=200,Pn=200,Ln=3e4;function gi(r){let e=[],t=document.getElementsByTagName("*"),n=/url\(("[^"]*"|'[^']*'|[^)]*)\)/i;for(let i=0;i<t.length;i++){let o=t[i],s="";if(o.tagName==="IMG"&&(s=o.currentSrc||o.src),!s){let g=getComputedStyle(o).getPropertyValue("background-image");if(g){let m=n.exec(g);m!==null&&(s=m[1],(s.startsWith('"')||s.startsWith("'"))&&(s=s.substr(1,s.length-2)));}}if(!s)continue;let a=s.substr(0,10)==="data:image"?0:r[s];if(a===void 0)continue;let c=o.getBoundingClientRect(),u=Math.max(c.top,0),p=Math.max(c.left,0),h=Math.min(c.bottom,window.innerHeight||document.documentElement&&document.documentElement.clientHeight||0),d=Math.min(c.right,window.innerWidth||document.documentElement&&document.documentElement.clientWidth||0);if(h<=u||d<=p)continue;let f=(h-u)*(d-p);e.push({time:a,area:f});}return e}function mi(r,e){let t=Math.max(document.documentElement&&document.documentElement.clientWidth||0,window.innerWidth||0)*Math.max(document.documentElement&&document.documentElement.clientHeight||0,window.innerHeight||0)/10,n=t*r;for(let i=0;i<e.length;i++){let{time:o,area:s}=e[i];t+=s,n+=s*(o>r?o:r);}return t===0?0:n/t}var ie=class{constructor(e){this.metrics=[];this.flushTimer=null;this.flushFailures=0;this.disabled=false;this.vitals={};this.activeTransactions=new Map;this.resourceObserver=null;this.resourceTimeMap={};this.resourceCount=0;this.pageLoadTimer=null;this.pageRenderTimer=null;this.config={endpoint:pi,enabled:true,webVitals:true,navigationTiming:true,resourceTiming:true,capturePageLoadTimings:true,capturePageRenderTimings:true,excludedResourceUrls:[],flushInterval:fi,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!==false&&this.initWebVitals(),this.config.resourceTiming!==false&&this.initResourceTiming(),this.config.capturePageLoadTimings!==false&&this.initPageLoadTiming(),this.config.capturePageRenderTimings!==false&&this.initPageRenderTiming(),this.startFlushTimer(),this.log("Performance monitoring initialized"));}initWebVitals(){Tn(e=>{this.vitals.cls=e.value,this.reportVital("CLS",e.value,"score");}),Mn(e=>{this.vitals.inp=e.value,this.reportVital("INP",e.value);}),Rn(e=>{this.vitals.lcp=e.value,this.reportVital("LCP",e.value);}),In(e=>{this.vitals.ttfb=e.value,this.reportVital("TTFB",e.value);}),ct(e=>{this.vitals.fcp=e.value,this.reportVital("FCP",e.value);});}initResourceTiming(){if(!(typeof PerformanceObserver>"u"))try{this.resourceObserver=new PerformanceObserver(e=>{for(let t of e.getEntries())this.processResourceEntry(t);}),this.resourceObserver.observe({type:"resource",buffered:!0});}catch{this.log("PerformanceObserver for resource timing not supported");}}isServiceURL(e){let t=this.config.performanceEndpoint||this.config.endpoint;return e.startsWith(t)}processResourceEntry(e){if(e.duration<0||!e.name.startsWith("http")||this.isServiceURL(e.name))return;this.resourceTimeMap!==null&&(this.resourceTimeMap[e.name]=e.startTime+e.duration);for(let c of this.config.excludedResourceUrls)if(e.name.startsWith(c))return;if(this.resourceCount>=hi)return;this.resourceCount++;let t=0;e.connectEnd&&e.connectEnd>e.domainLookupEnd?t=Math.max(0,e.requestStart-e.connectEnd):t=Math.max(0,e.requestStart-e.domainLookupEnd);let n=e.responseStatus&&e.responseStatus===304||e.deliveryType&&e.deliveryType==="cache"||e.transferSize===0&&e.decodedBodySize>0,i=e.responseStatus||0,o=i>=400,s={queueing:e.requestStart-e.fetchStart,dnsLookup:e.domainLookupEnd-e.domainLookupStart,initialConnection:e.connectEnd-e.connectStart,ssl:e.secureConnectionStart>0?e.connectEnd-e.secureConnectionStart:0,ttfb:e.responseStart-e.requestStart,contentDownload:e.responseEnd-e.responseStart,total:e.duration??e.responseEnd-e.startTime,stalled:t,cached:n,failed:o,responseStatus:i,headerSize:e.transferSize>e.encodedBodySize?e.transferSize-e.encodedBodySize:0,encodedBodySize:e.encodedBodySize||0,decodedBodySize:o?-111:e.decodedBodySize||0,transferSize:e.transferSize,initiatorType:e.initiatorType},a=this.config.resourceNameSanitizer?this.config.resourceNameSanitizer(e.name):e.name;this.addMetric({type:"resource",name:a,value:e.duration,unit:"ms",timestamp:new Date().toISOString(),url:typeof window<"u"&&window.location?window.location.href:void 0,data:s});}initPageLoadTiming(){if(typeof window>"u"||!window.performance)return;let e=0,t=0,n=false,i=performance.now();this.pageLoadTimer=setInterval(()=>{if(n){this.pageLoadTimer&&clearInterval(this.pageLoadTimer);return}if(e===0||t===0)for(let a of performance.getEntriesByType("paint"))a.name==="first-paint"&&(e=a.startTime),a.name==="first-contentful-paint"&&(t=a.startTime);let o=performance.getEntriesByType("navigation")[0],s=performance.now()-i>Ln;if((o&&o.loadEventEnd>0||s)&&(n=true,this.pageLoadTimer&&clearInterval(this.pageLoadTimer),o)){let a=o.startTime;this.addMetric({type:"navigation",name:"page_load",value:o.loadEventEnd-a,unit:"ms",timestamp:new Date().toISOString(),url:window.location.href,data:{requestStart:o.requestStart-a,responseStart:o.responseStart-a,responseEnd:o.responseEnd-a,domContentLoadedEventStart:o.domContentLoadedEventEnd-a,domContentLoadedEventEnd:o.domContentLoadedEventEnd-a,loadEventStart:o.loadEventStart-a,loadEventEnd:o.loadEventEnd-a,firstPaint:e,firstContentfulPaint:t,dns:o.domainLookupEnd-o.domainLookupStart,tcp:o.connectEnd-o.connectStart,ttfb:o.responseStart-o.requestStart,domComplete:o.domComplete-a,transferSize:o.transferSize,encodedBodySize:o.encodedBodySize,decodedBodySize:o.decodedBodySize}});}},Pn);}initPageRenderTiming(){if(typeof window>"u"||!window.performance)return;let e=0,t=0,n=0,i=0,o=null,s=false,a=performance.now();this.pageRenderTimer=setInterval(()=>{if(s){this.pageRenderTimer&&clearInterval(this.pageRenderTimer);return}let c=performance.now();if(e===0)for(let p of performance.getEntriesByType("paint"))p.name==="first-contentful-paint"&&(e=p.startTime);if(this.resourceTimeMap!==null){let p=Object.values(this.resourceTimeMap);p.length>0&&(t=Math.max(...p)),c-t>1e3&&(o=gi(this.resourceTimeMap),this.resourceTimeMap=null);}i!==null&&(c-i>50&&(n=c),i=c-n>5e3?null:c);let u=c-a>Ln;if(o!==null&&i===null||u){s=true,this.pageRenderTimer&&clearInterval(this.pageRenderTimer),this.resourceTimeMap=null;let p=o===null?0:mi(e||0,o),h=performance.getEntriesByType("navigation")[0],d=h?h.domContentLoadedEventEnd-h.startTime:0,f=i===null?Math.max(n,e,d):0,g=window.location.href,m=new Date().toISOString();p>0&&this.addMetric({type:"page_render",name:"speed_index",value:Math.round(p),unit:"ms",timestamp:m,url:g}),t>0&&this.addMetric({type:"page_render",name:"visually_complete",value:Math.round(t),unit:"ms",timestamp:m,url:g}),f>0&&this.addMetric({type:"page_render",name:"tti",value:Math.round(f),unit:"ms",timestamp:m,url:g});}},Pn);}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?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.pageLoadTimer&&(clearInterval(this.pageLoadTimer),this.pageLoadTimer=null),this.pageRenderTimer&&(clearInterval(this.pageRenderTimer),this.pageRenderTimer=null),this.resourceObserver&&(this.resourceObserver.disconnect(),this.resourceObserver=null),this.flush();}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?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=[],this.resourceCount=0;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>=lt){this.disabled=true,console.warn(`[SitePong Performance] Disabled after ${lt} 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}/${lt}):`,n);}}log(...e){this.config.debug&&console.log("[SitePong Performance]",...e);}};function _n(r){let e=r?.trim().toLowerCase();return e&&e.length>0?e:void 0}function Dn(r,e){return _n(r)??e}function Fn(r,e){return (e??["development"]).map(n=>_n(n)).filter(n=>n!==void 0).includes(r)}var ut=9,An=8;function vi(r,e,t){return Math.round(.299*r+.587*e+.114*t)}function yi(r,e,t){let n=new Float64Array(e*t);for(let i=0;i<e*t;i++){let o=i*4;n[i]=vi(r[o],r[o+1],r[o+2]);}return n}function bi(r,e,t,n,i){let o=new Float64Array(n*i),s=e/n,a=t/i;for(let c=0;c<i;c++){let u=(c+.5)*a-.5;u<0&&(u=0),u>t-1&&(u=t-1);let p=Math.floor(u),h=Math.min(p+1,t-1),d=u-p;for(let f=0;f<n;f++){let g=(f+.5)*s-.5;g<0&&(g=0),g>e-1&&(g=e-1);let m=Math.floor(g),b=Math.min(m+1,e-1),w=g-m,se=r[p*e+m],Ie=r[p*e+b],ae=r[h*e+m],Wn=r[h*e+b],wt=se+(Ie-se)*w,qn=ae+(Wn-ae)*w;o[c*n+f]=wt+(qn-wt)*d;}}return o}function Nn(r,e,t){if(e<=0||t<=0)throw new Error(`dHash: invalid dimensions ${e}x${t}`);if(r.length<e*t*4)throw new Error(`dHash: rgba length ${r.length} too short for ${e}x${t} (need ${e*t*4})`);let n=yi(r,e,t),i=bi(n,e,t,ut,An),o=new Uint8Array(8);for(let a=0;a<An;a++){let c=0;for(let u=0;u<8;u++){let p=i[a*ut+u],h=i[a*ut+u+1],d=p<h?1:0;c|=d<<7-u;}o[a]=c;}let s="";for(let a=0;a<8;a++)s+=o[a].toString(16).padStart(2,"0");return s}function wi(r){let e=0;for(;r;)r&=r-1,e++;return e}function On(r,e){if(r.length!==e.length)throw new Error(`hamming: length mismatch (${r.length} vs ${e.length})`);if(r.length%2!==0)throw new Error(`hamming: hex string length must be even, got ${r.length}`);let t=0;for(let n=0;n<r.length;n+=2){let i=parseInt(r.slice(n,n+2),16),o=parseInt(e.slice(n,n+2),16);if(Number.isNaN(i)||Number.isNaN(o))throw new Error(`hamming: invalid hex at offset ${n}`);t+=wi(i^o);}return t}var Hn=10;function oe(r,e){return `${r}:${e}`}function Un(r){let e=r.lastIndexOf(":");if(e<0)throw new Error(`parseFingerprint: missing ':' in "${r}"`);return {screenName:r.slice(0,e),pHashHex:r.slice(e+1)}}var dt="0000000000000000",Si=50,Ti=1e4,ki=1e3,pt=3,Kn=480,Bn="img, picture, video, canvas, iframe, [data-sp-mask]",$n="sitepong_wt_session_id",ft="sitepong_wt_seq",zn="sitepong_wt_started_at",ht="sitepong_wt_start_sent";function xi(){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 vt=class{constructor(){this.memory={};}get(e){try{if(typeof sessionStorage<"u")return sessionStorage.getItem(e)}catch{}return this.memory[e]??null}set(e,t){try{if(typeof sessionStorage<"u"){sessionStorage.setItem(e,t);return}}catch{}this.memory[e]=t;}get sessionId(){let e=this.get($n);return e||(e=xi(),this.set($n,e),this.set(zn,String(Date.now())),this.set(ft,"0"),this.set(ht,"0")),e}get startedAt(){let e=this.get(zn),t=e?parseInt(e,10):NaN;return Number.isFinite(t)?t:Date.now()}get startSent(){return this.get(ht)==="1"}markStartSent(){this.set(ht,"1");}nextSequence(){let e=this.get(ft),t=e?parseInt(e,10):0,n=(Number.isFinite(t)?t:0)+1;return this.set(ft,String(n)),n}},Ei=async(r,e,t)=>{let n=await fetch(r,{method:"POST",headers:t.headers,body:e,keepalive:t.keepalive});return {ok:n.ok,status:n.status}},Re=class{constructor(e){this.session=new vt;this.queue=[];this.flushTimer=null;this.flushFailures=0;this.disabled=false;this.channel="production";this.channelSuppressed=false;this.active=false;this.distinctId=null;this.currentScreen=null;this.detachAutocapture=null;this.ownAutocapture=null;this.originalPushState=null;this.originalReplaceState=null;this.popstateHandler=null;this.pagehideHandler=null;this.fpCache=new Map;this.uploadedFps=new Set;this.lastRasterAt=new Map;this.rasterInFlight=false;this.config={...e},this.transport=e.transport||Ei,this.rasterizer=e.rasterizer||null,this.channel=Dn(e.channel,"production"),this.channelSuppressed=Fn(this.channel,e.ignoreChannels);}start(e){if(this.active||typeof window>"u")return;if(this.channelSuppressed){this.log("Suppressed channel",this.channel,"\u2014 not capturing");return}this.active=true,this.rasterizer||(this.rasterizer=new bt({blockSelector:this.combinedBlockSelector(),maskSelector:this.config.maskSelector,maxWidth:Kn}));let t=this.session.sessionId;if(this.session.startSent||(this.enqueue(this.baseEvent("session_start")),this.session.markStartSent()),this.log("Started (session",t+")"),this.currentScreen=this.pathname(),this.currentScreen!==null){let n=this.baseEvent("screen_view");n.screen_name=this.currentScreen,this.enqueue(n),this.scheduleFingerprint(this.currentScreen);}this.setupNavigationTracking(),this.setupPagehide(),this.startFlushTimer(),e?this.detachAutocapture=e.addListener(n=>this.onAutocaptureEvent(n)):(this.ownAutocapture=new P({clicks:true,forms:false,pageviews:false,debug:this.config.debug},n=>this.onAutocaptureEvent(n)),this.ownAutocapture.start());}stop(){this.active&&(this.active=false,this.detachAutocapture&&(this.detachAutocapture(),this.detachAutocapture=null),this.ownAutocapture&&(this.ownAutocapture.stop(),this.ownAutocapture=null),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),typeof window<"u"&&(this.popstateHandler&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),this.pagehideHandler&&(window.removeEventListener("pagehide",this.pagehideHandler),this.pagehideHandler=null),this.originalPushState&&(window.history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(window.history.replaceState=this.originalReplaceState,this.originalReplaceState=null)),this.flush(),this.log("Stopped"));}isActive(){return this.active}getSessionId(){return this.session.sessionId}setDistinctId(e){this.distinctId=e;}onAutocaptureEvent(e){if(!this.active||e.type!=="click")return;let t=e.properties,n=typeof t.$x=="number"?t.$x:null,i=typeof t.$y=="number"?t.$y:null;n===null||i===null||this.recordTap({selector:typeof t.$selector=="string"?t.$selector:"",label:typeof t.$el_text=="string"&&t.$el_text||typeof t.$aria_label=="string"&&t.$aria_label||void 0,role:typeof t.$el_role=="string"&&t.$el_role||Ci(typeof t.$tag_name=="string"?t.$tag_name:void 0),clientX:n,clientY:i});}recordTap(e){if(!this.active||typeof window>"u")return;let t=window.innerWidth||1,n=window.innerHeight||1,i=this.pathname()??"/",o=this.baseEvent("tap");o.screen_name=i,o.screen_fp=this.fpCache.get(i)??oe(i,dt),o.element_id=e.selector||"unknown",e.label&&(o.element_label=e.label),e.role&&(o.element_role=e.role),o.x=Vn(e.clientX/t),o.y=Vn(e.clientY/n),o.viewport_w=t,o.viewport_h=n,this.enqueue(o),this.scheduleFingerprint(i);}setupNavigationTracking(){if(typeof window>"u"||!window.history||typeof window.addEventListener!="function")return;let e=()=>this.handleRouteChange();this.popstateHandler=e,window.addEventListener("popstate",this.popstateHandler);let t=window.history.pushState.bind(window.history),n=window.history.replaceState.bind(window.history);this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState,window.history.pushState=(...i)=>{t(...i),e();},window.history.replaceState=(...i)=>{n(...i),e();};}handleRouteChange(){if(!this.active)return;let e=this.pathname();if(e===null||e===this.currentScreen)return;let t=this.currentScreen;this.currentScreen=e;let n=this.baseEvent("screen_view");n.screen_name=e,t&&(n.prev_screen_name=t),this.enqueue(n),this.scheduleFingerprint(e);}setupPagehide(){typeof window>"u"||typeof window.addEventListener!="function"||(this.pagehideHandler=()=>{if(!this.active)return;let e=this.baseEvent("session_end");e.reason="background",e.duration_ms=Math.max(0,Date.now()-this.session.startedAt),this.enqueue(e),this.flush({keepalive:true});},window.addEventListener("pagehide",this.pagehideHandler));}baseEvent(e){return {type:e,session_id:this.session.sessionId,sequence:this.session.nextSequence(),timestamp:new Date().toISOString(),platform:"web",app_version:this.config.appVersion||void 0,distinct_id:this.distinctId||void 0,os_version:typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:void 0,channel:this.channel}}enqueue(e){this.disabled||(this.queue.push(e),this.queue.length>=(this.config.maxBatchSize??Si)&&this.flush());}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval??Ti);}async flush(e){if(this.queue.length===0)return;if(this.disabled){this.queue=[];return}let t=this.queue;this.queue=[];try{let n=await this.transport(`${this.config.endpoint}/api/taps`,JSON.stringify({events:t}),{headers:this.headers(),keepalive:e?.keepalive});if(!n.ok)throw new Error(`HTTP ${n.status}`);this.flushFailures=0,this.log(`Flushed ${t.length} events`);}catch(n){if(this.flushFailures++,this.flushFailures>=pt){this.disabled=true,this.queue=[],this.log(`Disabled after ${pt} consecutive flush failures`);return}this.queue.unshift(...t),this.log(`Flush failed (attempt ${this.flushFailures}/${pt}):`,n);}}headers(){return {"Content-Type":"application/json","X-Project-ID":this.config.projectId,"X-API-Key":this.config.apiKey}}scheduleFingerprint(e){if(!this.active||this.disabled||!this.rasterizer)return;let t=Date.now(),n=this.lastRasterAt.get(e)??0,i=this.config.templateThrottleMs??ki;t-n<i||this.rasterInFlight||(this.lastRasterAt.set(e,t),Mi(()=>{this.captureFingerprint(e);}));}async captureFingerprint(e){if(!(!this.active||this.rasterInFlight||!this.rasterizer)){this.rasterInFlight=true;try{let t=await this.rasterizer.rasterize();if(!t){this.fpCache.has(e)||this.fpCache.set(e,oe(e,dt));return}let n=Nn(t.rgba,t.width,t.height),i=oe(e,n);this.fpCache.set(e,i),await this.maybeUploadTemplate(e,n,i,t);}catch(t){this.log("Fingerprint capture failed:",t),this.fpCache.has(e)||this.fpCache.set(e,oe(e,dt));}finally{this.rasterInFlight=false;}}}async maybeUploadTemplate(e,t,n,i){for(let o of this.uploadedFps){let s=Un(o);if(s.screenName===e&&On(s.pHashHex,t)<=Hn)return}if(i.pngBase64)try{(await this.transport(`${this.config.endpoint}/api/taps/template`,JSON.stringify({route_name:e,p_hash:t,width:i.width,height:i.height,image_base64:i.pngBase64}),{headers:this.headers()})).ok&&(this.uploadedFps.add(n),this.log("Uploaded template for",n));}catch(o){this.log("Template upload failed:",o);}}combinedBlockSelector(){return this.config.blockSelector?`${Bn}, ${this.config.blockSelector}`:Bn}pathname(){return typeof window>"u"||!window.location?null:window.location.pathname||"/"}log(...e){this.config.debug&&console.log("[SitePong Watchtower]",...e);}};function Vn(r){return Number.isFinite(r)?Math.min(1,Math.max(0,r)):0}function Ci(r){switch(r){case "a":return "link";case "button":return "button";case "input":return "input";case "select":return "select";case "textarea":return "textarea";default:return r||void 0}}function Mi(r){let e=globalThis;typeof e.requestIdleCallback=="function"?e.requestIdleCallback(r,{timeout:2e3}):setTimeout(r,250);}var Ri=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function gt(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function mt(r){return r.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g,"")}function yt(r,e=false){if(r.type==="text")return gt(mt(r.textContent??""));if(r.type==="comment")return "";let t=(r.tagName||"div").toLowerCase(),n={...r.attributes||{}},i=n._cssText;if(t==="style"||t==="link"){if(typeof i=="string"&&i)return `<style>${gt(mt(i))}</style>`;if(t==="link")return ""}let o=n._computedStyle;typeof o=="string"&&o&&(n.style=n.style?`${n.style};${o}`:o);let s=n._value;typeof s=="string"&&s&&(n.value=s),n._checked==="true"&&(n.checked="checked");let a="";for(let[u,p]of Object.entries(n))u.startsWith("_")||u.startsWith("on")||/^[a-zA-Z_][\w:.-]*$/.test(u)&&(a+=` ${u}="${gt(mt(String(p)))}"`);if(e&&(a=` xmlns="http://www.w3.org/1999/xhtml"${a}`),Ri.has(t))return `<${t}${a}/>`;let c="";if(t==="style"&&typeof i!="string")for(let u of r.children||[])c+=yt(u);else for(let u of r.children||[])c+=yt(u);return `<${t}${a}>${c}</${t}>`}var bt=class{constructor(e){this.options=e;}async rasterize(){try{if(typeof document>"u"||typeof window>"u")return null;Xe();let e=H(document.documentElement,{maskInputs:!0,blockSelector:this.options.blockSelector,maskSelector:this.options.maskSelector});if(!e)return null;let t=window.innerWidth||1,n=window.innerHeight||1,i=yt(e,!0),o=`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}"><foreignObject width="100%" height="100%">${i}</foreignObject></svg>`,s=await Ii(o),a=Math.min(1,(this.options.maxWidth??Kn)/t),c=Math.max(1,Math.round(t*a)),u=Math.max(1,Math.round(n*a)),p=document.createElement("canvas");p.width=c,p.height=u;let h=p.getContext("2d");if(!h)return null;h.fillStyle="#ffffff",h.fillRect(0,0,c,u),h.drawImage(s,0,0,c,u);let d=h.getImageData(0,0,c,u),f=new Uint8Array(d.data.buffer,d.data.byteOffset,d.data.byteLength),g=null;try{let m=p.toDataURL("image/png"),b="data:image/png;base64,";g=m.startsWith(b)?m.slice(b.length):null;}catch{g=null;}return {rgba:f,width:c,height:u,pngBase64:g}}catch{return null}}};function Ii(r){return new Promise((e,t)=>{let n=new Blob([r],{type:"image/svg+xml;charset=utf-8"}),i=URL.createObjectURL(n),o=new Image,s=setTimeout(()=>{URL.revokeObjectURL(i),t(new Error("SVG rasterization timed out"));},3e3);o.onload=()=>{clearTimeout(s),URL.revokeObjectURL(i),e(o);},o.onerror=()=>{clearTimeout(s),URL.revokeObjectURL(i),t(new Error("SVG rasterization failed"));},o.src=i;})}z(St());Yt({createReplay:r=>new ee(r),createFingerprint:r=>new ne(r),createPerformance:r=>new ie(r),createWatchtowerCapture:r=>new Re(r)});
|
|
8
|
+
exports.DEFAULT_SUPERLINK_ENDPOINT=ze;exports.SuperLinkClient=X;exports.TracePropagator=he;exports.addBreadcrumb=ts;exports.areFlagsReady=cs;exports.captureError=jo;exports.captureMessage=Go;exports.captureWebDeepLink=Q;exports.clearAnonymousId=Tt;exports.clearUser=es;exports.client=l;exports.completeFromScan=Qt;exports.createTraceContext=$e;exports.cronCheckin=Fs;exports.cronStart=As;exports.cronWrap=Ns;exports.dbTrack=Is;exports.dbTrackSync=Ps;exports.default=br;exports.endSpan=Ms;exports.endTransaction=Es;exports.extractIdentityMetadata=qt;exports.extractTrace=Bt;exports.flush=Jo;exports.flushMetrics=Vs;exports.flushProfiles=Gs;exports.generateSpanId=ge;exports.generateTraceId=Be;exports.getAllFlags=is;exports.getAnonymousId=D;exports.getDbNPlusOnePatterns=Ds;exports.getDbQueryCount=Ls;exports.getDeepLink=jt;exports.getDeviceSignals=ms;exports.getFlag=rs;exports.getFraudCheck=vs;exports.getLatestProfile=js;exports.getMatchedDeepLink=Vt;exports.getProfiles=qs;exports.getRemoteConfig=Xs;exports.getReplaySessionId=ks;exports.getVariant=os;exports.getVariantPayload=ss;exports.getVisitorId=gs;exports.getWebVitals=Rs;exports.group=fs;exports.identify=ps;exports.init=Wo;exports.initRN=qo;exports.initSuperLink=gr;exports.isInitialized=Zo;exports.isRemoteConfigFeatureEnabled=Qs;exports.isReplayRecording=Ts;exports.metricDistribution=Bs;exports.metricGauge=Hs;exports.metricHistogram=Us;exports.metricIncrement=Os;exports.metricStartTimer=zs;exports.metricTime=$s;exports.onDeferredDeepLink=zt;exports.onRemoteConfigChange=Ys;exports.parseUniversalLink=me;exports.profile=Ks;exports.propagateTrace=fe;exports.refreshFlags=ls;exports.registerIdentifyHook=Js;exports.registerWebManagerFactories=Yt;exports.resetAnalytics=hs;exports.resetDbQueryCount=_s;exports.setAnonymousId=kt;exports.setContext=Xo;exports.setCurrentScreen=ns;exports.setEnvironment=z;exports.setRNGetCurrentScreen=Le;exports.setTags=Yo;exports.setUser=Qo;exports.startProfileSpan=Ws;exports.startReplay=ys;exports.startSpan=Cs;exports.startTransaction=xs;exports.startWatchtowerCapture=ws;exports.stopReplay=bs;exports.stopWatchtowerCapture=Ss;exports.superlinkClient=T;exports.superlinkIdentify=Xt;exports.track=us;exports.trackPageView=ds;exports.waitForFlags=as;exports.writeClipboardToken=Wt;Object.defineProperty(exports,'__esModule',{value:true});return exports;})({});//# sourceMappingURL=sitepong.min.js.map
|
|
9
9
|
//# sourceMappingURL=sitepong.min.js.map
|