@simplr-ai/web-components 1.0.0

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.
@@ -0,0 +1,6 @@
1
+ var SimplrWebComponents=(function(exports){'use strict';async function re(e){let t=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")}function g(e,t=0){let i=t,r=3432918353,n=461845907;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);o=Math.imul(o,r),o=o<<15|o>>>17,o=Math.imul(o,n),i^=o,i=i<<13|i>>>19,i=Math.imul(i,5)+3864292196;}return i^=e.length,i^=i>>>16,i=Math.imul(i,2246822507),i^=i>>>13,i=Math.imul(i,3266489909),i^=i>>>16,i>>>0}async function ne(e){let t=Object.keys(e).sort().map(i=>{let r=e[i];return `${i}:${r??"null"}`});return re(t.join("|"))}function me(){try{let e=document.createElement("canvas");e.width=280,e.height=60;let t=e.getContext("2d");if(!t)return {hash:"",isSupported:!1};t.fillStyle="#f0f0f0",t.fillRect(0,0,e.width,e.height),t.textBaseline="alphabetic",t.fillStyle="#069",t.font="15px 'Arial', sans-serif",t.fillText("Simplr Fraud SDK",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.font="18px 'Times New Roman', serif",t.fillText("Canvas Fingerprint",4,35),t.beginPath(),t.arc(50,50,10,0,Math.PI*2),t.fillStyle="#f00",t.fill(),t.beginPath(),t.moveTo(80,40),t.lineTo(100,55),t.lineTo(80,55),t.closePath(),t.fillStyle="#0f0",t.fill();let i=t.createLinearGradient(0,0,e.width,0);i.addColorStop(0,"red"),i.addColorStop(.5,"green"),i.addColorStop(1,"blue"),t.fillStyle=i,t.fillRect(120,40,80,15);let r=e.toDataURL("image/png");return {hash:g(r).toString(16),isSupported:!0}}catch{return {hash:"",isSupported:false}}}function fe(){try{let e=document.createElement("canvas");e.width=16,e.height=16;let t=e.getContext("2d");if(!t)return !0;t.fillStyle="#ff0000",t.fillRect(0,0,8,8),t.fillStyle="#00ff00",t.fillRect(8,0,8,8);let i=t.getImageData(0,0,16,16).data,r=[i[0],i[1],i[2],i[3]],n=!0;for(let s=4;s<i.length;s+=4)if(i[s]!==r[0]||i[s+1]!==r[1]||i[s+2]!==r[2]){n=!1;break}return n}catch{return true}}function ve(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return {hash:"",vendor:null,renderer:null,isSupported:!1};let i=t,r=i.getExtension("WEBGL_debug_renderer_info"),n=null,s=null;r&&(n=i.getParameter(r.UNMASKED_VENDOR_WEBGL),s=i.getParameter(r.UNMASKED_RENDERER_WEBGL)),n||(n=i.getParameter(i.VENDOR)),s||(s=i.getParameter(i.RENDERER));let o=[n,s,i.getParameter(i.VERSION),i.getParameter(i.SHADING_LANGUAGE_VERSION),i.getParameter(i.MAX_VERTEX_ATTRIBS),i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),i.getParameter(i.MAX_VARYING_VECTORS),i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS),i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),i.getParameter(i.MAX_TEXTURE_SIZE),i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),i.getParameter(i.MAX_RENDERBUFFER_SIZE),i.getParameter(i.MAX_VIEWPORT_DIMS),i.getParameter(i.ALIASED_LINE_WIDTH_RANGE),i.getParameter(i.ALIASED_POINT_SIZE_RANGE)],a=i.getSupportedExtensions()||[];return o.push(a.join(",")),{hash:g(o.join("|")).toString(16),vendor:n,renderer:s,isSupported:!0}}catch{return {hash:"",vendor:null,renderer:null,isSupported:false}}}async function we(){try{let e=window.AudioContext||window.webkitAudioContext;if(!e)return {hash:"",isSupported:!1};let t=new e,i=t.createOscillator();i.type="triangle",i.frequency.setValueAtTime(1e4,t.currentTime);let r=t.createDynamicsCompressor();r.threshold.setValueAtTime(-50,t.currentTime),r.knee.setValueAtTime(40,t.currentTime),r.ratio.setValueAtTime(12,t.currentTime),r.attack.setValueAtTime(0,t.currentTime),r.release.setValueAtTime(.25,t.currentTime);let n=t.createAnalyser();n.fftSize=256,i.connect(r),r.connect(n),i.start(0),await new Promise(a=>setTimeout(a,50));let s=new Float32Array(n.frequencyBinCount);n.getFloatFrequencyData(s),i.stop(),await t.close();let o=Array.from(s).slice(0,30).map(a=>a.toFixed(2)).join(",");return {hash:g(o).toString(16),isSupported:!0}}catch{return {hash:"",isSupported:false}}}var se=["Arial","Arial Black","Calibri","Cambria","Comic Sans MS","Consolas","Courier New","Georgia","Impact","Lucida Console","Lucida Sans Unicode","Microsoft Sans Serif","Palatino Linotype","Segoe UI","Tahoma","Times New Roman","Trebuchet MS","Verdana","American Typewriter","Andale Mono","Apple Chancery","Avenir","Baskerville","Big Caslon","Brush Script MT","Chalkboard","Copperplate","Didot","Futura","Geneva","Gill Sans","Helvetica","Helvetica Neue","Herculanum","Hoefler Text","Lucida Grande","Marker Felt","Menlo","Monaco","Optima","Papyrus","Rockwell","SF Pro","Skia","Liberation Sans","Liberation Serif","Liberation Mono","DejaVu Sans","DejaVu Serif","DejaVu Sans Mono","Ubuntu","Droid Sans","Droid Serif","Roboto","Noto Sans","Noto Serif","Open Sans","Lato","Montserrat","Source Sans Pro","Oswald","Raleway","PT Sans","Merriweather","Nunito","Playfair Display"],ye=["monospace","sans-serif","serif"],Se="mmmmmmmmmmlli";function Z(e,t){let i=document.createElement("span");i.style.position="absolute",i.style.left="-9999px",i.style.fontSize="72px",i.style.fontStyle="normal",i.style.fontWeight="normal",i.style.letterSpacing="normal",i.style.lineHeight="normal",i.style.textTransform="none",i.style.textAlign="left",i.style.textDecoration="none",i.style.textShadow="none",i.style.whiteSpace="nowrap",i.style.fontFamily=`'${e}', ${t}`,i.textContent=Se,document.body.appendChild(i);let r=i.getBoundingClientRect(),n=r.width,s=r.height;return document.body.removeChild(i),{width:n,height:s}}function ke(e){for(let t of ye){let i=Z(t,t),r=Z(e,t);if(r.width!==i.width||r.height!==i.height)return true}return false}function Q(){try{let e=[];for(let t of se)ke(t)&&e.push(t);return {hash:g(e.join(",")).toString(16),detectedFonts:e,fontCount:e.length}}catch{return {hash:"",detectedFonts:[],fontCount:0}}}async function be(){try{if(!document.fonts)return Q();await document.fonts.ready;let e=[];for(let t of se)document.fonts.check(`12px '${t}'`)&&e.push(t);return {hash:g(e.join(",")).toString(16),detectedFonts:e,fontCount:e.length}}catch{return Q()}}function Te(){let e=window.navigator,t=window.screen,i=[];if(e.plugins)for(let a=0;a<e.plugins.length;a++){let l=e.plugins[a];l?.name&&i.push(l.name);}let r=[];if(e.mimeTypes)for(let a=0;a<e.mimeTypes.length;a++){let l=e.mimeTypes[a];l?.type&&r.push(l.type);}let n=e.deviceMemory??null,s=!!(e.webdriver||window.__webdriver_evaluate||window.__selenium_evaluate||window.__webdriver_script_function||window.__webdriver_script_func||window.__webdriver_script_fn||window.__fxdriver_evaluate||window.__driver_unwrapped||window.__webdriver_unwrapped||window.__driver_evaluate||window.__selenium_unwrapped||window.__fxdriver_unwrapped||window._Selenium_IDE_Recorder||window._selenium||window.calledSelenium||/HeadlessChrome/.test(e.userAgent)||/Headless/.test(e.userAgent)),o="";try{o=Intl.DateTimeFormat().resolvedOptions().timeZone;}catch{}return {userAgent:e.userAgent,platform:e.platform,vendor:e.vendor,language:e.language,languages:[...e.languages],cookiesEnabled:e.cookieEnabled,doNotTrack:e.doNotTrack||null,timezone:o,timezoneOffset:new Date().getTimezoneOffset(),screenResolution:`${t.width}x${t.height}`,screenColorDepth:t.colorDepth,devicePixelRatio:window.devicePixelRatio||1,hardwareConcurrency:e.hardwareConcurrency||0,deviceMemory:n,maxTouchPoints:e.maxTouchPoints||0,hasTouch:"ontouchstart"in window||e.maxTouchPoints>0,isWebDriver:s,plugins:i,mimeTypes:r}}function Ee(){let e=[];return navigator.webdriver&&e.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&e.push("headless_chrome_ua"),navigator.plugins.length===0&&e.push("no_plugins"),(!navigator.languages||navigator.languages.length===0)&&e.push("no_languages"),window.__puppeteer_evaluation_script__&&e.push("puppeteer"),window.callPhantom&&e.push("phantomjs"),(window.outerWidth===0||window.outerHeight===0)&&e.push("zero_dimensions"),/Chrome/.test(navigator.userAgent)&&!window.chrome&&e.push("missing_chrome_object"),{isHeadless:e.length>0,indicators:e}}function Ce(){let e=navigator.userAgent;if(/Windows NT 10.0/.test(e))return {os:"Windows",version:"10"};if(/Windows NT 6.3/.test(e))return {os:"Windows",version:"8.1"};if(/Windows NT 6.2/.test(e))return {os:"Windows",version:"8"};if(/Windows NT 6.1/.test(e))return {os:"Windows",version:"7"};if(/Windows/.test(e))return {os:"Windows",version:null};if(/Mac OS X/.test(e)){let t=e.match(/Mac OS X (\d+[._]\d+)/);return {os:"macOS",version:t?t[1].replace("_","."):null}}if(/Android/.test(e)){let t=e.match(/Android (\d+(\.\d+)?)/);return {os:"Android",version:t?t[1]:null}}if(/iPhone|iPad|iPod/.test(e)){let t=e.match(/OS (\d+[._]\d+)/);return {os:"iOS",version:t?t[1].replace("_","."):null}}return /Linux/.test(e)?{os:"Linux",version:null}:/CrOS/.test(e)?{os:"Chrome OS",version:null}:{os:"Unknown",version:null}}function _e(){let e=navigator.userAgent;if(/Edg\//.test(e)){let t=e.match(/Edg\/(\d+(\.\d+)?)/);return {browser:"Edge",version:t?t[1]:null}}if(/OPR\//.test(e)){let t=e.match(/OPR\/(\d+(\.\d+)?)/);return {browser:"Opera",version:t?t[1]:null}}if(/Chrome\//.test(e)&&!/Chromium/.test(e)){let t=e.match(/Chrome\/(\d+(\.\d+)?)/);return {browser:"Chrome",version:t?t[1]:null}}if(/Firefox\//.test(e)){let t=e.match(/Firefox\/(\d+(\.\d+)?)/);return {browser:"Firefox",version:t?t[1]:null}}if(/Safari\//.test(e)&&!/Chrome/.test(e)){let t=e.match(/Version\/(\d+(\.\d+)?)/);return {browser:"Safari",version:t?t[1]:null}}return {browser:"Unknown",version:null}}var f="simplr_device_id",X="simplr_device_id_ts";function K(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,15),i=Math.random().toString(36).substring(2,15);return `${e}-${t}-${i}`}function $(){if(typeof localStorage<"u")try{let e=localStorage.getItem(f);return e||(e=K(),localStorage.setItem(f,e),localStorage.setItem(X,Date.now().toString())),e}catch{}if(typeof sessionStorage<"u")try{let e=sessionStorage.getItem(f);return e||(e=K(),sessionStorage.setItem(f,e)),e}catch{}return K()}function Ie(){if(typeof localStorage<"u")try{let e=localStorage.getItem(X);if(e)return new Date(parseInt(e,10))}catch{}return null}function Ae(){if(typeof localStorage<"u")try{localStorage.removeItem(f),localStorage.removeItem(X);}catch{}if(typeof sessionStorage<"u")try{sessionStorage.removeItem(f);}catch{}}var Me=class{constructor(){this.keystrokes=[],this.pendingKeydowns=new Map,this.startTime=null,this.pasteCount=0,this.isTracking=false;}start(){this.isTracking||(this.isTracking=true,this.reset());}stop(){this.isTracking=false;}reset(){this.keystrokes=[],this.pendingKeydowns.clear(),this.startTime=null,this.pasteCount=0;}handleKeyDown(e){if(!this.isTracking)return;let t=performance.now();if(this.startTime===null&&(this.startTime=t),["Control","Alt","Shift","Meta"].includes(e.key))return;if((e.ctrlKey||e.metaKey)&&e.key==="v"){this.pasteCount++;return}let i=`${e.code}-${e.key}`;if(this.pendingKeydowns.has(i))return;let r={key:e.key,keyCode:e.keyCode,timestamp:t,keydownTime:t,keyupTime:null,holdDuration:null};this.pendingKeydowns.set(i,r),this.keystrokes.push(r);}handleKeyUp(e){if(!this.isTracking)return;let t=`${e.code}-${e.key}`,i=this.pendingKeydowns.get(t);if(i){let r=performance.now();i.keyupTime=r,i.holdDuration=r-i.keydownTime,this.pendingKeydowns.delete(t);}}getEventHandlers(){return {onKeyDown:this.handleKeyDown.bind(this),onKeyUp:this.handleKeyUp.bind(this),onPaste:()=>{this.isTracking&&this.pasteCount++;}}}getMetrics(){let e=this.keystrokes.length;if(e===0)return {avgInterKeyDelay:0,interKeyDelayStdDev:0,avgHoldDuration:0,holdDurationStdDev:0,typingSpeed:0,correctionRate:0,keystrokeCount:0,correctionCount:0,totalDuration:0,interKeyDelays:[],holdDurations:[],pasteCount:this.pasteCount};let t=[];for(let o=1;o<this.keystrokes.length;o++){let a=this.keystrokes[o].keydownTime-this.keystrokes[o-1].keydownTime;a>0&&a<2e3&&t.push(a);}let i=[];for(let o of this.keystrokes)o.holdDuration!==null&&o.holdDuration>0&&i.push(o.holdDuration);let r=this.keystrokes.filter(o=>o.key==="Backspace"||o.key==="Delete").length,n=e>0?this.keystrokes[e-1].keydownTime-this.keystrokes[0].keydownTime:0,s=n>0?e/n*1e3:0;return {avgInterKeyDelay:x(t),interKeyDelayStdDev:ee(t),avgHoldDuration:x(i),holdDurationStdDev:ee(i),typingSpeed:s,correctionRate:e>0?r/e:0,keystrokeCount:e,correctionCount:r,totalDuration:n,interKeyDelays:t,holdDurations:i,pasteCount:this.pasteCount}}getRawData(){return [...this.keystrokes]}};function x(e){return e.length===0?0:e.reduce((t,i)=>t+i,0)/e.length}function ee(e){if(e.length<2)return 0;let t=x(e),i=e.map(r=>Math.pow(r-t,2));return Math.sqrt(x(i))}function xe(){return new Me}var Pe=class{constructor(){this.points=[],this.clicks=[],this.scrollEvents=[],this.isTracking=false,this.lastPoint=null;}start(){this.isTracking||(this.isTracking=true,this.reset());}stop(){this.isTracking=false;}reset(){this.points=[],this.clicks=[],this.scrollEvents=[],this.lastPoint=null;}handleMouseMove(e){if(!this.isTracking)return;let t={x:e.clientX,y:e.clientY,timestamp:performance.now()};if(this.lastPoint){let i=Math.sqrt(Math.pow(t.x-this.lastPoint.x,2)+Math.pow(t.y-this.lastPoint.y,2)),r=t.timestamp-this.lastPoint.timestamp;if(i<5&&r<50)return}this.points.push(t),this.lastPoint=t,this.points.length>1e3&&(this.points=this.points.slice(-500));}handleClick(e){this.isTracking&&this.clicks.push({x:e.clientX,y:e.clientY,timestamp:performance.now(),button:e.button});}handleScroll(e){this.isTracking&&(this.scrollEvents.push({delta:Math.abs(e.deltaY),timestamp:performance.now()}),this.scrollEvents.length>100&&(this.scrollEvents=this.scrollEvents.slice(-50)));}getEventHandlers(){return {onMouseMove:this.handleMouseMove.bind(this),onClick:this.handleClick.bind(this),onWheel:this.handleScroll.bind(this)}}getMetrics(){let e=[],t=[],i=0,r=0,n=0;for(let l=1;l<this.points.length;l++){let c=this.points[l-1],u=this.points[l],m=u.x-c.x,O=u.y-c.y,J=Math.sqrt(m*m+O*O),N=(u.timestamp-c.timestamp)/1e3;if(i+=J,N>0){let w=J/N;if(e.push(w),e.length>1){let V=e[e.length-2],H=(w-V)/N;t.push(Math.abs(H));}}if(l>=2){let w=this.points[l-2],V=c.x-w.x,H=c.y-w.y,pe=Math.atan2(H,V),ge=Math.atan2(O,m),I=Math.abs(ge-pe);I>Math.PI&&(I=2*Math.PI-I),I>Math.PI/4&&r++;}}if(this.points.length>=2){let l=this.points[0],c=this.points[this.points.length-1];n=Math.sqrt(Math.pow(c.x-l.x,2)+Math.pow(c.y-l.y,2));}let s=[];for(let l=1;l<this.clicks.length;l++)s.push(this.clicks[l].timestamp-this.clicks[l-1].timestamp);let o=[];for(let l=1;l<this.scrollEvents.length;l++){let c=(this.scrollEvents[l].timestamp-this.scrollEvents[l-1].timestamp)/1e3;c>0&&o.push(this.scrollEvents[l].delta/c);}let a=this.points.length>1?this.points[this.points.length-1].timestamp-this.points[0].timestamp:0;return {avgVelocity:d(e),velocityStdDev:Re(e),avgAcceleration:d(t),accelerationVariance:Le(t),totalDistance:i,directionChanges:r,straightnessRatio:i>0?n/i:0,avgClickInterval:d(s),clickCount:this.clicks.length,avgScrollSpeed:d(o),scrollCount:this.scrollEvents.length,totalDuration:a,movementCount:this.points.length}}getRawData(){return {points:[...this.points],clicks:[...this.clicks]}}};function d(e){return e.length===0?0:e.reduce((t,i)=>t+i,0)/e.length}function Re(e){if(e.length<2)return 0;let t=d(e),i=e.map(r=>Math.pow(r-t,2));return Math.sqrt(d(i))}function Le(e){if(e.length<2)return 0;let t=d(e),i=e.map(r=>Math.pow(r-t,2));return d(i)}function De(){return new Pe}var Ue=class{constructor(){this.touches=[],this.touchDurations=[],this.activeTouches=new Map,this.multiTouchCount=0,this.isTracking=false,this.startTime=null;}start(){this.isTracking||(this.isTracking=true,this.reset());}stop(){this.isTracking=false;}reset(){this.touches=[],this.touchDurations=[],this.activeTouches.clear(),this.multiTouchCount=0,this.startTime=null;}handleTouchStart(e){if(!this.isTracking)return;let t=performance.now();this.startTime===null&&(this.startTime=t),e.touches.length>1&&this.multiTouchCount++;for(let i=0;i<e.changedTouches.length;i++){let r=e.changedTouches[i],n={x:r.clientX,y:r.clientY,timestamp:t,pressure:r.force||0,radiusX:r.radiusX||0,radiusY:r.radiusY||0,force:r.force||0};this.touches.push(n),this.activeTouches.set(r.identifier,{start:n,startTime:t});}}handleTouchMove(e){if(!this.isTracking)return;let t=performance.now();for(let i=0;i<e.changedTouches.length;i++){let r=e.changedTouches[i],n={x:r.clientX,y:r.clientY,timestamp:t,pressure:r.force||0,radiusX:r.radiusX||0,radiusY:r.radiusY||0,force:r.force||0};this.touches.push(n);}this.touches.length>1e3&&(this.touches=this.touches.slice(-500));}handleTouchEnd(e){if(!this.isTracking)return;let t=performance.now();for(let i=0;i<e.changedTouches.length;i++){let r=e.changedTouches[i],n=this.activeTouches.get(r.identifier);if(n){let s=t-n.startTime;this.touchDurations.push(s),this.activeTouches.delete(r.identifier);}}}getEventHandlers(){return {onTouchStart:this.handleTouchStart.bind(this),onTouchMove:this.handleTouchMove.bind(this),onTouchEnd:this.handleTouchEnd.bind(this)}}getMetrics(){let e=this.touches.map(s=>s.pressure).filter(s=>s>0),t=this.touches.map(s=>(s.radiusX+s.radiusY)/2).filter(s=>s>0),i=this.touches.map(s=>s.force).filter(s=>s>0),r=[];for(let s=1;s<this.touches.length;s++){let o=this.touches[s-1],a=this.touches[s],l=(a.timestamp-o.timestamp)/1e3;if(l>0&&l<1){let c=Math.sqrt(Math.pow(a.x-o.x,2)+Math.pow(a.y-o.y,2));r.push(c/l);}}let n=this.touches.length>1?this.touches[this.touches.length-1].timestamp-this.touches[0].timestamp:0;return {avgPressure:p(e),pressureStdDev:Fe(e),avgRadius:p(t),avgForce:p(i),avgSwipeVelocity:p(r),touchCount:this.touches.length,multiTouchCount:this.multiTouchCount,avgTouchDuration:p(this.touchDurations),totalDuration:n}}getRawData(){return [...this.touches]}};function p(e){return e.length===0?0:e.reduce((t,i)=>t+i,0)/e.length}function Fe(e){if(e.length<2)return 0;let t=p(e),i=e.map(r=>Math.pow(r-t,2));return Math.sqrt(p(i))}function Oe(){return new Ue}function z(){return "ontouchstart"in window||navigator.maxTouchPoints>0||(navigator.msMaxTouchPoints??0)>0}var q="simplr_rum_session";function oe(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return (e==="x"?t:t&3|8).toString(16)})}var Ne=class{constructor(e=18e5,t){this.session=null,this.inactivityTimer=null,this.sessionTimeout=e,this.onSessionEnd=t;}initialize(){let e=this.loadSession(),t=Date.now();if(e){if(t-e.lastActivityAt<this.sessionTimeout)return this.session=e,this.session.lastActivityAt=t,this.saveSession(),this.startInactivityTimer(),this.session;this.onSessionEnd&&this.onSessionEnd(e);}return this.session=this.createNewSession(),this.saveSession(),this.startInactivityTimer(),this.session}createNewSession(){let e=Date.now();return {sessionId:oe(),startedAt:e,lastActivityAt:e,viewCount:0,actionCount:0,errorCount:0}}getSession(){return this.session}getSessionId(){return this.session?.sessionId||null}recordActivity(){this.session&&(this.session.lastActivityAt=Date.now(),this.saveSession(),this.resetInactivityTimer());}incrementViewCount(){this.session&&(this.session.viewCount++,this.recordActivity());}incrementActionCount(){this.session&&(this.session.actionCount++,this.recordActivity());}incrementErrorCount(){this.session&&(this.session.errorCount++,this.recordActivity());}setUser(e,t){this.session&&(this.session.userId=e,this.session.userAttributes=t,this.saveSession());}clearUser(){this.session&&(delete this.session.userId,delete this.session.userAttributes,this.saveSession());}endSession(){if(this.session){let e={...this.session};return this.onSessionEnd&&this.onSessionEnd(e),this.clearSession(),e}return null}clearSession(){this.session=null,this.stopInactivityTimer();try{typeof sessionStorage<"u"&&sessionStorage.removeItem(q);}catch{}}saveSession(){if(this.session)try{typeof sessionStorage<"u"&&sessionStorage.setItem(q,JSON.stringify(this.session));}catch{}}loadSession(){try{if(typeof sessionStorage<"u"){let e=sessionStorage.getItem(q);if(e)return JSON.parse(e)}}catch{}return null}startInactivityTimer(){this.stopInactivityTimer(),this.inactivityTimer=setTimeout(()=>{this.handleInactivityTimeout();},this.sessionTimeout);}resetInactivityTimer(){this.startInactivityTimer();}stopInactivityTimer(){this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null);}handleInactivityTimeout(){this.endSession();}destroy(){this.stopInactivityTimer(),this.session=null;}},Ve=class{constructor(){this.cachedContext=null;}getContext(){if(this.cachedContext)return this.cachedContext;let e={platform:this.detectPlatform(),os:this.detectOS(),osVersion:this.detectOSVersion(),browser:this.detectBrowser(),browserVersion:this.detectBrowserVersion(),screenResolution:this.getScreenResolution(),viewportSize:this.getViewportSize(),language:this.getLanguage(),timezone:this.getTimezone(),userAgent:this.getUserAgent()};return this.cachedContext=e,e}detectPlatform(){if(typeof navigator>"u")return "web";let e=navigator.userAgent.toLowerCase();return /iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":"web"}detectOS(){if(typeof navigator>"u")return "unknown";let e=navigator.userAgent;return /Windows/.test(e)?"Windows":/Mac OS X/.test(e)?"macOS":/iPhone|iPad|iPod/.test(e)?"iOS":/Android/.test(e)?"Android":/Linux/.test(e)?"Linux":/CrOS/.test(e)?"Chrome OS":"unknown"}detectOSVersion(){if(typeof navigator>"u")return;let e=navigator.userAgent,t=e.match(/Windows NT (\d+\.\d+)/);if(t)return {"10.0":"10/11","6.3":"8.1","6.2":"8","6.1":"7"}[t[1]]||t[1];let i=e.match(/Mac OS X (\d+[._]\d+[._]?\d*)/);if(i)return i[1].replace(/_/g,".");let r=e.match(/OS (\d+[._]\d+[._]?\d*)/);if(r)return r[1].replace(/_/g,".");let n=e.match(/Android (\d+\.?\d*\.?\d*)/);if(n)return n[1]}detectBrowser(){if(typeof navigator>"u")return;let e=navigator.userAgent;if(/Edg\//.test(e))return "Edge";if(/OPR\/|Opera/.test(e))return "Opera";if(/Chrome/.test(e))return "Chrome";if(/Safari/.test(e))return "Safari";if(/Firefox/.test(e))return "Firefox";if(/MSIE|Trident/.test(e))return "Internet Explorer"}detectBrowserVersion(){if(typeof navigator>"u")return;let e=navigator.userAgent,t=[[/Edg\/(\d+\.?\d*)/,1],[/OPR\/(\d+\.?\d*)/,1],[/Chrome\/(\d+\.?\d*)/,1],[/Version\/(\d+\.?\d*).*Safari/,1],[/Firefox\/(\d+\.?\d*)/,1]];for(let[i,r]of t){let n=e.match(i);if(n)return n[r]}}getScreenResolution(){if(!(typeof screen>"u"))return `${screen.width}x${screen.height}`}getViewportSize(){if(!(typeof window>"u"))return `${window.innerWidth}x${window.innerHeight}`}getLanguage(){if(!(typeof navigator>"u"))return navigator.language}getTimezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}getUserAgent(){if(!(typeof navigator>"u"))return navigator.userAgent}clearCache(){this.cachedContext=null;}},He=class{constructor(e){this.currentView=null,this.onViewEnd=e;}startView(e,t){this.endCurrentView();let i=oe();return this.currentView={id:i,name:e,url:t||(typeof location<"u"?location.href:""),startedAt:Date.now(),actionCount:0,errorCount:0,resourceCount:0},i}endCurrentView(){if(this.currentView&&this.onViewEnd){let e=Date.now()-this.currentView.startedAt;this.onViewEnd({id:this.currentView.id,name:this.currentView.name,url:this.currentView.url,duration:e,actionCount:this.currentView.actionCount,errorCount:this.currentView.errorCount,resourceCount:this.currentView.resourceCount});}this.currentView=null;}getCurrentViewId(){return this.currentView?.id||null}getCurrentViewName(){return this.currentView?.name||null}incrementActionCount(){this.currentView&&this.currentView.actionCount++;}incrementErrorCount(){this.currentView&&this.currentView.errorCount++;}incrementResourceCount(){this.currentView&&this.currentView.resourceCount++;}},Ke=new Set(["HTML","BODY","HEAD","SCRIPT","STYLE","META","LINK"]);function ae(e){let t=e.getAttribute("aria-label");if(t)return A(t);let i=e.getAttribute("title");if(i)return A(i);if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){let n=e.getAttribute("placeholder");return n?A(n):void 0}let r=e.tagName.toUpperCase();if(["BUTTON","A","LABEL"].includes(r)){let n=e.textContent?.trim();if(n)return A(n)}}function A(e){let t=e.replace(/\s+/g," ").trim();return t.length<=100?t:t.substring(0,100)+"..."}function ze(e){let t=[],i=e,r=0,n=5;for(;i&&i!==document.body&&r<n;){let s=i.tagName.toLowerCase();if(i.id){s=`#${CSS.escape(i.id)}`,t.unshift(s);break}let o=Array.from(i.classList).filter(l=>!l.startsWith("_")&&!l.includes("--")).slice(0,2);o.length>0&&(s+="."+o.map(l=>CSS.escape(l)).join("."));let a=i.parentElement;if(a){let l=i.tagName,c=Array.from(a.children).filter(u=>u.tagName===l);if(c.length>1){let u=c.indexOf(i)+1;s+=`:nth-of-type(${u})`;}}t.unshift(s),i=a,r++;}return t.join(" > ")}function qe(e){let t=e.tagName.toLowerCase(),i=ae(e),r=e.getAttribute("type"),n=e.getAttribute("role"),s=e.getAttribute("aria-label");return s?`Click on ${s}`:i?`Click on "${i}"`:e.id?`Click on #${e.id}`:t==="input"&&r?`Click on ${r} input`:t==="button"?"Click on button":t==="a"?"Click on link":n?`Click on ${n}`:`Click on ${t}`}var Be=class{constructor(e){this.isTracking=false,this.handleClick=t=>{let i=t.target;if(!i||!this.onAction)return;let r=this.findActionableElement(i);if(!r||Ke.has(r.tagName.toUpperCase()))return;let n=this.extractTargetInfo(r,t),s=qe(r);this.onAction(s,"click",n,t);},this.onAction=e;}start(){this.isTracking||typeof document>"u"||(document.addEventListener("click",this.handleClick,{capture:true}),this.isTracking=true);}stop(){!this.isTracking||typeof document>"u"||(document.removeEventListener("click",this.handleClick,{capture:true}),this.isTracking=false);}findActionableElement(e){let t=e,i=5,r=0;for(;t&&r<i;){let n=t.tagName.toUpperCase();if(["BUTTON","A","INPUT","SELECT","TEXTAREA"].includes(n)||t.getAttribute("role")==="button"||t.getAttribute("onclick")||t.hasAttribute("tabindex")||t.hasAttribute("data-action")||t.hasAttribute("data-click"))return t;t=t.parentElement,r++;}return e}extractTargetInfo(e,t){return e.getBoundingClientRect(),{tag:e.tagName.toLowerCase(),id:e.id||void 0,className:e.className?Array.from(e.classList).slice(0,3).join(" "):void 0,text:ae(e),selector:ze(e),position:{x:Math.round(t.pageX),y:Math.round(t.pageY)},viewportPosition:{x:Math.round(t.clientX),y:Math.round(t.clientY)}}}trackAction(e,t,i){if(this.onAction){let r={tag:i?.tag||"custom",...i},n=new MouseEvent("click",{bubbles:true,cancelable:true,clientX:i?.viewportPosition?.x||0,clientY:i?.viewportPosition?.y||0});this.onAction(e,t,r,n);}}isActive(){return this.isTracking}},Xe=class{constructor(e){this.isTracking=false,this.lastScrollTime=0,this.scrollStartY=0,this.scrollTimeout=null,this.handleScroll=()=>{let t=Date.now(),i=window.scrollY;t-this.lastScrollTime>200&&(this.scrollStartY=i,this.lastScrollTime=t),this.scrollTimeout&&clearTimeout(this.scrollTimeout),this.scrollTimeout=setTimeout(()=>{this.handleScrollEnd(i,t);},150);},this.onScroll=e;}start(){this.isTracking||typeof window>"u"||(window.addEventListener("scroll",this.handleScroll,{passive:true}),this.isTracking=true);}stop(){!this.isTracking||typeof window>"u"||(window.removeEventListener("scroll",this.handleScroll),this.isTracking=false,this.scrollTimeout&&(clearTimeout(this.scrollTimeout),this.scrollTimeout=null));}handleScrollEnd(e,t){if(!this.onScroll)return;let i=Math.abs(e-this.scrollStartY),r=t-this.lastScrollTime,n=e>this.scrollStartY?"down":"up";i>100&&this.onScroll(n,i,r);}};function v(e){let t=e;return t=t.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[EMAIL]"),t=t.replace(/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g,"[PHONE]"),t=t.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"[UUID]"),t.length>1e3&&(t=t.substring(0,1e3)+"..."),t}function R(e){let t=e.replace(/\?[^\s)]+/g,"?[QUERY]");return t.length>1e4&&(t=t.substring(0,1e4)+`
2
+ ...truncated`),t}function $e(e){return e instanceof Error?e.constructor.name:e instanceof Event&&e.type==="error"?"ResourceError":"UnknownError"}function je(e){return {message:v(e.message||"Unknown error"),stack:e.error?.stack?R(e.error.stack):void 0,type:$e(e.error),source:"source",handled:false,filename:e.filename,lineno:e.lineno,colno:e.colno}}function Ge(e){let t=e.reason;return t instanceof Error?{message:v(t.message),stack:t.stack?R(t.stack):void 0,type:`UnhandledRejection(${t.constructor.name})`,source:"source",handled:false}:{message:v(String(t)),type:"UnhandledRejection",source:"source",handled:false}}function We(e,t=false){return {message:v(e.message),stack:e.stack?R(e.stack):void 0,type:e.constructor.name,source:"custom",handled:t}}var Ye=class{constructor(e){this.isTracking=false,this.originalConsoleError=null,this.trackConsoleErrors=false,this.handleError=t=>{if(!this.onError||t.filename&&this.isExtensionError(t.filename))return;let i=je(t);this.onError(i);},this.handleRejection=t=>{if(!this.onError)return;let i=Ge(t);this.onError(i);},this.onError=e;}start(e){this.isTracking||typeof window>"u"||(this.trackConsoleErrors=e?.trackConsoleErrors??false,window.addEventListener("error",this.handleError),window.addEventListener("unhandledrejection",this.handleRejection),this.trackConsoleErrors&&this.interceptConsoleError(),this.isTracking=true);}stop(){!this.isTracking||typeof window>"u"||(window.removeEventListener("error",this.handleError),window.removeEventListener("unhandledrejection",this.handleRejection),this.originalConsoleError&&(console.error=this.originalConsoleError,this.originalConsoleError=null),this.isTracking=false);}interceptConsoleError(){this.originalConsoleError=console.error;let e=this;console.error=function(...t){if(e.originalConsoleError?.apply(console,t),e.onError){let i=t.map(n=>{if(n instanceof Error)return n.message;if(typeof n=="object")try{return JSON.stringify(n)}catch{return String(n)}return String(n)}).join(" "),r={message:v(i),type:"ConsoleError",source:"console",handled:true};t[0]instanceof Error&&(r.stack=t[0].stack?R(t[0].stack):void 0,r.type=`ConsoleError(${t[0].constructor.name})`),e.onError(r);}};}isExtensionError(e){return [/^chrome-extension:\/\//,/^moz-extension:\/\//,/^safari-extension:\/\//,/^ms-browser-extension:\/\//].some(t=>t.test(e))}trackError(e,t){if(!this.onError)return;let i;e instanceof Error?i=We(e,true):i={message:v(e),type:"CustomError",source:"custom",handled:true},this.onError(i);}isActive(){return this.isTracking}},Je=class{constructor(e=6e4,t=3){this.recentErrors=new Map,this.cleanupInterval=null,this.windowMs=e,this.maxDuplicates=t;}start(){this.cleanupInterval||(this.cleanupInterval=setInterval(()=>{this.cleanup();},this.windowMs));}stop(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.recentErrors.clear();}shouldTrack(e){let t=this.getErrorKey(e),i=this.recentErrors.get(t)||0;return i>=this.maxDuplicates?false:(this.recentErrors.set(t,i+1),true)}getErrorKey(e){let t=e.message.split(`
3
+ `)[0],i=e.stack?.split(`
4
+ `)[1]||"";return `${e.type}:${t}:${i}`}cleanup(){this.recentErrors.clear();}},Ze=[/\/v1\/rum\/events/,/google-analytics\.com/,/googletagmanager\.com/,/segment\.io/,/mixpanel\.com/,/amplitude\.com/,/sentry\.io/,/datadoghq\.com/];function M(e){try{let t=new URL(e,window.location.origin);["token","key","api_key","apikey","auth","password","secret","access_token","refresh_token"].forEach(r=>{t.searchParams.has(r)&&t.searchParams.set(r,"[REDACTED]");});let i=t.toString();return i.length>2e3&&(i=i.substring(0,2e3)+"..."),i}catch{return e.length>2e3?e.substring(0,2e3)+"...":e}}function te(e,t,i){return i&&i.length>0&&!i.some(r=>r.test(e))?true:t.some(r=>r.test(e))}var Qe=class{constructor(e){this.isTracking=false,this.originalFetch=null,this.originalXhrOpen=null,this.originalXhrSend=null,this.excludedPatterns=[],this.onResource=e;}start(e){this.isTracking||typeof window>"u"||(this.excludedPatterns=[...Ze,...(e?.excludedPatterns||[]).map(t=>typeof t=="string"?new RegExp(t):t)],e?.allowedPatterns&&(this.allowedPatterns=e.allowedPatterns.map(t=>typeof t=="string"?new RegExp(t):t)),this.interceptFetch(),this.interceptXHR(),this.isTracking=true);}stop(){this.isTracking&&(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),this.isTracking=false);}interceptFetch(){if(typeof fetch>"u")return;this.originalFetch=window.fetch;let e=this;window.fetch=async function(t,i){let r=typeof t=="string"?t:t instanceof URL?t.toString():t.url,n=i?.method||"GET",s=performance.now();if(te(r,e.excludedPatterns,e.allowedPatterns))return e.originalFetch.call(window,t,i);let o;i?.body&&(typeof i.body=="string"?o=i.body.length:i.body instanceof Blob?o=i.body.size:i.body instanceof ArrayBuffer&&(o=i.body.byteLength));try{let a=await e.originalFetch.call(window,t,i),l=performance.now()-s,c,u=a.headers.get("content-length");return u&&(c=parseInt(u,10)),e.onResource&&e.onResource({url:M(r),method:n.toUpperCase(),status:a.status,statusText:a.statusText,duration:Math.round(l),requestSize:o,responseSize:c,type:"fetch"}),a}catch(a){let l=performance.now()-s;throw e.onResource&&e.onResource({url:M(r),method:n.toUpperCase(),duration:Math.round(l),type:"fetch",error:a instanceof Error?a.message:"Network error"}),a}};}interceptXHR(){if(typeof XMLHttpRequest>"u")return;this.originalXhrOpen=XMLHttpRequest.prototype.open,this.originalXhrSend=XMLHttpRequest.prototype.send;let e=this;XMLHttpRequest.prototype.open=function(t,i,r=true,n,s){return this.__rum_method=t,this.__rum_url=i.toString(),e.originalXhrOpen.call(this,t,i,r,n,s)},XMLHttpRequest.prototype.send=function(t){let i=this,r=i.__rum_url,n=i.__rum_method;if(te(r,e.excludedPatterns,e.allowedPatterns))return e.originalXhrSend.call(i,t);let s=performance.now(),o;t&&(typeof t=="string"?o=t.length:t instanceof Blob?o=t.size:t instanceof ArrayBuffer&&(o=t.byteLength));let a=i.onreadystatechange;return i.onreadystatechange=function(l){if(i.readyState===XMLHttpRequest.DONE){let c=performance.now()-s,u,m=i.getResponseHeader("content-length");m&&(u=parseInt(m,10)),e.onResource&&(i.status>0?e.onResource({url:M(r),method:n.toUpperCase(),status:i.status,statusText:i.statusText,duration:Math.round(c),requestSize:o,responseSize:u,type:"xhr"}):e.onResource({url:M(r),method:n.toUpperCase(),duration:Math.round(c),type:"xhr",error:"Network error"}));}a&&a.call(i,l);},e.originalXhrSend.call(i,t)};}isActive(){return this.isTracking}},et={LCP:{good:2500,poor:4e3},FID:{good:100,poor:300},CLS:{good:.1,poor:.25},FCP:{good:1800,poor:3e3},TTFB:{good:800,poor:1800},INP:{good:200,poor:500}};function tt(e,t){let i=et[e];return t<=i.good?"good":t<=i.poor?"needs-improvement":"poor"}var it=class{constructor(e,t){this.observers=[],this.reportedVitals=new Set,this.onVital=e,this.onLongTask=t;}start(e){typeof PerformanceObserver>"u"||(this.observeLCP(),this.observeFID(),this.observeCLS(),this.observeFCP(),this.measureTTFB(),e?.trackLongTasks!==false&&this.observeLongTasks());}stop(){this.observers.forEach(e=>e.disconnect()),this.observers=[],this.reportedVitals.clear();}observeLCP(){try{let e=new PerformanceObserver(t=>{let i=t.getEntries(),r=i[i.length-1];if(r&&!this.reportedVitals.has("LCP")){let n=r.renderTime||r.loadTime||r.startTime;this.reportVital("LCP",n);}});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.reportedVitals.add("LCP");},{once:!0});}catch{}}observeFID(){try{let e=new PerformanceObserver(t=>{let i=t.getEntries()[0];if(i&&!this.reportedVitals.has("FID")){let r=i.processingStart-i.startTime;this.reportVital("FID",r);}});e.observe({type:"first-input",buffered:!0}),this.observers.push(e);}catch{}}observeCLS(){let e=0,t=0,i=[];try{let r=new PerformanceObserver(n=>{for(let s of n.getEntries())if(!s.hadRecentInput&&s.value){let o=i[0],a=i[i.length-1];t&&s.startTime-(a?.startTime||0)<1e3&&s.startTime-(o?.startTime||0)<5e3?(t+=s.value,i.push(s)):(t=s.value,i=[s]),t>e&&(e=t);}});r.observe({type:"layout-shift",buffered:!0}),this.observers.push(r),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&!this.reportedVitals.has("CLS")&&this.reportVital("CLS",e);},{once:!0});}catch{}}observeFCP(){try{let e=new PerformanceObserver(t=>{let i=t.getEntries().find(r=>r.name==="first-contentful-paint");i&&!this.reportedVitals.has("FCP")&&this.reportVital("FCP",i.startTime);});e.observe({type:"paint",buffered:!0}),this.observers.push(e);}catch{}}measureTTFB(){if(!(typeof performance>"u"))try{let e=performance.getEntriesByType("navigation")[0];if(e&&!this.reportedVitals.has("TTFB")){let t=e.responseStart-e.requestStart;t>=0&&this.reportVital("TTFB",t);}}catch{}}observeLongTasks(){try{let e=new PerformanceObserver(t=>{for(let i of t.getEntries())this.onLongTask&&this.onLongTask({duration:Math.round(i.duration),startTime:Math.round(i.startTime),attribution:this.getTaskAttribution(i)});});e.observe({type:"longtask",buffered:!0}),this.observers.push(e);}catch{}}getTaskAttribution(e){let t=e;if(t.attribution&&t.attribution.length>0){let i=t.attribution[0];if(i.containerSrc)return i.containerSrc;if(i.containerName)return i.containerName;if(i.name)return i.name}}reportVital(e,t){this.reportedVitals.has(e)||(this.reportedVitals.add(e),this.onVital&&this.onVital({name:e,value:Math.round(t*100)/100,rating:tt(e,t)}));}trackVital(e,t){this.reportVital(e,t);}},rt=class{constructor(e){this.isTracking=false,this.currentPath="",this.handleNavigation=()=>{let t=window.location.pathname+window.location.search;t!==this.currentPath&&this.onNavigate&&(this.onNavigate(this.currentPath,t),this.currentPath=t);},this.onNavigate=e;}start(){this.isTracking||typeof window>"u"||(this.currentPath=window.location.pathname+window.location.search,window.addEventListener("popstate",this.handleNavigation),this.interceptHistoryMethods(),this.isTracking=true);}stop(){!this.isTracking||typeof window>"u"||(window.removeEventListener("popstate",this.handleNavigation),this.isTracking=false);}interceptHistoryMethods(){let e=this,t=history.pushState,i=history.replaceState;history.pushState=function(...r){t.apply(this,r),e.handleNavigation();},history.replaceState=function(...r){i.apply(this,r),e.handleNavigation();};}getCurrentPath(){return this.currentPath}};function P(e){let t=e;return t=t.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[EMAIL]"),t=t.replace(/\b(\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g,"[PHONE]"),t=t.replace(/\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/g,"[CARD]"),t=t.replace(/\b\d{3}[-\s]?\d{2}[-\s]?\d{4}\b/g,"[SSN]"),t=t.replace(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,"[IP]"),t=t.replace(/eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*/g,"[JWT]"),t.length>5e3&&(t=t.substring(0,5e3)+"...[truncated]"),t}function ie(e){let t={},i=Object.keys(e).slice(0,50);for(let r of i){let n=e[r],s=r.toLowerCase();if(s.includes("password")||s.includes("secret")||s.includes("token")||s.includes("auth")||s.includes("key")||s.includes("credential")){t[r]="[REDACTED]";continue}if(typeof n=="string")t[r]=P(n);else if(typeof n=="object"&&n!==null)try{t[r]=JSON.parse(JSON.stringify(n,(o,a)=>typeof a=="string"?P(a):a));}catch{t[r]="[Object]";}else t[r]=n;}return t}var nt=class{constructor(e){this.isInterceptingConsole=false,this.originalConsole={},this.onLog=e;}interceptConsole(){this.isInterceptingConsole||typeof console>"u"||(["debug","info","warn","error"].forEach(e=>{this.originalConsole[e]=console[e];let t=this;console[e]=function(...i){t.originalConsole[e]?.apply(console,i),t.trackFromArgs(e,i);};}),this.isInterceptingConsole=true);}restoreConsole(){this.isInterceptingConsole&&(Object.keys(this.originalConsole).forEach(e=>{console[e]=this.originalConsole[e];}),this.originalConsole={},this.isInterceptingConsole=false);}trackFromArgs(e,t){if(!this.onLog||t.length===0)return;let i=t.map(s=>{if(typeof s=="string")return s;if(s instanceof Error)return `${s.name}: ${s.message}`;try{return JSON.stringify(s)}catch{return String(s)}}).join(" "),r,n=t[t.length-1];t.length>1&&typeof n=="object"&&n!==null&&!(n instanceof Error)&&(r=ie(n)),this.onLog({level:e,message:P(i),context:r});}log(e,t,i){this.onLog&&this.onLog({level:e,message:P(t),context:i?ie(i):void 0});}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}isIntercepting(){return this.isInterceptingConsole}},B=[1e3,5e3,15e3],st=class{constructor(e){this.queue=[],this.flushTimer=null,this.isFlushing=false,this.handleVisibilityChange=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&this.flushSync();},this.handlePageHide=()=>{this.flushSync();},this.handleBeforeUnload=()=>{this.flushSync();},this.endpoint=e.endpoint,this.apiKey=e.apiKey,this.batchSize=e.batchSize||30,this.flushInterval=e.flushInterval||1e4,this.onFlushError=e.onFlushError,this.onFlushSuccess=e.onFlushSuccess;}start(){this.flushTimer||(this.flushTimer=setInterval(()=>{this.flush();},this.flushInterval),typeof window<"u"&&(window.addEventListener("visibilitychange",this.handleVisibilityChange),window.addEventListener("pagehide",this.handlePageHide),window.addEventListener("beforeunload",this.handleBeforeUnload)));}stop(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),typeof window<"u"&&(window.removeEventListener("visibilitychange",this.handleVisibilityChange),window.removeEventListener("pagehide",this.handlePageHide),window.removeEventListener("beforeunload",this.handleBeforeUnload));}add(e){this.queue.length>=1e3&&(this.queue=this.queue.slice(Math.floor(1e3/2))),this.queue.push(e),this.queue.length>=this.batchSize&&this.flush();}async flush(){if(this.isFlushing||this.queue.length===0)return;this.isFlushing=true;let e=[...this.queue];this.queue=[];try{await this.sendBatch(e);}catch(t){this.queue.length+e.length<1e3&&(this.queue=[...e,...this.queue]),this.onFlushError&&this.onFlushError(t instanceof Error?t:new Error(String(t)),e);}finally{this.isFlushing=false;}}async sendBatch(e,t=0){let i={events:e,sentAt:Date.now()};try{let r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify(i),keepalive:!0});if(!r.ok){let s=await r.text();throw console.error(`[SimplrRUM] Batch send failed: HTTP ${r.status}`,s),new Error(`HTTP ${r.status}: ${r.statusText}`)}let n=await r.json();this.onFlushSuccess&&this.onFlushSuccess(n,e);}catch(r){if(console.error(`[SimplrRUM] Batch send error (retry ${t}):`,r),t<3){let n=B[t]||B[B.length-1];return await this.sleep(n),this.sendBatch(e,t+1)}throw r}}sleep(e){return new Promise(t=>setTimeout(t,e))}flushSync(){if(this.queue.length===0)return;let e=[...this.queue];this.queue=[];let t={events:e,sentAt:Date.now(),apiKey:this.apiKey};if(typeof navigator<"u"&&navigator.sendBeacon){let i=new Blob([JSON.stringify(t)],{type:"application/json"});navigator.sendBeacon(this.endpoint,i)||(this.queue=[...e,...this.queue]);}else fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify(t),keepalive:true}).catch(()=>{});}getQueueSize(){return this.queue.length}isRunning(){return this.flushTimer!==null}clear(){this.queue=[];}},ot=class{constructor(e=1){this.sampleRate=Math.min(1,Math.max(0,e)),this.sessionSampled=Math.random()<this.sampleRate;}shouldSample(){return this.sessionSampled}shouldSampleEvent(e){return e==="error"||e==="session_start"||e==="session_end"?true:this.sessionSampled}getSampleRate(){return this.sampleRate}isSessionSampled(){return this.sessionSampled}},at={updateInterval:6e4,highAccuracy:false,timeout:1e4,maximumAge:6e4},lt=class le{constructor(t={},i){this.currentLocation=null,this.watchId=null,this.updateTimer=null,this.permissionGranted=false,this.config={...at,...t},this.onLocationUpdate=i;}static isSupported(){return typeof navigator<"u"&&"geolocation"in navigator}async start(){if(!le.isSupported())return console.warn("SimplrRUM: Geolocation not supported"),false;try{let t=await this.getCurrentPosition();return t&&(this.currentLocation=this.positionToLocationData(t),this.permissionGranted=!0,this.onLocationUpdate?.(this.currentLocation)),this.startWatching(),this.startUpdateTimer(),!0}catch(t){return console.warn("SimplrRUM: Failed to start location tracking",t),false}}stop(){this.watchId!==null&&(navigator.geolocation.clearWatch(this.watchId),this.watchId=null),this.updateTimer!==null&&(clearInterval(this.updateTimer),this.updateTimer=null);}getLocation(){return this.currentLocation}hasPermission(){return this.permissionGranted}getCurrentPosition(){return new Promise(t=>{navigator.geolocation.getCurrentPosition(i=>t(i),i=>{console.warn("SimplrRUM: Geolocation error",i.message),t(null);},{enableHighAccuracy:this.config.highAccuracy,timeout:this.config.timeout,maximumAge:this.config.maximumAge});})}startWatching(){this.watchId===null&&(this.watchId=navigator.geolocation.watchPosition(t=>{this.currentLocation=this.positionToLocationData(t),this.onLocationUpdate?.(this.currentLocation);},t=>{t.code!==t.PERMISSION_DENIED&&console.warn("SimplrRUM: Watch position error",t.message);},{enableHighAccuracy:this.config.highAccuracy,timeout:this.config.timeout,maximumAge:this.config.maximumAge}));}startUpdateTimer(){this.updateTimer===null&&(this.updateTimer=setInterval(async()=>{let t=await this.getCurrentPosition();t&&(this.currentLocation=this.positionToLocationData(t),this.onLocationUpdate?.(this.currentLocation));},this.config.updateInterval));}positionToLocationData(t){return {latitude:t.coords.latitude,longitude:t.coords.longitude,accuracy:t.coords.accuracy,altitude:t.coords.altitude??void 0,altitudeAccuracy:t.coords.altitudeAccuracy??void 0,heading:t.coords.heading??void 0,speed:t.coords.speed??void 0,timestamp:t.timestamp}}},ct="https://api.simplr.so/v1/rum/events",ce=class y{constructor(){this.config=null,this.initialized=false,this.sessionManager=null,this.deviceCollector=null,this.viewManager=null,this.clickTracker=null,this.scrollTracker=null,this.errorTracker=null,this.errorDeduplicator=null,this.networkTracker=null,this.performanceTracker=null,this.navigationTracker=null,this.logCollector=null,this.locationTracker=null,this.batcher=null,this.sampler=null,this.globalAttributes={};}static getInstance(){return y.instance||(y.instance=new y),y.instance}initialize(t){if(this.initialized){console.warn("SimplrRUM already initialized");return}if(typeof window>"u"){console.warn("SimplrRUM requires a browser environment");return}if(this.config={trackClicks:true,trackErrors:true,trackNetwork:true,trackPerformance:true,trackLongTasks:true,trackLocation:false,locationUpdateInterval:6e4,locationHighAccuracy:false,batchSize:30,flushInterval:1e4,scrubPII:true,sampleRate:1,sessionTimeout:1800*1e3,...t},this.sampler=new ot(this.config.sampleRate),!this.sampler.isSessionSampled()){console.log("SimplrRUM: Session not sampled, skipping initialization"),this.initialized=true;return}this.deviceCollector=new Ve,this.sessionManager=new Ne(this.config.sessionTimeout,n=>this.trackEvent("session_end",{attributes:{duration:Date.now()-n.startedAt}})),this.sessionManager.initialize(),this.trackEvent("session_start"),this.viewManager=new He(n=>{this.trackEvent("view",{view:{id:n.id,name:n.name,url:n.url,startedAt:0,duration:n.duration,isActive:false,actionCount:n.actionCount,errorCount:n.errorCount,resourceCount:n.resourceCount}});});let i=this.config.endpoint||ct;this.batcher=new st({endpoint:i,apiKey:this.config.apiKey,batchSize:this.config.batchSize,flushInterval:this.config.flushInterval,onFlushError:(n,s)=>{console.error("SimplrRUM: Failed to flush events",n);}}),this.batcher.start(),this.config.trackClicks&&(this.clickTracker=new Be((n,s,o,a)=>{this.trackAction(n,s,{target:o});}),this.clickTracker.start(),this.scrollTracker=new Xe((n,s,o)=>{this.trackAction(`Scroll ${n}`,"scroll",{target:{tag:"window"}});}),this.scrollTracker.start()),this.config.trackErrors&&(this.errorDeduplicator=new Je,this.errorDeduplicator.start(),this.errorTracker=new Ye(n=>{this.errorDeduplicator?.shouldTrack(n)&&this.trackError(n);}),this.errorTracker.start()),this.config.trackNetwork&&(this.networkTracker=new Qe(n=>{this.trackResource(n);}),this.networkTracker.start({excludedPatterns:this.config.excludedUrlPatterns,allowedPatterns:this.config.allowedUrlPatterns})),this.config.trackPerformance&&(this.performanceTracker=new it(n=>this.trackVital(n),n=>this.trackLongTask(n)),this.performanceTracker.start({trackLongTasks:this.config.trackLongTasks})),this.navigationTracker=new rt((n,s)=>{this.trackView(s);}),this.navigationTracker.start(),this.logCollector=new nt(n=>{this.trackLog(n);}),this.config.trackLocation&&(this.locationTracker=new lt({updateInterval:this.config.locationUpdateInterval,highAccuracy:this.config.locationHighAccuracy},n=>{console.log("SimplrRUM: Location updated",n.latitude,n.longitude);}),this.locationTracker.start().then(n=>{n&&console.log("SimplrRUM: Location tracking enabled");}));let r=typeof location<"u"?location.pathname+location.search:"/";this.trackView(r),this.initialized=true,console.log("SimplrRUM initialized");}isInitialized(){return this.initialized}setUser(t,i){this.initialized&&this.sessionManager?.setUser(t,i);}clearUser(){this.initialized&&this.sessionManager?.clearUser();}addAttribute(t,i){this.globalAttributes[t]=i;}removeAttribute(t){delete this.globalAttributes[t];}trackView(t,i){if(!this.initialized)return;let r=this.viewManager?.startView(t);this.sessionManager?.incrementViewCount(),this.trackEvent("view",{view:{id:r||"",name:t,url:typeof location<"u"?location.href:"",startedAt:Date.now(),isActive:true,actionCount:0,errorCount:0,resourceCount:0},attributes:i});}trackAction(t,i,r){this.initialized&&(this.sessionManager?.incrementActionCount(),this.viewManager?.incrementActionCount(),this.trackEvent("action",{action:{name:t,type:i,target:r?.target},attributes:r?.attributes}));}trackError(t,i){if(!this.initialized)return;this.sessionManager?.incrementErrorCount(),this.viewManager?.incrementErrorCount();let r=t instanceof Error?{message:t.message,stack:t.stack,type:t.constructor.name,source:"custom",handled:true}:t;this.trackEvent("error",{error:r,attributes:i});}trackResource(t){this.initialized&&(this.viewManager?.incrementResourceCount(),this.trackEvent("resource",{resource:t}));}trackVital(t){this.initialized&&this.trackEvent("vital",{vital:t});}trackLongTask(t){this.initialized&&this.trackEvent("long_task",{longTask:t});}trackLog(t){this.initialized&&this.trackEvent("log",{log:t});}log(t,i,r){this.initialized&&this.logCollector?.log(t,i,r);}stopSession(){this.initialized&&(this.viewManager?.endCurrentView(),this.sessionManager?.endSession(),this.batcher?.flush(),this.clickTracker?.stop(),this.scrollTracker?.stop(),this.errorTracker?.stop(),this.errorDeduplicator?.stop(),this.networkTracker?.stop(),this.performanceTracker?.stop(),this.navigationTracker?.stop(),this.locationTracker?.stop(),this.batcher?.stop(),this.initialized=false);}trackEvent(t,i){if(!this.sampler?.shouldSampleEvent(t))return;let r=this.sessionManager?.getSession();if(!r)return;let n={type:t,timestamp:Date.now(),sessionId:r.sessionId,viewId:this.viewManager?.getCurrentViewId()||void 0,userId:r.userId,applicationId:this.config.applicationId,applicationVersion:this.config?.applicationVersion,environment:this.config?.environment,device:this.deviceCollector?.getContext()||{platform:"web",os:"unknown"},location:this.locationTracker?.getLocation()||void 0,globalAttributes:Object.keys(this.globalAttributes).length>0?this.globalAttributes:void 0,...i};this.sessionManager?.recordActivity(),this.batcher?.add(n);}flush(){return this.batcher?.flush()||Promise.resolve()}getSessionId(){return this.sessionManager?.getSessionId()||null}getViewId(){return this.viewManager?.getCurrentViewId()||null}};ce.instance=null;var ue=ce,S=ue.getInstance();function ut(e,t){let i=t[e.attribute];switch(e.op){case "eq":return String(i)===e.value;case "neq":return String(i)!==e.value;case "contains":return String(i??"").includes(e.value);default:return false}}var L=class{constructor(){this.apiKey="",this.baseUrl="https://api.simplr.sh",this.environment="test",this.refreshIntervalMs=6e4,this.flags={},this.timer=null,this.ready=false;}async initialize(e){this.apiKey=e.apiKey,e.baseUrl&&(this.baseUrl=e.baseUrl),e.environment&&(this.environment=e.environment),e.refreshIntervalMs!==void 0&&(this.refreshIntervalMs=e.refreshIntervalMs),await this.refresh(),this.ready=true,this.refreshIntervalMs>0&&typeof setInterval<"u"&&(this.timer=setInterval(()=>this.refresh(),this.refreshIntervalMs));}setUser(e){this.userId=e;}async refresh(){try{let e=await fetch(`${this.baseUrl}/v1/flags?environment=${encodeURIComponent(this.environment)}`,{headers:{"X-API-Key":this.apiKey}});if(!e.ok)return;let t=(await e.json())?.content?.flags||[],i={};for(let r of t)i[r.key]=r;this.flags=i;}catch{}}isEnabled(e,t){let i=this.flags[e];if(!i||!i.enabled)return false;let r=t?.userId||this.userId||$();return i.target_user_ids&&i.target_user_ids.includes(r)||t?.attributes&&i.rules?.length&&i.rules.some(n=>ut(n,t.attributes))||i.rollout_percentage>=100?true:i.rollout_percentage<=0?false:g(`${e}:${r}`)%100<i.rollout_percentage}getAll(){return {...this.flags}}isReady(){return this.ready}dispose(){this.timer&&clearInterval(this.timer),this.timer=null;}},ht=new L,D=class{constructor(e){if(this.config={apiKey:e.apiKey,endpoint:e.endpoint||"https://api.simplr.so",gatewayUrl:e.gatewayUrl||"https://auth.simplr.so"},!this.config.apiKey)throw new Error("API key is required")}async connect(e){let t=e.mode||"popup",i=await this.request("/v1/ai-connect/initiate",{method:"POST",body:JSON.stringify({end_user_id:e.userId,end_user_email:e.email,redirect_uri:window.location.href,binding:e.binding||"any_location",expires_in_days:e.expiresInDays||7,fingerprint_hash:e.fingerprintHash})}),r=await i.json();if(!i.ok)return {success:false,error:r.message||"Failed to initiate connection"};let n=r.data.gateway_url;return t==="redirect"?(window.location.href=n,{success:true}):this.openConnectPopup(n,e)}openConnectPopup(e,t){return new Promise(i=>{let r=t.popupWidth||450,n=t.popupHeight||650,s=window.screenX+(window.outerWidth-r)/2,o=window.screenY+(window.outerHeight-n)/2,a=window.open(e,"simplr-ai-connect",`width=${r},height=${n},left=${s},top=${o},scrollbars=yes,resizable=yes`);if(!a){i({success:false,error:"Popup blocked. Please allow popups for this site."});return}let l=u=>{u.origin.includes("simplr")&&u.data?.type==="simplr-ai-connect-complete"&&(window.removeEventListener("message",l),clearInterval(c),u.data.success?i({success:true,delegationId:u.data.delegationId,token:u.data.token}):i({success:false,error:u.data.error||"Connection failed"}),a.close());};window.addEventListener("message",l);let c=setInterval(()=>{a.closed&&(clearInterval(c),window.removeEventListener("message",l),i({success:false,error:"Connection cancelled"}));},500);})}async createDelegation(e){let t=await this.request("/v1/ai/delegations",{method:"POST",body:JSON.stringify({end_user_id:e.userId,end_user_email:e.email,binding:e.binding||"any_location",expires_in_days:e.expiresInDays||7,session_id:e.sessionId,fingerprint_hash:e.fingerprintHash})}),i=await t.json();if(!t.ok)throw new Error(i.message||"Failed to create delegation");return {token:i.data.delegation.token,delegationId:i.data.delegation.delegation_id,expiresAt:i.data.delegation.expires_at,bindingMode:i.data.delegation.binding_mode}}async validate(e,t){let i=await this.request("/v1/ai/validate",{method:"POST",body:JSON.stringify({token:e,fingerprint_hash:t?.fingerprintHash,ai_provider:t?.aiProvider,action:t?.action})}),r=await i.json();return i.ok?{valid:true,sessionType:r.data.session_type,endUserId:r.data.end_user_id,delegation:r.data.delegation?{delegationId:r.data.delegation.delegation_id,bindingMode:r.data.delegation.binding_mode,expiresAt:r.data.delegation.expires_at,useCount:r.data.delegation.use_count}:void 0}:{valid:false,error:r.error||r.message||"Validation failed"}}async revoke(e,t){let i=`/v1/ai/delegations/${e}${t?`?reason=${encodeURIComponent(t)}`:""}`,r=await this.request(i,{method:"DELETE"});if(!r.ok){let n=await r.json();throw new Error(n.message||"Failed to revoke delegation")}}async list(e){let t=e?`/v1/ai/delegations?end_user_id=${encodeURIComponent(e)}`:"/v1/ai/delegations",i=await this.request(t,{method:"GET"}),r=await i.json();if(!i.ok)throw new Error(r.message||"Failed to list delegations");return r.data.delegations.map(n=>({delegationId:n.delegation_id,endUserId:n.end_user_id,bindingMode:n.binding_mode,status:n.status,expiresAt:n.expires_at,useCount:n.use_count,lastUsedAt:n.last_used_at,createdAt:n.created_at}))}async get(e){let t=await this.request(`/v1/ai/delegations/${e}`,{method:"GET"}),i=await t.json();if(!t.ok)throw new Error(i.message||"Failed to get delegation");let r=i.data.delegation;return {delegationId:r.delegation_id,endUserId:r.end_user_id,bindingMode:r.binding_mode,status:r.status,expiresAt:r.expires_at,useCount:r.use_count,lastUsedAt:r.last_used_at,createdAt:r.created_at}}async stats(){let e=await this.request("/v1/ai/stats",{method:"GET"}),t=await e.json();if(!e.ok)throw new Error(t.message||"Failed to get stats");return {totalDelegations:t.data.stats.total_delegations,activeDelegations:t.data.stats.active_delegations,totalUses:t.data.stats.total_uses,delegationsByBinding:{verifiedDevice:t.data.stats.delegations_by_binding.verified_device,anyLocation:t.data.stats.delegations_by_binding.any_location}}}async revokeAllForUser(e,t){let i=await this.request("/v1/ai/revoke-all",{method:"POST",body:JSON.stringify({end_user_id:e,reason:t})}),r=await i.json();if(!i.ok)throw new Error(r.message||"Failed to revoke delegations");return r.data.revoked_count}async request(e,t){let i=`${this.config.endpoint}${e}`;return fetch(i,{...t,headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey,...t.headers}})}};function dt(e){return new D(e)}var U=class{constructor(e){this.config=e,this.baseUrl=e.baseUrl||"https://api.simplr.sh";}setDeviceSignalCollector(e){this.collectDeviceSignalsFn=e;}async identify(e,t){let i=t?.deviceSignals;!i&&this.collectDeviceSignalsFn&&(i=await this.collectDeviceSignalsFn());let r={external_id:e,profile_type:t?.profileType||"customer"};return i&&(r.fingerprint_hash=i.fingerprint),this.request("POST","/v1/profiles",r)}async submitOrder(e){let t={...e};if(!t.fingerprint_hash&&this.collectDeviceSignalsFn){let i=await this.collectDeviceSignalsFn();t.fingerprint_hash=i.fingerprint;}if(!t.location_latitude&&typeof navigator<"u"&&navigator.geolocation)try{let i=await new Promise((r,n)=>{navigator.geolocation.getCurrentPosition(r,n,{timeout:3e3});});t.location_latitude=i.coords.latitude,t.location_longitude=i.coords.longitude;}catch{}return this.request("POST","/v1/orders",t)}async getProfileRisk(e){return this.request("GET",`/v1/profiles/${encodeURIComponent(e)}`)}async reportOutcome(e,t){await this.request("POST",`/v1/profiles/${encodeURIComponent(e)}/report`,{outcome:t});}async request(e,t,i){let r=`${this.baseUrl}${t}`,n={"Content-Type":"application/json","x-api-key":this.config.apiKey},s=await fetch(r,{method:e,headers:n,body:i?JSON.stringify(i):void 0});if(!s.ok){let o=await s.text();throw new Error(`SimplrProfiles API error (${s.status}): ${o}`)}return (await s.json()).data}};function pt(e){return new U(e)}var j=class{constructor(e={}){this.formStartTime=null,this.isInitialized=false,this.config={collectBiometrics:true,autoStart:true,...e},this.keystrokeTracker=xe(),this.mouseTracker=De(),this.touchTracker=Oe(),this.config.autoStart&&this.initialize();}initialize(){this.isInitialized||(this.isInitialized=true,this.config.collectBiometrics&&this.startTracking());}startTracking(){if(this.keystrokeTracker.start(),this.mouseTracker.start(),z()&&this.touchTracker.start(),this.formStartTime=performance.now(),typeof document<"u"){let e=this.mouseTracker.getEventHandlers();if(document.addEventListener("mousemove",e.onMouseMove,{passive:true}),document.addEventListener("click",e.onClick),document.addEventListener("wheel",e.onWheel,{passive:true}),z()){let t=this.touchTracker.getEventHandlers();document.addEventListener("touchstart",t.onTouchStart,{passive:true}),document.addEventListener("touchmove",t.onTouchMove,{passive:true}),document.addEventListener("touchend",t.onTouchEnd,{passive:true});}}}stopTracking(){this.keystrokeTracker.stop(),this.mouseTracker.stop(),this.touchTracker.stop();}trackInput(e){let t=this.keystrokeTracker.getEventHandlers();return {onKeyDown:t.onKeyDown,onKeyUp:t.onKeyUp,onPaste:t.onPaste,"data-simplr-field":e}}async collectDeviceSignals(){let[e,t,i,r]=await Promise.all([Promise.resolve(me()),Promise.resolve(ve()),we(),be()]),n=Te(),s=Ee(),o=Ce(),a=_e(),l={canvas_hash:e.hash,webgl_hash:t.hash,audio_hash:i.hash,fonts_hash:r.hash},c=await ne({...l,screen:n.screenResolution,timezone:n.timezone,language:n.language,platform:n.platform}),u=Ie();return {fingerprint:c,fingerprint_components:l,device_id:$(),device_id_created_at:u?.toISOString()??null,platform:"web",os:o.os,os_version:o.version,browser:a.browser,browser_version:a.version,user_agent:n.userAgent,screen_resolution:n.screenResolution,color_depth:n.screenColorDepth,device_pixel_ratio:n.devicePixelRatio,timezone:n.timezone,timezone_offset:n.timezoneOffset,language:n.language,languages:n.languages,cpu_cores:n.hardwareConcurrency,device_memory:n.deviceMemory,has_touch:n.hasTouch,max_touch_points:n.maxTouchPoints,is_webdriver:n.isWebDriver,is_headless:s.isHeadless,headless_indicators:s.indicators,canvas_blocked:fe(),webgl_vendor:t.vendor,webgl_renderer:t.renderer,plugin_count:n.plugins.length,cookies_enabled:n.cookiesEnabled,do_not_track:n.doNotTrack}}collectBehaviorSignals(){let e={};return this.config.collectBiometrics&&(e.keystroke=this.keystrokeTracker.getMetrics(),e.mouse=this.mouseTracker.getMetrics(),z()&&(e.touch=this.touchTracker.getMetrics()),this.formStartTime!==null&&(e.form_fill_time=performance.now()-this.formStartTime)),e}async collect(){let[e,t]=await Promise.all([this.collectDeviceSignals(),Promise.resolve(this.collectBehaviorSignals())]);return {device:e,behavior:t,collected_at:new Date().toISOString()}}reset(){this.keystrokeTracker.reset(),this.mouseTracker.reset(),this.touchTracker.reset(),this.formStartTime=performance.now();}get isReady(){return this.isInitialized}};var he="https://api.simplr.sh";function G(e,t){if(!(e===false||e===void 0))return e===true?t:{...t,...e}}var F=class{constructor(){this._config=null;this._baseUrl=he;this.fraud=null;this.flags=null;this.profiles=null;this.rum=null;this.ai=null;this.readyResolvers=[];this._ready=false;}get isConfigured(){return this._config!==null}get apiKey(){return this._config?.apiKey}get baseUrl(){return this._baseUrl}configure(t){if(this._config&&this._config.apiKey===t.apiKey)return this;this._config={autoStart:true,collectBiometrics:true,...t},this._baseUrl=(t.baseUrl||he).replace(/\/+$/,"");let i=t.apiKey;this.fraud=new j({apiKey:i,autoStart:this._config.autoStart,collectBiometrics:this._config.collectBiometrics,...t.fraud});let r=G(t.flags===void 0?true:t.flags,{apiKey:i,baseUrl:this._baseUrl});r&&(this.flags=new L,this.flags.initialize(r));let n=G(t.profiles===void 0?true:t.profiles,{apiKey:i,baseUrl:this._baseUrl});n&&(this.profiles=new U(n),this.profiles.setDeviceSignalCollector(()=>this.fraud.collectDeviceSignals())),t.rum&&(S.isInitialized()||S.initialize(t.rum),this.rum=S);let s=G(t.ai===void 0?true:t.ai,{apiKey:i});return s&&s.apiKey&&(this.ai=new D(s)),this._ready=true,this.readyResolvers.splice(0).forEach(o=>o()),typeof window<"u"&&window.dispatchEvent(new CustomEvent("simplr:configured",{detail:{controller:this}})),this}ready(){return this._ready?Promise.resolve():new Promise(t=>this.readyResolvers.push(t))}requireFraud(){if(!this.fraud)throw new Error('Simplr is not configured. Call SimplrElements.configure({ apiKey }) or add a <simplr-provider api-key="pk_..."> element first.');return this.fraud}collect(){return this.requireFraud().collect()}getDeviceSignals(){return this.requireFraud().collectDeviceSignals()}getBehaviorSignals(){return this.requireFraud().collectBehaviorSignals()}trackInput(t){return this.requireFraud().trackInput(t)}reset(){this.requireFraud().reset();}async check(t={}){let i=await this.collect(),r={...t,device:t.device??i.device,behavior:t.behavior??i.behavior};return this.request("/v1/check",r)}async request(t,i){let r=this.apiKey;if(!r)throw new Error("Simplr is not configured (missing apiKey).");let n=await fetch(`${this._baseUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":r},body:JSON.stringify(i)}),s=await n.json().catch(()=>null);if(!n.ok){let o=s&&(s.message||s.error)||`Simplr API error ${n.status}`;throw new Error(o)}return s&&"content"in s?s.content:s}isFeatureEnabled(t,i){return this.flags?this.flags.isEnabled(t,i):false}dispose(){this.fraud?.stopTracking(),this.flags?.dispose(),this.rum?.stopSession(),this._config=null,this._ready=false,this.fraud=this.flags=this.profiles=this.ai=this.rum=null;}},h=new F;function gt(e,t){return h.isFeatureEnabled(e,t)}function mt(e){return e.getAttribute("api-key")||e.getAttribute("public-key")||e.getAttribute("publicKey")||e.getAttribute("data-simplr-key")||typeof document<"u"&&(document.documentElement.getAttribute("data-simplr-key")||document.body?.getAttribute("data-simplr-key"))||void 0||(typeof window<"u"?window.SIMPLR_CONFIG?.apiKey||window.SIMPLR_CONFIG?.publicKey:void 0)||void 0}function W(e,t,i){if(!e.hasAttribute(t))return i;let r=e.getAttribute(t);return r!=="false"&&r!=="off"&&r!=="0"}var k=class extends HTMLElement{static get observedAttributes(){return ["api-key","public-key","base-url"]}connectedCallback(){this.tryConfigure();}attributeChangedCallback(){this.isConnected&&this.tryConfigure();}tryConfigure(){let t=mt(this);if(!t)return;let i=this.getAttribute("app-id")||(typeof window<"u"?window.SIMPLR_CONFIG?.appId:void 0);h.configure({apiKey:t,baseUrl:this.getAttribute("base-url")||(typeof window<"u"?window.SIMPLR_CONFIG?.baseUrl:void 0)||void 0,autoStart:!this.hasAttribute("no-autostart"),flags:W(this,"flags",true),profiles:W(this,"profiles",true),ai:W(this,"ai",true),rum:i?{apiKey:t,applicationId:i}:void 0}),this.dispatchEvent(new CustomEvent("simplr-ready",{bubbles:true,composed:true,detail:{controller:h}}));}};var b=class extends HTMLElement{constructor(){super(...arguments);this.form=null;this.onSubmit=i=>this.handleSubmit(i);}connectedCallback(){this.form=this.querySelector("form"),(this.form??this).addEventListener("submit",this.onSubmit);}disconnectedCallback(){(this.form??this).removeEventListener("submit",this.onSubmit);}get fieldName(){return this.getAttribute("field-name")||"simplr_signals"}async handleSubmit(i){this.hasAttribute("native-submit")||i.preventDefault(),this.setAttribute("submitting","");try{let n=await h.collect(),s;if(this.hasAttribute("auto-check")){let o=this.form??i.target,a={},l=o?.querySelector?.('[type="email"], [name="email"]');l?.value&&(a.email=l.value),s=await h.check(a);}if(this.form){let o=this.form.querySelector(`input[name="${this.fieldName}"]`);o||(o=document.createElement("input"),o.type="hidden",o.name=this.fieldName,this.form.appendChild(o)),o.value=JSON.stringify({signals:n,check:s});}this.dispatchEvent(new CustomEvent("simplr-submit",{bubbles:!0,composed:!0,detail:{signals:n,check:s,event:i}}));}catch(n){this.dispatchEvent(new CustomEvent("simplr-error",{bubbles:true,composed:true,detail:{error:n instanceof Error?n:new Error(String(n))}}));}finally{this.removeAttribute("submitting");}}};var T=class extends HTMLElement{constructor(){super(...arguments);this.input=null;this.handlers=null;this.bound={};}static get observedAttributes(){return ["field"]}get field(){return this.getAttribute("field")||"input"}connectedCallback(){queueMicrotask(()=>this.attach());}disconnectedCallback(){this.detach();}attributeChangedCallback(){this.isConnected&&(this.detach(),this.attach());}attach(){h.fraud&&(this.input=this.querySelector("input")||this.querySelector("textarea")||null,this.input&&(this.handlers=h.trackInput(this.field),this.input.setAttribute("data-simplr-field",this.field),this.bound.down=i=>this.handlers.onKeyDown(i),this.bound.up=i=>this.handlers.onKeyUp(i),this.bound.paste=()=>this.handlers.onPaste(),this.input.addEventListener("keydown",this.bound.down),this.input.addEventListener("keyup",this.bound.up),this.input.addEventListener("paste",this.bound.paste)));}detach(){this.input&&(this.bound.down&&this.input.removeEventListener("keydown",this.bound.down),this.bound.up&&this.input.removeEventListener("keyup",this.bound.up),this.bound.paste&&this.input.removeEventListener("paste",this.bound.paste),this.bound={},this.input=null);}};var E=class extends HTMLElement{constructor(){super(...arguments);this.onConfigured=()=>this.evaluate();this.poll=null;}static get observedAttributes(){return ["key","user-id"]}connectedCallback(){typeof window<"u"&&window.addEventListener("simplr:configured",this.onConfigured),this.evaluate(),this.poll=setInterval(()=>this.evaluate(),2e3);}disconnectedCallback(){typeof window<"u"&&window.removeEventListener("simplr:configured",this.onConfigured),this.poll&&clearInterval(this.poll),this.poll=null;}attributeChangedCallback(){this.isConnected&&this.evaluate();}get key(){return this.getAttribute("key")||""}get enabled(){if(!this.key)return false;let i={},r=this.getAttribute("user-id");return r&&(i.userId=r),h.isFeatureEnabled(this.key,i)}evaluate(){let i=this.enabled;i?(this.removeAttribute("hidden"),this.setAttribute("enabled","")):(this.setAttribute("hidden",""),this.removeAttribute("enabled")),this.dispatchEvent(new CustomEvent("simplr-flag",{bubbles:true,composed:true,detail:{key:this.key,enabled:i}}));}};var C=class extends HTMLElement{static get observedAttributes(){return ["name"]}get viewName(){return this.getAttribute("name")||(typeof location<"u"?location.pathname:"/")}connectedCallback(){this.track();}attributeChangedCallback(t,i,r){this.isConnected&&i!==r&&this.track();}track(){let t=h.rum;t&&t.isInitialized()&&(t.trackView(this.viewName),this.dispatchEvent(new CustomEvent("simplr-view",{bubbles:true,composed:true,detail:{name:this.viewName,viewId:t.getViewId()}})));}};var _=class extends HTMLElement{constructor(){super(...arguments);this.trigger=null;this.onClick=()=>this.run();}connectedCallback(){queueMicrotask(()=>{this.trigger=this.querySelector("[slot=trigger]")||this.querySelector("button")||this,this.trigger.addEventListener("click",this.onClick);});}disconnectedCallback(){this.trigger?.removeEventListener("click",this.onClick);}get userId(){return this.getAttribute("user-id")||""}async run(){let i=h.ai;if(!i){this.dispatchEvent(new CustomEvent("simplr-error",{bubbles:true,composed:true,detail:{error:new Error("AI delegation is not configured.")}}));return}let r=this.getAttribute("binding")||void 0,n=this.getAttribute("email")||void 0,s;try{h.fraud&&(s=(await h.getDeviceSignals()).fingerprint);}catch{}try{let o=this.getAttribute("mode")==="connect"?await i.connect({userId:this.userId,email:n,binding:r,fingerprintHash:s}):await i.createDelegation({userId:this.userId,email:n,binding:r,fingerprintHash:s});this.dispatchEvent(new CustomEvent("simplr-delegation",{bubbles:!0,composed:!0,detail:{result:o}}));}catch(o){this.dispatchEvent(new CustomEvent("simplr-error",{bubbles:true,composed:true,detail:{error:o instanceof Error?o:new Error(String(o))}}));}}};var de={"simplr-provider":k,"simplr-protected-form":b,"simplr-protected-input":T,"simplr-feature-flag":E,"simplr-rum-view":C,"simplr-ai-delegation":_};function Y(){if(!(typeof customElements>"u"))for(let[e,t]of Object.entries(de))customElements.get(e)||customElements.define(e,t);}typeof customElements<"u"&&Y();
5
+ exports.SIMPLR_ELEMENTS=de;exports.SimplrAI=D;exports.SimplrAiDelegationElement=_;exports.SimplrController=F;exports.SimplrElements=h;exports.SimplrFeatureFlagElement=E;exports.SimplrFlags=L;exports.SimplrFraud=j;exports.SimplrProfiles=U;exports.SimplrProtectedFormElement=b;exports.SimplrProtectedInputElement=T;exports.SimplrProviderElement=k;exports.SimplrRUM=ue;exports.SimplrRumViewElement=C;exports.clearDeviceId=Ae;exports.createFingerprintHash=ne;exports.createSimplrAI=dt;exports.createSimplrProfiles=pt;exports.defineSimplrElements=Y;exports.getDeviceId=$;exports.isFeatureEnabled=gt;exports.murmurHash3=g;exports.sha256=re;exports.simplrFlags=ht;exports.simplrRUM=S;return exports;})({});//# sourceMappingURL=simplr-web-components.global.js.map
6
+ //# sourceMappingURL=simplr-web-components.global.js.map