@tracelog/lib 2.10.0 → 3.0.0-rc.115.6

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.
@@ -1,3 +1,3 @@
1
- var A=9e5;var X=120,z=49152,Y=100,q=500,Ae=200;var C=1e3,J=500,Ce=1e3;var _="data-tlog",ot=["button","a",'input[type="button"]','input[type="submit"]','input[type="reset"]','input[type="checkbox"]','input[type="radio"]',"select","textarea",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="option"]','[role="checkbox"]','[role="radio"]','[role="switch"]',"[routerLink]","[ng-click]","[data-action]","[data-click]","[data-navigate]","[data-toggle]","[onclick]",".btn",".button",".clickable",".nav-link",".menu-item","[data-testid]",'[tabindex="0"]'],at=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],lt=["token","auth","key","session","reset","password","api_key","apikey","secret","access_token","refresh_token","verification","code","otp"];var v={INVALID_SESSION_TIMEOUT:"Session timeout must be between 30000ms (30 seconds) and 86400000ms (24 hours)",INVALID_SAMPLING_RATE:"Sampling rate must be between 0 and 1",INVALID_ERROR_SAMPLING_RATE:"Error sampling must be between 0 and 1",INVALID_TRACELOG_PROJECT_ID:"TraceLog project ID is required when integration is enabled",INVALID_CUSTOM_API_URL:"Custom API URL is required when integration is enabled",INVALID_GLOBAL_METADATA:"Global metadata must be an object",INVALID_SENSITIVE_QUERY_PARAMS:"Sensitive query params must be an array of strings",INVALID_PRIMARY_SCROLL_SELECTOR:"Primary scroll selector must be a non-empty string",INVALID_PRIMARY_SCROLL_SELECTOR_SYNTAX:"Invalid CSS selector syntax for primaryScrollSelector",INVALID_PAGE_VIEW_THROTTLE:"Page view throttle must be a non-negative number",INVALID_CLICK_THROTTLE:"Click throttle must be a non-negative number",INVALID_MAX_SAME_EVENT_PER_MINUTE:"Max same event per minute must be a positive number",INVALID_VIEWPORT_CONFIG:"Viewport config must be an object",INVALID_VIEWPORT_ELEMENTS:"Viewport elements must be a non-empty array",INVALID_VIEWPORT_ELEMENT:"Each viewport element must have a valid selector string",INVALID_VIEWPORT_ELEMENT_ID:"Viewport element id must be a non-empty string",INVALID_VIEWPORT_ELEMENT_NAME:"Viewport element name must be a non-empty string",INVALID_VIEWPORT_THRESHOLD:"Viewport threshold must be a number between 0 and 1",INVALID_VIEWPORT_MIN_DWELL_TIME:"Viewport minDwellTime must be a non-negative number",INVALID_VIEWPORT_COOLDOWN_PERIOD:"Viewport cooldownPeriod must be a non-negative number",INVALID_VIEWPORT_MAX_TRACKED_ELEMENTS:"Viewport maxTrackedElements must be a positive number",INVALID_SEND_INTERVAL:"Send interval must be between 1000ms (1 second) and 60000ms (60 seconds)"},ct=[/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,/javascript:/gi,/on\w+\s*=/gi,/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,/<embed\b[^>]*>/gi,/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi];var S="tlog",N=`${S}:qa_mode`,U=`${S}:uid`,Ne="tlog_mode",Oe="qa",Pe="qa_off",dt=i=>i?`${S}:${i}:queue`:`${S}:queue`,ut=i=>i?`${S}:${i}:rate_limit`:`${S}:rate_limit`,mt=i=>i?`${S}:${i}:session`:`${S}:session`;var pt=i=>i?`${S}:${i}:broadcast`:`${S}:broadcast`,xe=(i,e)=>`${S}:${i}:session_counts:${e}`,De=10080*60*1e3,ke=`${S}:session_counts_last_cleanup`,Ve=3600*1e3,Z=i=>i?`${S}:${i}:identity`:`${S}:identity`,M=`${S}:pending_identity`;var ft=(t=>(t.Localhost="localhost:8080",t.Fail="localhost:9999",t))(ft||{});var ht=(n=>(n.Mobile="mobile",n.Tablet="tablet",n.Desktop="desktop",n.Unknown="unknown",n))(ht||{});var Ue=(t=>(t.EVENT="event",t.QUEUE="queue",t))(Ue||{});var R=class i extends Error{constructor(t,r,n){super(t);this.statusCode=r;this.responseCode=n;this.name="PermanentError",Error.captureStackTrace&&Error.captureStackTrace(this,i);}},H=class i extends Error{constructor(e){super(e),this.name="RateLimitError",Error.captureStackTrace&&Error.captureStackTrace(this,i);}},F=class i extends Error{constructor(e){super(e),this.name="TimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,i);}};var I=(d=>(d.PAGE_VIEW="page_view",d.CLICK="click",d.SCROLL="scroll",d.SESSION_START="session_start",d.CUSTOM="custom",d.WEB_VITALS="web_vitals",d.ERROR="error",d.VIEWPORT_VISIBLE="viewport_visible",d))(I||{}),gt=(t=>(t.UP="up",t.DOWN="down",t))(gt||{}),Et=(t=>(t.JS_ERROR="js_error",t.PROMISE_REJECTION="promise_rejection",t))(Et||{});var He=(e=>(e.QA="qa",e))(He||{});var Un=i=>i.type==="scroll"&&"scroll_data"in i&&i.scroll_data.is_primary===true,Hn=i=>i.type==="scroll"&&"scroll_data"in i&&i.scroll_data.is_primary===false;var O=class extends Error{constructor(t,r,n){super(t);this.errorCode=r;this.layer=n;this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}},p=class extends O{constructor(e,t="config"){super(e,"APP_CONFIG_INVALID",t);}},ee=class extends O{constructor(e,t="config"){super(e,"SESSION_TIMEOUT_INVALID",t);}},B=class extends O{constructor(e,t="config"){super(e,"SAMPLING_RATE_INVALID",t);}},b=class extends O{constructor(e,t="config"){super(e,"INTEGRATION_INVALID",t);}},vt=class extends O{constructor(t,r,n="runtime"){super(t,"INITIALIZATION_TIMEOUT",n);this.timeoutMs=r;}};var Fe="background: #ff9800; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;",Be="background: #9e9e9e; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;",St="background: #d32f2f; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;";var Mr=(i,e)=>{if(e){if(e instanceof Error){let t=e.message.replace(/\s+at\s+.*$/gm,"").replace(/\s*\([^()]+:\d+:\d+\)/g,"");return `[TraceLog] ${i}: ${t}`}if(e instanceof Error)return `[TraceLog] ${i}: ${e.message}`;if(typeof e=="string")return `[TraceLog] ${i}: ${e}`;if(typeof e=="object")try{return `[TraceLog] ${i}: ${JSON.stringify(e)}`}catch{return `[TraceLog] ${i}: [Unable to serialize error]`}return `[TraceLog] ${i}: ${String(e)}`}return `[TraceLog] ${i}`},Rr=()=>{if(typeof window>"u"||typeof sessionStorage>"u")return false;try{return sessionStorage.getItem(N)==="true"}catch{return false}},o=(i,e,t)=>{let{error:r,data:n,showToClient:s=false,style:a,visibility:l}=t??{},d=r?Mr(e,r):`[TraceLog] ${e}`,c=i==="error"?"error":i==="warn"?"warn":"log";if(!Lr(l,s))return;let m=Ar(l,a),g=n!==void 0?$e(n):void 0;Tt(c,d,m,g);},Lr=(i,e)=>i==="critical"?true:i==="qa"||e?Rr():false,Ar=(i,e)=>e!==void 0&&e!==""?e:i==="critical"?St:"",Tt=(i,e,t,r)=>{let n=t!==void 0&&t!=="",s=n?`%c${e}`:e;r!==void 0?n?console[i](s,t,r):console[i](s,r):n?console[i](s,t):console[i](s);},$e=i=>{let e={},t=["token","password","secret","key","apikey","api_key","sessionid","session_id"];for(let[r,n]of Object.entries(i)){let s=r.toLowerCase();if(t.some(a=>s.includes(a))){e[r]="[REDACTED]";continue}n!==null&&typeof n=="object"&&!Array.isArray(n)?e[r]=$e(n):Array.isArray(n)?e[r]=n.map(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?$e(a):a):e[r]=n;}return e};var We,yt,Cr=()=>{typeof window<"u"&&!We&&(We=window.matchMedia("(pointer: coarse)"),yt=window.matchMedia("(hover: none)"));},te="Unknown",Nr=i=>{let e=i.userAgentData?.platform;if(e!=null&&e!==""){if(/windows/i.test(e))return "Windows";if(/macos/i.test(e))return "macOS";if(/android/i.test(e))return "Android";if(/linux/i.test(e))return "Linux";if(/chromeos/i.test(e))return "ChromeOS";if(/ios/i.test(e))return "iOS"}let t=navigator.userAgent;return /Windows/i.test(t)?"Windows":/iPhone|iPad|iPod/i.test(t)?"iOS":/Mac OS X|Macintosh/i.test(t)?"macOS":/Android/i.test(t)?"Android":/CrOS/i.test(t)?"ChromeOS":/Linux/i.test(t)?"Linux":te},Or=i=>{let e=i.userAgentData?.brands;if(e!=null&&e.length>0){let n=e.filter(s=>!/not.?a.?brand|chromium/i.test(s.brand))[0];if(n!=null){let s=n.brand;return /google chrome/i.test(s)?"Chrome":/microsoft edge/i.test(s)?"Edge":/opera/i.test(s)?"Opera":s}}let t=navigator.userAgent;return /Edg\//i.test(t)?"Edge":/OPR\//i.test(t)?"Opera":/Chrome/i.test(t)?"Chrome":/Firefox/i.test(t)?"Firefox":/Safari/i.test(t)&&!/Chrome/i.test(t)?"Safari":te},Pr=()=>{try{let i=navigator;if(i.userAgentData!=null&&typeof i.userAgentData.mobile=="boolean"){let d=i.userAgentData.platform;return d!=null&&d!==""&&/ipad|tablet/i.test(d)?"tablet":i.userAgentData.mobile?"mobile":"desktop"}Cr();let e=window.innerWidth,t=We?.matches??!1,r=yt?.matches??!1,n="ontouchstart"in window||navigator.maxTouchPoints>0,s=navigator.userAgent.toLowerCase(),a=/mobile|android|iphone|ipod|blackberry|iemobile|opera mini/.test(s),l=/tablet|ipad|android(?!.*mobile)/.test(s);return e<=767||a&&n?"mobile":e>=768&&e<=1024||l||t&&r&&n?"tablet":"desktop"}catch(i){return o("debug","Device detection failed, defaulting to desktop",{error:i}),"desktop"}},_t=()=>{try{let i=navigator;return {type:Pr(),os:Nr(i),browser:Or(i)}}catch(i){return o("debug","Device info detection failed, using defaults",{error:i}),{type:"desktop",os:te,browser:te}}};var $=[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/gi,/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g,/\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/g,/\b[A-Z]{2}\d{2}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/gi,/\b[sp]k_(test|live)_[a-zA-Z0-9]{10,}\b/gi,/Bearer\s+[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?(?:\.[A-Za-z0-9_-]+)?/gi,/:\/\/[^:/]+:([^@]+)@/gi,/[?&](token|password|passwd|auth|secret|secret_key|private_key|auth_key|api_key|apikey|access_token)=[^&\s]+/gi];var xr={LCP:2500,FCP:1800,CLS:.1,INP:200,TTFB:800,LONG_TASK:50},Qe={LCP:2500,FCP:1800,CLS:.1,INP:200,TTFB:800,LONG_TASK:50},It={LCP:4e3,FCP:3e3,CLS:.25,INP:500,TTFB:1800,LONG_TASK:50},W="needs-improvement",re=(i=W)=>{switch(i){case "all":return {LCP:0,FCP:0,CLS:0,INP:0,TTFB:0,LONG_TASK:0};case "needs-improvement":return Qe;case "poor":return It;default:return Qe}},bt=1e3,wt=50;var Mt="2.9.0";var Rt=Mt;var Lt=()=>typeof window<"u"&&typeof sessionStorage<"u",kr=()=>{try{let i=new URLSearchParams(window.location.search);i.delete(Ne);let e=i.toString(),t=window.location.pathname+(e?"?"+e:"")+window.location.hash;window.history.replaceState({},"",t);}catch{}},At=()=>{if(!Lt())return false;try{let e=new URLSearchParams(window.location.search).get(Ne),t=sessionStorage.getItem(N),r=null;return e===Oe?(r=!0,sessionStorage.setItem(N,"true"),o("info","QA Mode ACTIVE",{visibility:"qa",style:Fe})):e===Pe&&(r=!1,sessionStorage.setItem(N,"false"),o("info","QA Mode DISABLED",{visibility:"qa",style:Be})),(e===Oe||e===Pe)&&kr(),r??t==="true"}catch{return false}},Ct=i=>{if(Lt())try{sessionStorage.setItem(N,i?"true":"false"),o("info",i?"QA Mode ACTIVE":"QA Mode DISABLED",{visibility:"qa",style:i?Fe:Be});}catch{o("debug","Cannot set QA mode: sessionStorage unavailable");}};var Vr=["co.uk","org.uk","com.au","net.au","com.br","co.nz","co.jp","com.mx","co.in","com.cn","co.za"],Nt=i=>{let e=i.toLowerCase().split(".");if(e.length<=2)return i.toLowerCase();let t=e.slice(-2).join(".");return Vr.includes(t)?e.slice(-3).join("."):e.slice(-2).join(".")},Ur=(i,e)=>i===e?true:Nt(i)===Nt(e),ne=()=>{let i=document.referrer;if(!i)return "Direct";try{let e=new URL(i).hostname.toLowerCase(),t=window.location.hostname.toLowerCase();return Ur(e,t)?"Direct":i}catch(e){return o("debug","Failed to parse referrer URL, using raw value",{error:e,data:{referrer:i}}),i}};var ie=()=>{let i=new URLSearchParams(window.location.search),e={};return at.forEach(r=>{let n=i.get(r);if(n){let s=r.split("utm_")[1];e[s]=n;}}),Object.keys(e).length?e:void 0};var ae=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return (i==="x"?e:e&3|8).toString(16)}),se=0,oe=0,Ot=()=>{let i=Date.now();i<oe&&(i=oe),i===oe?se=(se+1)%1e3:se=0,oe=i;let e=se.toString().padStart(3,"0"),t="";try{if(typeof crypto<"u"&&crypto.getRandomValues){let r=crypto.getRandomValues(new Uint8Array(3));r&&(t=Array.from(r,n=>n.toString(16).padStart(2,"0")).join(""));}}catch{}return t||(t=Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")),`${i}-${e}-${t}`};var Pt=(i,e=false)=>{try{let t=new URL(i),r=t.protocol==="https:",n=t.protocol==="http:";return r||e&&n}catch{return false}},Hr=i=>{try{let t=new URL(window.location.href).hostname;if(!t||typeof t!="string")throw new Error("Invalid hostname");if(t==="localhost"||t==="127.0.0.1"||/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t))throw new Error("SaaS integration not supported on localhost or IP addresses. Use custom backend integration instead.");let r=t.split(".");if(!r||!Array.isArray(r)||r.length===0||r.length===1&&r[0]==="")throw new Error("Invalid hostname structure");if(r.length===1)throw new Error("Single-part domain not supported for SaaS integration");let n;if(r.length===2?n=r.join("."):n=r.slice(-2).join("."),!n||n.split(".").length<2)throw new Error("Invalid domain structure for SaaS");let s=`https://${i}.${n}/collect`;if(!Pt(s))throw new Error("Generated URL failed validation");return s}catch(e){throw new Error(`Invalid SaaS URL configuration: ${e instanceof Error?e.message:String(e)}`)}},xt=i=>{let e={};i.integrations?.tracelog?.projectId&&(e.saas=Hr(i.integrations.tracelog.projectId));let t=i.integrations?.custom?.collectApiUrl;if(t){let r=i.integrations?.custom?.allowHttp??false;if(!Pt(t,r))throw new Error("Invalid custom API URL");e.custom=t;}return e},Q=(i,e=[])=>{if(!i||typeof i!="string")return o("warn","Invalid URL provided to normalizeUrl",{data:{type:typeof i}}),i||"";try{let t=new URL(i),r=t.searchParams,n=[...new Set([...lt,...e])],s=!1,a=[];return n.forEach(d=>{r.has(d)&&(r.delete(d),s=!0,a.push(d));}),!s&&i.includes("?")?i:(t.search=r.toString(),t.toString())}catch(t){return o("warn","URL normalization failed, returning original",{error:t,data:{urlLength:i?.length}}),i}};var Dt=i=>{if(!i||typeof i!="string"||i.trim().length===0)return "";let e=i;i.length>1e3&&(e=i.slice(0,Math.max(0,1e3)));let t=0;for(let n of ct){let s=e;e=e.replace(n,""),s!==e&&t++;}return t>0&&o("warn","XSS patterns detected and removed",{data:{patternMatches:t,valueLength:i.length}}),e.trim()},je=(i,e=0)=>{if(i==null)return null;if(typeof i=="string")return Dt(i);if(typeof i=="number")return !Number.isFinite(i)||i<-Number.MAX_SAFE_INTEGER||i>Number.MAX_SAFE_INTEGER?0:i;if(typeof i=="boolean")return i;if(e>10)return null;if(Array.isArray(i))return i.slice(0,1e3).map(n=>je(n,e+1)).filter(n=>n!==null);if(typeof i=="object"){let t={},n=Object.entries(i).slice(0,200);for(let[s,a]of n){let l=Dt(s);if(l){let d=je(a,e+1);d!==null&&(t[l]=d);}}return t}return null},kt=i=>{if(typeof i!="object"||i===null)return {};try{let e=je(i);return typeof e=="object"&&e!==null?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);throw new Error(`[TraceLog] Metadata sanitization failed: ${t}`)}};var Gr=i=>{if(i!==void 0&&(i===null||typeof i!="object"))throw new p("Configuration must be an object","config");if(i){if(i.sessionTimeout!==void 0&&(typeof i.sessionTimeout!="number"||i.sessionTimeout<3e4||i.sessionTimeout>864e5))throw new ee(v.INVALID_SESSION_TIMEOUT,"config");if(i.globalMetadata!==void 0&&(typeof i.globalMetadata!="object"||i.globalMetadata===null))throw new p(v.INVALID_GLOBAL_METADATA,"config");if(i.integrations&&zr(i.integrations),i.sensitiveQueryParams!==void 0){if(!Array.isArray(i.sensitiveQueryParams))throw new p(v.INVALID_SENSITIVE_QUERY_PARAMS,"config");for(let e of i.sensitiveQueryParams)if(typeof e!="string")throw new p("All sensitive query params must be strings","config")}if(i.errorSampling!==void 0&&(typeof i.errorSampling!="number"||i.errorSampling<0||i.errorSampling>1))throw new B(v.INVALID_ERROR_SAMPLING_RATE,"config");if(i.samplingRate!==void 0&&(typeof i.samplingRate!="number"||i.samplingRate<0||i.samplingRate>1))throw new B(v.INVALID_SAMPLING_RATE,"config");if(i.primaryScrollSelector!==void 0){if(typeof i.primaryScrollSelector!="string"||!i.primaryScrollSelector.trim())throw new p(v.INVALID_PRIMARY_SCROLL_SELECTOR,"config");if(i.primaryScrollSelector!=="window")try{document.querySelector(i.primaryScrollSelector);}catch{throw new p(`${v.INVALID_PRIMARY_SCROLL_SELECTOR_SYNTAX}: "${i.primaryScrollSelector}"`,"config")}}if(i.pageViewThrottleMs!==void 0&&(typeof i.pageViewThrottleMs!="number"||i.pageViewThrottleMs<0))throw new p(v.INVALID_PAGE_VIEW_THROTTLE,"config");if(i.clickThrottleMs!==void 0&&(typeof i.clickThrottleMs!="number"||i.clickThrottleMs<0))throw new p(v.INVALID_CLICK_THROTTLE,"config");if(i.maxSameEventPerMinute!==void 0&&(typeof i.maxSameEventPerMinute!="number"||i.maxSameEventPerMinute<=0))throw new p(v.INVALID_MAX_SAME_EVENT_PER_MINUTE,"config");if(i.sendIntervalMs!==void 0&&(!Number.isFinite(i.sendIntervalMs)||i.sendIntervalMs<1e3||i.sendIntervalMs>6e4))throw new p(v.INVALID_SEND_INTERVAL,"config");if(i.flushOnSpaNavigation!==void 0&&typeof i.flushOnSpaNavigation!="boolean")throw new p(`Invalid flushOnSpaNavigation type: ${typeof i.flushOnSpaNavigation}. Must be a boolean`,"config");if(i.flushOnPageHidden!==void 0&&typeof i.flushOnPageHidden!="boolean")throw new p(`Invalid flushOnPageHidden type: ${typeof i.flushOnPageHidden}. Must be a boolean`,"config");if(i.viewport!==void 0&&Xr(i.viewport),i.webVitalsMode!==void 0){if(typeof i.webVitalsMode!="string")throw new p(`Invalid webVitalsMode type: ${typeof i.webVitalsMode}. Must be a string`,"config");let e=["all","needs-improvement","poor"];if(!e.includes(i.webVitalsMode))throw new p(`Invalid webVitalsMode: "${i.webVitalsMode}". Must be one of: ${e.join(", ")}`,"config")}if(i.webVitalsThresholds!==void 0){if(typeof i.webVitalsThresholds!="object"||i.webVitalsThresholds===null||Array.isArray(i.webVitalsThresholds))throw new p("webVitalsThresholds must be an object","config");let e=["LCP","FCP","CLS","INP","TTFB","LONG_TASK"];for(let[t,r]of Object.entries(i.webVitalsThresholds)){if(!e.includes(t))throw new p(`Invalid Web Vitals threshold key: "${t}". Must be one of: ${e.join(", ")}`,"config");if(typeof r!="number"||!Number.isFinite(r)||r<0)throw new p(`Invalid Web Vitals threshold value for ${t}: ${r}. Must be a non-negative finite number`,"config")}}}},Xr=i=>{if(typeof i!="object"||i===null)throw new p(v.INVALID_VIEWPORT_CONFIG,"config");if(!i.elements||!Array.isArray(i.elements))throw new p(v.INVALID_VIEWPORT_ELEMENTS,"config");if(i.elements.length===0)throw new p(v.INVALID_VIEWPORT_ELEMENTS,"config");let e=new Set;for(let t of i.elements){if(!t.selector||typeof t.selector!="string"||!t.selector.trim())throw new p(v.INVALID_VIEWPORT_ELEMENT,"config");let r=t.selector.trim();if(e.has(r))throw new p(`Duplicate viewport selector found: "${r}". Each selector should appear only once.`,"config");if(e.add(r),t.id!==void 0&&(typeof t.id!="string"||!t.id.trim()))throw new p(v.INVALID_VIEWPORT_ELEMENT_ID,"config");if(t.name!==void 0&&(typeof t.name!="string"||!t.name.trim()))throw new p(v.INVALID_VIEWPORT_ELEMENT_NAME,"config")}if(i.threshold!==void 0&&(typeof i.threshold!="number"||i.threshold<0||i.threshold>1))throw new p(v.INVALID_VIEWPORT_THRESHOLD,"config");if(i.minDwellTime!==void 0&&(typeof i.minDwellTime!="number"||i.minDwellTime<0))throw new p(v.INVALID_VIEWPORT_MIN_DWELL_TIME,"config");if(i.cooldownPeriod!==void 0&&(typeof i.cooldownPeriod!="number"||i.cooldownPeriod<0))throw new p(v.INVALID_VIEWPORT_COOLDOWN_PERIOD,"config");if(i.maxTrackedElements!==void 0&&(typeof i.maxTrackedElements!="number"||i.maxTrackedElements<=0))throw new p(v.INVALID_VIEWPORT_MAX_TRACKED_ELEMENTS,"config")},zr=i=>{if(i){if(i.tracelog&&(!i.tracelog.projectId||typeof i.tracelog.projectId!="string"||i.tracelog.projectId.trim()===""))throw new b(v.INVALID_TRACELOG_PROJECT_ID,"config");if(i.custom){if(!i.custom.collectApiUrl||typeof i.custom.collectApiUrl!="string"||i.custom.collectApiUrl.trim()==="")throw new b(v.INVALID_CUSTOM_API_URL,"config");if(i.custom.allowHttp!==void 0&&typeof i.custom.allowHttp!="boolean")throw new b("allowHttp must be a boolean","config");let e=i.custom.collectApiUrl.trim();if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new b('Custom API URL must start with "http://" or "https://"',"config");if(!(i.custom.allowHttp??false)&&e.startsWith("http://"))throw new b("Custom API URL must use HTTPS in production. Set allowHttp: true in integration config to allow HTTP (not recommended)","config");if(i.custom.fetchCredentials!==void 0&&!["include","same-origin","omit"].includes(i.custom.fetchCredentials))throw new b('fetchCredentials must be "include", "same-origin", or "omit"',"config")}if(i.tracelog?.shopify!==void 0&&typeof i.tracelog.shopify!="boolean")throw new b("tracelog.shopify must be a boolean","config")}},Vt=i=>{Gr(i);let e={...i??{},sessionTimeout:i?.sessionTimeout??9e5,globalMetadata:i?.globalMetadata??{},sensitiveQueryParams:i?.sensitiveQueryParams??[],errorSampling:i?.errorSampling??1,samplingRate:i?.samplingRate??1,pageViewThrottleMs:i?.pageViewThrottleMs??1e3,clickThrottleMs:i?.clickThrottleMs??300,maxSameEventPerMinute:i?.maxSameEventPerMinute??60,sendIntervalMs:i?.sendIntervalMs??1e4,flushOnSpaNavigation:i?.flushOnSpaNavigation??false,flushOnPageHidden:i?.flushOnPageHidden??true};return e.integrations?.custom&&(e.integrations.custom={...e.integrations.custom,allowHttp:e.integrations.custom.allowHttp??false}),e.viewport&&(e.viewport={...e.viewport,threshold:e.viewport.threshold??.5,minDwellTime:e.viewport.minDwellTime??2e3,cooldownPeriod:e.viewport.cooldownPeriod??6e4,maxTrackedElements:e.viewport.maxTrackedElements??100}),e};var Ze=(i,e=new Set)=>{if(i==null)return true;let t=typeof i;return t==="string"||t==="number"||t==="boolean"?true:t==="function"||t==="symbol"||t==="bigint"||e.has(i)?false:(e.add(i),Array.isArray(i)?i.every(r=>Ze(r,e)):t==="object"?Object.values(i).every(r=>Ze(r,e)):false)},Ut=i=>typeof i!="object"||i===null?false:Ze(i),le=i=>{if(typeof i!="object"||i===null||Array.isArray(i))return;let e={};for(let[t,r]of Object.entries(i))typeof r=="string"&&(e[t]=r);return Object.keys(e).length>0?e:void 0};var Ft=i=>typeof i!="string"?{valid:false,error:"Event name must be a string"}:i.length===0?{valid:false,error:"Event name cannot be empty"}:i.length>120?{valid:false,error:`Event name is too long (max ${120} characters)`}:i.includes("<")||i.includes(">")||i.includes("&")?{valid:false,error:"Event name contains invalid characters"}:["constructor","prototype","__proto__","eval","function","var","let","const"].includes(i.toLowerCase())?{valid:false,error:"Event name cannot be a reserved word"}:{valid:true},Ht=(i,e,t)=>{let r=kt(e),n=t&&t==="customEvent"?`${t} "${i}" metadata error`:`${i} metadata error`;if(!Ut(r))return {valid:false,error:`${n}: object has invalid types. Valid types are string, number, boolean or string arrays.`};let s;try{s=JSON.stringify(r);}catch{return {valid:false,error:`${n}: object contains circular references or cannot be serialized.`}}if(new TextEncoder().encode(s).byteLength>49152)return {valid:false,error:`${n}: object is too large (max ${49152/1024} KB).`};if(Object.keys(r).length>100)return {valid:false,error:`${n}: object has too many keys (max ${100} keys).`};for(let[d,c]of Object.entries(r)){if(Array.isArray(c)){if(c.length>500)return {valid:false,error:`${n}: array property "${d}" is too large (max ${500} items).`};for(let f of c)if(typeof f=="string"&&f.length>500)return {valid:false,error:`${n}: array property "${d}" contains strings that are too long (max ${500} characters).`}}if(typeof c=="string"&&c.length>1e3)return {valid:false,error:`${n}: property "${d}" is too long (max ${1e3} characters).`}}return {valid:true,sanitizedMetadata:r}},ce=(i,e,t)=>{if(Array.isArray(e)){let r=[],n=t&&t==="customEvent"?`${t} "${i}" metadata error`:`${i} metadata error`;for(let s=0;s<e.length;s++){let a=e[s];if(typeof a!="object"||a===null||Array.isArray(a))return {valid:false,error:`${n}: array item at index ${s} must be an object.`};let l=Ht(i,a,t);if(!l.valid)return {valid:false,error:`${n}: array item at index ${s} is invalid: ${l.error}`};l.sanitizedMetadata&&r.push(l.sanitizedMetadata);}return {valid:true,sanitizedMetadata:r}}return Ht(i,e,t)};var Bt=(i,e)=>{let t=Ft(i);if(!t.valid)return o("error","Event name validation failed",{data:{eventName:i,error:t.error}}),t;if(!e)return {valid:true};let r=ce(i,e,"customEvent");return r.valid||o("error","Event metadata validation failed",{data:{eventName:i,error:r.error}}),r};var de=class{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);}off(e,t){let r=this.listeners.get(e);if(r){let n=r.indexOf(t);n>-1&&r.splice(n,1);}}emit(e,t){let r=this.listeners.get(e);r&&r.forEach(n=>{n(t);});}removeAllListeners(){this.listeners.clear();}};function et(i,e,t){try{let r=e(i);return r===null?null:typeof r=="object"&&r!==null&&"type"in r?r:(o("warn",`beforeSend transformer returned invalid data, using original [${t}]`),i)}catch(r){return o("error",`beforeSend transformer threw error, using original event [${t}]`,{error:r,visibility:"critical"}),i}}function $t(i,e,t){return i.map(r=>et(r,e,t)).filter(r=>r!==null)}function ue(i,e,t){try{let r=e(i);return r===null?(o("debug",`Batch filtered by beforeBatch transformer [${t}]`,{data:{eventCount:i.events.length}}),null):typeof r=="object"&&r!==null&&Array.isArray(r.events)?r:(o("warn",`beforeBatch transformer returned invalid data, using original [${t}]`,{data:{eventCount:i.events.length}}),i)}catch(r){return o("error",`beforeBatch transformer threw error, using original batch [${t}]`,{error:r,data:{eventCount:i.events.length},visibility:"critical"}),i}}var tt={config:{}};var h=class{get(e){return tt[e]}set(e,t){tt[e]=t;}getState(){return {...tt}}};var j=class extends h{storeManager;integrationId;apiUrl;transformers;staticHeaders;customHeadersProvider;lastPermanentErrorLog=null;recoveryInProgress=false;lastMetadataTimestamp=0;fetchCredentials;pendingControllers=new Set;consecutiveNetworkFailures=0;circuitOpenedAt=0;rateLimitedUntil=0;rateLimitStorageKeyAtArm=null;constructor(e,t,r,n={},s={},a,l="include"){if(super(),t&&!r||!t&&r)throw new Error("SenderManager: integrationId and apiUrl must either both be provided or both be undefined");this.storeManager=e,this.integrationId=t,this.apiUrl=r,this.transformers=n,this.staticHeaders=s,this.customHeadersProvider=a,this.fetchCredentials=l,this.rateLimitedUntil=this.loadRateLimitCooldown();}getIntegrationId(){return this.integrationId}setCustomHeadersProvider(e){this.customHeadersProvider=e;}removeCustomHeadersProvider(){this.customHeadersProvider=void 0;}getCustomHeaders(){if(this.integrationId!=="custom")return {};let e={};if(this.customHeadersProvider)try{let t=this.customHeadersProvider();typeof t=="object"&&t!==null&&!Array.isArray(t)?e=t:o("warn","Custom headers provider returned invalid value, expected object",{data:{received:typeof t}});}catch(t){o("warn","Custom headers provider threw an error, using static headers only",{error:t});}return {...this.staticHeaders,...e}}getQueueStorageKey(){let e=this.get("userId")||"anonymous",t=dt(e);return this.integrationId?`${t}:${this.integrationId}`:t}getRateLimitStorageKey(){let e=this.get("userId")||"anonymous",t=ut(e);return this.integrationId?`${t}:${this.integrationId}`:t}getActiveRateLimitKey(){return this.rateLimitStorageKeyAtArm??this.getRateLimitStorageKey()}armRateLimitCooldown(e){this.rateLimitedUntil=e,this.rateLimitStorageKeyAtArm=this.getRateLimitStorageKey(),this.persistRateLimitCooldown(e);}loadRateLimitCooldown(){let e=this.getRateLimitStorageKey();try{let t=this.storeManager.getItem(e);if(!t)return 0;let r=Number(t);return !Number.isFinite(r)||r<=Date.now()?(this.storeManager.removeItem(e),0):(this.rateLimitStorageKeyAtArm=e,r)}catch{return 0}}persistRateLimitCooldown(e){let t=this.getActiveRateLimitKey();try{let r=this.storeManager.getItem(t);if(r){let n=Number(r);if(Number.isFinite(n)&&n>=e)return}this.storeManager.setItem(t,String(e));}catch{}}clearRateLimitCooldown(){let e=this.getActiveRateLimitKey();try{let t=this.storeManager.getItem(e);if(t){let r=Number(t);if(Number.isFinite(r)&&r>Date.now()){this.rateLimitedUntil=r;return}}this.storeManager.removeItem(e);}catch{}this.rateLimitedUntil=0,this.rateLimitStorageKeyAtArm=null;}isRateLimited(){return this.rateLimitedUntil===0&&(this.rateLimitedUntil=this.loadRateLimitCooldown()),!(this.rateLimitedUntil===0||Date.now()>=this.rateLimitedUntil&&(this.clearRateLimitCooldown(),this.rateLimitedUntil===0))}sendEventsQueueSync(e){if(this.shouldSkipSend())return true;if(this.isRateLimited()){o("debug",`Rate-limit cooldown active, skipping sync send${this.integrationId?` [${this.integrationId}]`:""}`,{data:{cooldownRemainingMs:this.rateLimitedUntil-Date.now(),events:e.events.length}});let t=this.ensureBatchMetadata(e),r=this.getPersistedData(),n=typeof r?.recoveryFailures=="number"&&Number.isFinite(r.recoveryFailures)?r.recoveryFailures:0;return this.persistEventsWithFailureCount(t,n,true),false}return this.apiUrl?.includes("localhost:9999")?(o("warn",`Fail mode: simulating network failure (sync)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length}}),false):this.apiUrl?.includes("localhost:8080")?(o("debug",`Success mode: simulating successful send (sync)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length}}),true):this.sendQueueSyncInternal(e)}async sendEventsQueue(e,t){let r=this.ensureBatchMetadata(e);try{let n=await this.send(r);return n?(this.clearPersistedEvents(),t?.onSuccess?.(r.events.length,r.events,r)):(this.persistEvents(r),t?.onFailure?.()),n}catch(n){return n instanceof R?(this.logPermanentError("Permanent error, not retrying",n),this.clearPersistedEvents(),t?.onFailure?.(),false):(this.persistEvents(r),t?.onFailure?.(),false)}}async recoverPersistedEvents(e){if(this.recoveryInProgress){o("debug","Recovery already in progress, skipping duplicate attempt");return}this.recoveryInProgress=true;let t=null,r=0;try{let n=this.getPersistedData();if(!n||!this.isDataRecent(n)||n.events.length===0){this.clearPersistedEvents();return}let s=n.recoveryFailures;if(r=typeof s=="number"&&Number.isFinite(s)&&s>=0?s:0,r>=3){o("debug",`Discarding persisted events after ${r} failed recovery attempts${this.integrationId?` [${this.integrationId}]`:""}`),this.clearPersistedEvents(),e?.onFailure?.();return}if(this.isRateLimited()){o("debug",`Rate-limit cooldown active, deferring recovery${this.integrationId?` [${this.integrationId}]`:""}`,{data:{cooldownRemainingMs:this.rateLimitedUntil-Date.now()}}),e?.onFailure?.();return}t=this.ensureBatchMetadata(this.createRecoveryBody(n)),await this.send(t)?(this.clearPersistedEvents(),e?.onSuccess?.(n.events.length,n.events,t)):(this.persistEventsWithFailureCount(t,r+1,!0),e?.onFailure?.());}catch(n){if(n instanceof R){this.logPermanentError("Permanent error during recovery, clearing persisted events",n),this.clearPersistedEvents(),e?.onFailure?.();return}o("error","Failed to recover persisted events",{error:n}),t&&this.persistEventsWithFailureCount(t,r+1,true),e?.onFailure?.();}finally{this.recoveryInProgress=false;}}stop(){}applyBeforeSendTransformer(e){if(this.integrationId==="saas")return e;let t=this.transformers.beforeSend;if(!t)return e;let r=$t(e.events,t,this.integrationId||"SenderManager");return r.length===0?null:{...e,events:r}}applyBeforeBatchTransformer(e){if(this.integrationId==="saas")return e;let t=this.transformers.beforeBatch;return t?ue(e,t,this.integrationId||"SenderManager"):e}async backoffDelay(e){let t=100*Math.pow(2,e),r=Math.random()*100,n=t+r;return new Promise(s=>setTimeout(s,n))}async send(e){if(this.shouldSkipSend())return this.simulateSuccessfulSend();let t=this.applyBeforeSendTransformer(e);if(!t)return true;let r=this.applyBeforeBatchTransformer(t);if(!r)return true;let n=this.ensureBatchMetadata(r,e._metadata?.idempotency_token);if(this.apiUrl?.includes("localhost:9999"))return o("debug",`Fail mode: simulating network failure${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:n.events.length}}),false;if(this.apiUrl?.includes("localhost:8080"))return o("debug",`Success mode: simulating successful send${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:n.events.length}}),true;if(this.isRateLimited())return o("debug",`Rate-limit cooldown active, skipping send${this.integrationId?` [${this.integrationId}]`:""}`,{data:{cooldownRemainingMs:this.rateLimitedUntil-Date.now(),events:n.events.length}}),false;if(this.consecutiveNetworkFailures>=3){let c=Date.now()-this.circuitOpenedAt;if(c<12e4)return o("debug",`Network circuit open, skipping send${this.integrationId?` [${this.integrationId}]`:""}`,{data:{consecutiveNetworkFailures:this.consecutiveNetworkFailures,cooldownRemainingMs:12e4-c}}),false}let{url:s,payload:a}=this.prepareRequest(n),l=true,d=false;for(let c=1;c<=3;c++)try{return (await this.sendWithTimeout(s,a)).ok?(c>1&&o("info",`Send succeeded after ${c-1} retry attempt(s)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:n.events.length,attempt:c}}),this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0,!0):!1}catch(f){let E=c===3;if(f instanceof R)throw this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0,f;if(f instanceof H){this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0,l=false,d=true,this.armRateLimitCooldown(Date.now()+6e4),o("warn",`Rate limited, skipping retries${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length,attempt:c,cooldownMs:6e4}});break}if(f instanceof F||(l=false),f instanceof TypeError||(d=true),o(E?"error":"warn",`Send attempt ${c} failed${this.integrationId?` [${this.integrationId}]`:""}${E?" (all retries exhausted)":", will retry"}`,{error:f,data:{events:e.events.length,url:s.replace(/\/\/[^/]+/,"//[DOMAIN]"),attempt:c,maxAttempts:3}}),!E){await this.backoffDelay(c);continue}return l?(o("debug",`All retry attempts timed out, preserving batch for retry${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:n.events.length}}),false):(d?(this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0):(this.consecutiveNetworkFailures=Math.min(this.consecutiveNetworkFailures+1,3),this.consecutiveNetworkFailures>=3&&(this.circuitOpenedAt=Date.now())),false)}return false}async sendWithTimeout(e,t){let r=new AbortController;this.pendingControllers.add(r);let n=false,s=setTimeout(()=>{n=true,r.abort();},15e3);try{let a=this.getCustomHeaders(),l=await fetch(e,{method:"POST",body:t,keepalive:!0,credentials:this.fetchCredentials,signal:r.signal,headers:{...a,"Content-Type":"application/json"}});if(!l.ok){if(l.status>=400&&l.status<500&&l.status!==408&&l.status!==429){let c=await this.readTraceLogErrorCode(l),f=c?`HTTP ${l.status}: ${l.statusText} (${c})`:`HTTP ${l.status}: ${l.statusText}`;throw new R(f,l.status,c)}throw l.status===429?new H(`HTTP 429: ${l.statusText}`):new Error(`HTTP ${l.status}: ${l.statusText}`)}return l}catch(a){throw a instanceof R?a:n?new F("Request timed out"):a}finally{clearTimeout(s),this.pendingControllers.delete(r);}}async readTraceLogErrorCode(e){try{let t=await e.clone().json();if(typeof t.code=="string"&&t.code.length>0&&t.code.length<=64)return t.code}catch{}}sendQueueSyncInternal(e){let t=this.ensureBatchMetadata(e),r=this.applyBeforeSendTransformer(t);if(!r)return true;let n=this.applyBeforeBatchTransformer(r);if(!n)return true;let s=this.ensureBatchMetadata(n,t._metadata?.idempotency_token),{url:a,payload:l}=this.prepareRequest(s);if(l.length>65536)return o("warn",`Payload exceeds sendBeacon limit, persisting for recovery${this.integrationId?` [${this.integrationId}]`:""}`,{data:{size:l.length,limit:65536,events:s.events.length}}),this.persistEvents(t),false;let d=new Blob([l],{type:"application/json"});if(!this.isSendBeaconAvailable())return o("warn",`sendBeacon not available, persisting events for recovery${this.integrationId?` [${this.integrationId}]`:""}`),this.persistEvents(t),false;let c=navigator.sendBeacon(a,d);return c||(o("warn",`sendBeacon rejected request, persisting events for recovery${this.integrationId?` [${this.integrationId}]`:""}`),this.persistEvents(t)),c}prepareRequest(e){let t=Date.now();t<this.lastMetadataTimestamp&&(t=this.lastMetadataTimestamp),this.lastMetadataTimestamp=t;let r={...e,_metadata:{...e._metadata,idempotency_token:e._metadata?.idempotency_token??this.computeContentToken(e),referer:typeof window<"u"?window.location.href:void 0,timestamp:t,client_version:Rt}};return {url:this.apiUrl||"",payload:JSON.stringify(r)}}ensureBatchMetadata(e,t){let r=e._metadata?.idempotency_token??t??this.computeContentToken(e);return e._metadata?.idempotency_token===r?e:{...e,_metadata:{...e._metadata,idempotency_token:r}}}computeContentToken(e){let t=e.events.map(s=>s.id).sort().join(","),r=`${e.user_id}|${e.session_id}|${t}`,n=2166136261;for(let s=0;s<r.length;s++)n^=r.charCodeAt(s),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")}getPersistedData(){try{let e=this.getQueueStorageKey(),t=this.storeManager.getItem(e);if(t)return JSON.parse(t)}catch(e){o("debug",`Failed to parse persisted data${this.integrationId?` [${this.integrationId}]`:""}`,{error:e}),this.clearPersistedEvents();}return null}isDataRecent(e){return !e.timestamp||typeof e.timestamp!="number"?false:(Date.now()-e.timestamp)/(1e3*60*60)<2}createRecoveryBody(e){let{timestamp:t,recoveryFailures:r,...n}=e;return n}persistEvents(e){let t=this.getPersistedData(),r=typeof t?.recoveryFailures=="number"&&Number.isFinite(t.recoveryFailures)?t.recoveryFailures:0;return this.persistEventsWithFailureCount(e,r)}persistEventsWithFailureCount(e,t,r=false){try{let n=this.getPersistedData();if(!r&&n&&n.timestamp){let l=Date.now()-n.timestamp;if(l<1e3)return o("debug",`Skipping persistence, another tab recently persisted events${this.integrationId?` [${this.integrationId}]`:""}`,{data:{timeSinceExisting:l}}),!0}let s={...e,timestamp:Date.now(),...t>0&&{recoveryFailures:t}},a=this.getQueueStorageKey();return this.storeManager.setItem(a,JSON.stringify(s)),!!this.storeManager.getItem(a)}catch(n){return o("debug",`Failed to persist events${this.integrationId?` [${this.integrationId}]`:""}`,{error:n}),false}}clearPersistedEvents(){try{let e=this.getQueueStorageKey();this.storeManager.removeItem(e);}catch(e){o("debug",`Failed to clear persisted events${this.integrationId?` [${this.integrationId}]`:""}`,{error:e});}}shouldSkipSend(){return !this.apiUrl}async simulateSuccessfulSend(){let e=Math.random()*400+100;return await new Promise(t=>setTimeout(t,e)),true}isSendBeaconAvailable(){return typeof navigator<"u"&&typeof navigator.sendBeacon=="function"}logPermanentError(e,t){let r=Date.now(),n=`${t.statusCode??"unknown"}:${t.responseCode??""}`;(!this.lastPermanentErrorLog||this.lastPermanentErrorLog.key!==n||r-this.lastPermanentErrorLog.timestamp>=6e4)&&(o("error",`${e}${this.integrationId?` [${this.integrationId}]`:""}`,{data:{status:t.statusCode,code:t.responseCode,message:t.message}}),this.lastPermanentErrorLog={key:n,timestamp:r});}};var me=class extends h{bootTime;bootTimestamp;hasPerformanceNow;lastClockSkewCheck=0;detectedSkew=0;constructor(){if(super(),typeof window>"u"){this.hasPerformanceNow=false,this.bootTime=0,this.bootTimestamp=0;return}this.hasPerformanceNow=typeof performance<"u"&&typeof performance.now=="function",this.hasPerformanceNow?(this.bootTime=performance.now(),this.bootTimestamp=Date.now(),o("debug","TimeManager initialized with monotonic clock",{data:{bootTime:this.bootTime.toFixed(3),bootTimestamp:this.bootTimestamp}})):(this.bootTime=0,this.bootTimestamp=Date.now(),o("debug","performance.now() not available, falling back to Date.now()"));}now(){if(!this.hasPerformanceNow)return Date.now();let e=performance.now()-this.bootTime;return Math.round(this.bootTimestamp+e)}getClockSkew(){if(!this.hasPerformanceNow)return 0;let e=Date.now();if(e-this.lastClockSkewCheck<5e3)return this.detectedSkew;this.lastClockSkewCheck=e;let t=this.now(),r=Date.now();return this.detectedSkew=r-t,Math.abs(this.detectedSkew)>3e4&&o("warn","Significant clock skew detected",{data:{skewMs:this.detectedSkew,skewMinutes:(this.detectedSkew/1e3/60).toFixed(2),monotonicTime:new Date(t).toISOString(),systemTime:new Date(r).toISOString()}}),this.detectedSkew}validateTimestamp(e){let r=this.now(),n=e-r;return n>12e4?{valid:false,error:`Timestamp is ${(n/1e3/60).toFixed(2)} minutes in the future (max allowed: 2 minutes)`}:{valid:true}}getBootInfo(){return {bootTime:this.bootTime,bootTimestamp:this.bootTimestamp,hasPerformanceNow:this.hasPerformanceNow,clockSkew:this.getClockSkew()}}};var hn=new Set(Object.values(I)),pe=class extends h{dataSenders;emitter;transformers;timeManager;recentEventFingerprints=new Map;perEventRateLimits=new Map;eventsQueue=[];pendingEventsBuffer=[];sendTimeoutId=null;sendInProgress=false;consecutiveSendFailures=0;rateLimitCounter=0;rateLimitWindowStart=0;lastSessionId=null;pendingSyncFlush=false;sessionEventCounts={total:0,click:0,page_view:0,custom:0,viewport_visible:0,scroll:0};saveSessionCountsDebounced=null;constructor(e,t=null,r={},n={},s,a="include"){super(),this.emitter=t,this.transformers=r,this.timeManager=new me,this.dataSenders=[];let l=this.get("collectApiUrls");l?.saas&&this.dataSenders.push(new j(e,"saas",l.saas,r)),l?.custom&&this.dataSenders.push(new j(e,"custom",l.custom,r,n,s,a)),this.saveSessionCountsDebounced=this.debounce(d=>{this.saveSessionCounts(d);},500),this.cleanupExpiredSessionCounts();}async recoverPersistedEvents(){let e=this.dataSenders.map(async t=>t.recoverPersistedEvents({onSuccess:(r,n,s)=>{if(n&&n.length>0){let a=n.map(l=>l.id);this.removeProcessedEvents(a),s&&this.emitEventsQueue(s);}},onFailure:()=>{o("debug","Failed to recover persisted events");}}));await Promise.allSettled(e);}track({type:e,page_url:t,from_page_url:r,scroll_data:n,click_data:s,custom_event:a,web_vitals:l,error_data:d,viewport_data:c,page_view:f}){if(!e){o("error","Event type is required - event will be ignored");return}if(!hn.has(e)){o("error","Invalid event type - event will be ignored",{data:{type:e}});return}let E=this.get("sessionId");if(!E){this.pendingEventsBuffer.length>=100&&(this.pendingEventsBuffer.shift(),o("debug","Pending events buffer full - dropping oldest event",{data:{maxBufferSize:100}})),this.pendingEventsBuffer.push({type:e,page_url:t,from_page_url:r,scroll_data:n,click_data:s,custom_event:a,web_vitals:l,error_data:d,viewport_data:c,page_view:f});return}this.lastSessionId!==E&&(this.lastSessionId=E,this.sessionEventCounts=this.loadSessionCounts(E));let m=e==="session_start";if(m&&o("debug","Processing SESSION_START event",{data:{sessionId:E}}),!m&&!this.checkRateLimit())return;let g=e;if(!m){if(this.sessionEventCounts.total>=1e3){o("warn","Session event limit reached",{data:{type:g,total:this.sessionEventCounts.total,limit:1e3}});return}let y=this.getTypeLimitForEvent(g);if(y){let Le=this.sessionEventCounts[g];if(Le!==void 0&&Le>=y){o("warn","Session event type limit reached",{data:{type:g,count:Le,limit:y}});return}}}if(g==="custom"&&a?.name){let y=this.get("config")?.maxSameEventPerMinute??60;if(!this.checkPerEventRateLimit(a.name,y))return}let Re=g==="session_start",G=t||this.get("pageUrl"),V=this.buildEventPayload({type:g,page_url:G,from_page_url:r,scroll_data:n,click_data:s,custom_event:a,web_vitals:l,error_data:d,viewport_data:c,page_view:f});if(V&&!(!m&&!this.shouldSample())){if(Re){let y=this.get("sessionId");if(!y){o("error","Session start event requires sessionId - event will be ignored");return}if(this.get("hasStartSession")){o("debug","Duplicate session_start detected",{data:{sessionId:y}});return}this.set("hasStartSession",true);}if(!this.isDuplicateEvent(V)){if(this.get("mode")==="qa"){if(g==="custom"&&a){o("info",`Custom Event: ${a.name}`,{visibility:"qa",data:{name:a.name,...a.metadata&&{metadata:a.metadata}}}),this.emitEvent(V);return}if(g==="viewport_visible"&&c){let y=c.name||c.id||c.selector;o("info",`Viewport Visible: ${y}`,{visibility:"qa",data:{selector:c.selector,...c.name&&{name:c.name},...c.id&&{id:c.id},visibilityRatio:c.visibilityRatio,dwellTime:c.dwellTime}}),this.emitEvent(V);return}}if(this.addToQueue(V),!m){this.sessionEventCounts.total++,this.sessionEventCounts[g]!==void 0&&this.sessionEventCounts[g]++;let y=this.get("sessionId");y&&this.saveSessionCountsDebounced&&this.saveSessionCountsDebounced(y);}}}}stop(){this.clearSendTimeout(),this.sendInProgress=false,this.pendingSyncFlush=false,this.consecutiveSendFailures=0;let e=this.get("sessionId");e&&this.saveSessionCounts(e),this.eventsQueue=[],this.pendingEventsBuffer=[],this.recentEventFingerprints.clear(),this.rateLimitCounter=0,this.rateLimitWindowStart=0,this.perEventRateLimits.clear(),this.sessionEventCounts={total:0,click:0,page_view:0,custom:0,viewport_visible:0,scroll:0},this.lastSessionId=null,this.set("hasStartSession",false),this.dataSenders.forEach(t=>{t.stop();});}async flushImmediately(){return this.flushEvents(false)}flushImmediatelySync(){return this.flushEvents(true)}setCustomHeadersProvider(e){for(let t of this.dataSenders)t.getIntegrationId()==="custom"&&t.setCustomHeadersProvider(e);}removeCustomHeadersProvider(){for(let e of this.dataSenders)e.getIntegrationId()==="custom"&&e.removeCustomHeadersProvider();}getQueueLength(){return this.eventsQueue.length}getQueueEvents(){return this.eventsQueue.map(({_session_id:e,...t})=>t)}async flushQueue(){await this.flushImmediately();}clearQueue(){this.eventsQueue=[];}flushPendingEvents(){if(this.pendingEventsBuffer.length===0)return;if(!this.get("sessionId")){o("debug","Cannot flush pending events: session not initialized - keeping in buffer",{data:{bufferedEventCount:this.pendingEventsBuffer.length}});return}let t=[...this.pendingEventsBuffer];this.pendingEventsBuffer=[],t.forEach(r=>{this.track(r);});}clearSendTimeout(){this.sendTimeoutId!==null&&(clearTimeout(this.sendTimeoutId),this.sendTimeoutId=null);}isSuccessfulResult(e){return e.status==="fulfilled"&&e.value===true}groupQueuedEventsBySession(){let e=new Map,t=[];for(let r of this.eventsQueue){if(!r._session_id){o("debug","Queued event missing _session_id, dropping",{data:{eventId:r.id,type:r.type}}),t.push(r.id);continue}let n=e.get(r._session_id);n?n.push(r):e.set(r._session_id,[r]);}return t.length>0&&this.removeProcessedEvents(t),e}buildBatchesWithIds(){let e=this.groupQueuedEventsBySession();if(e.size===0)return [];let t=[];for(let[r,n]of e)t.push({batch:this.buildBatchFromGroup(r,n),eventIds:n.map(s=>s.id)});return t}flushEvents(e){if(this.eventsQueue.length===0)return e?true:Promise.resolve(true);if(!e&&this.sendInProgress)return o("debug","Async flush skipped: send already in progress"),Promise.resolve(false);let t=this.buildBatchesWithIds();if(t.length===0)return e?true:Promise.resolve(true);if(this.dataSenders.length===0){for(let{batch:r,eventIds:n}of t)this.removeProcessedEvents(n),this.emitEventsQueue(r);return this.clearSendTimeout(),e?true:Promise.resolve(true)}if(e&&this.sendInProgress){let r=t.reduce((n,s)=>n+s.eventIds.length,0);return this.pendingSyncFlush=true,o("debug","Sync flush deferred: async send in-flight, will retry on settle",{data:{eventCount:r}}),false}if(e){let r=t.map(({batch:n,eventIds:s})=>this.sendBatchSync(n,s));return this.settleSendTimeout(),r.some(Boolean)}return this.sendInProgress=true,(async()=>{try{let r=await Promise.all(t.map(async({batch:n,eventIds:s})=>this.sendBatchAsync(n,s)));return this.settleSendTimeout(),r.some(Boolean)}finally{this.sendInProgress=false,this.drainPendingSyncFlush();}})()}settleSendTimeout(){this.eventsQueue.length===0?this.clearSendTimeout():this.scheduleSendTimeout();}drainPendingSyncFlush(){this.pendingSyncFlush&&(this.pendingSyncFlush=false,this.flushImmediatelySync());}sendBatchSync(e,t){let n=this.dataSenders.map(s=>s.sendEventsQueueSync(e)).some(s=>s);return n?(this.removeProcessedEvents(t),this.emitEventsQueue(e)):o("debug","Sync send complete failure, events kept in queue for retry",{data:{eventCount:t.length,sessionId:e.session_id}}),n}async sendBatchAsync(e,t){let r=this.dataSenders.map(async a=>a.sendEventsQueue(e,{onSuccess:()=>{},onFailure:()=>{}})),n=await Promise.allSettled(r),s=n.some(a=>this.isSuccessfulResult(a));if(s){this.removeProcessedEvents(t),this.emitEventsQueue(e);let a=n.filter(l=>!this.isSuccessfulResult(l)).length;a>0&&o("debug","Async send completed with some failures, removed from queue and persisted per-integration",{data:{eventCount:t.length,failedCount:a,sessionId:e.session_id}});}else o("debug","Async send complete failure, events kept in queue for retry",{data:{eventCount:t.length,sessionId:e.session_id}});return s}async sendEventsQueue(){if(!(this.eventsQueue.length===0||this.sendInProgress)){this.sendInProgress=true;try{let e=this.buildBatchesWithIds();if(e.length===0)return;if(this.dataSenders.length===0){for(let{batch:n}of e)this.emitEventsQueue(n);return}(await Promise.all(e.map(async({batch:n,eventIds:s})=>this.sendBatchAsync(n,s)))).some(Boolean)?this.consecutiveSendFailures=0:this.consecutiveSendFailures=Math.min(this.consecutiveSendFailures+1,5),this.eventsQueue.length===0?this.clearSendTimeout():this.scheduleSendTimeout();}finally{this.sendInProgress=false,this.drainPendingSyncFlush();}}}buildBatchFromGroup(e,t){let r=new Map,n=[];for(let m of t){let g=this.createEventSignature(m);r.has(g)||n.push(g),r.set(g,m);}let s=n.map(m=>r.get(m)).filter(m=>!!m).sort((m,g)=>m.type==="session_start"&&g.type!=="session_start"?-1:g.type==="session_start"&&m.type!=="session_start"?1:m.timestamp-g.timestamp).map(({_session_id:m,...g})=>g),a=this.get("config")?.globalMetadata,l=this.get("identity"),d={user_id:this.get("userId"),session_id:e,device:this.get("device"),events:s,...a&&{global_metadata:a},...l&&{identify:l}},c=this.get("collectApiUrls"),f=!!(c?.custom||c?.saas),E=this.transformers.beforeBatch;if(!f&&E){let m=ue(d,E,"EventManager");m!==null&&(d=m);}return d}buildEventPayload(e){let t=this.get("sessionId");if(!t)return o("error","buildEventPayload reached without sessionId \u2014 event dropped",{data:{type:e.type},visibility:"critical"}),null;let r=e.page_url??this.get("pageUrl"),n=typeof r=="string"&&r.length>0?r:"unknown",s=this.timeManager.now(),a=this.timeManager.validateTimestamp(s);a.valid||o("warn","Event timestamp validation failed",{data:{type:e.type,error:a.error}});let l=this.get("sessionReferrer"),d=this.get("sessionUtm"),c={id:Ot(),type:e.type,page_url:n,timestamp:s,...l&&{referrer:l},...e.from_page_url&&{from_page_url:e.from_page_url},...e.scroll_data&&{scroll_data:e.scroll_data},...e.click_data&&{click_data:e.click_data},...e.custom_event&&{custom_event:e.custom_event},...e.web_vitals&&{web_vitals:e.web_vitals},...e.error_data&&{error_data:e.error_data},...e.viewport_data&&{viewport_data:e.viewport_data},...e.page_view&&{page_view:e.page_view},...d&&{utm:d}},f=this.get("collectApiUrls"),E=!!f?.custom,m=!!f?.saas,g=E||m,Re=E&&m,G=this.transformers.beforeSend;if(G&&(!g||E&&!Re)){let y=et(c,G,"EventManager");if(y===null)return null;c=y;}return {...c,_session_id:t}}isDuplicateEvent(e){let t=Date.now(),r=this.createEventFingerprint(e),n=this.recentEventFingerprints.get(r);return n&&t-n<1e3?(this.recentEventFingerprints.set(r,t),true):(this.recentEventFingerprints.set(r,t),this.recentEventFingerprints.size>1500&&this.pruneOldFingerprints(),this.recentEventFingerprints.size>3e3&&(this.recentEventFingerprints.clear(),this.recentEventFingerprints.set(r,t),o("debug","Event fingerprint cache exceeded hard limit, cleared",{data:{hardLimit:3e3}})),false)}pruneOldFingerprints(){let e=Date.now(),t=1e3*10;for(let[r,n]of this.recentEventFingerprints.entries())e-n>t&&this.recentEventFingerprints.delete(r);o("debug","Pruned old event fingerprints",{data:{remaining:this.recentEventFingerprints.size,cutoffMs:t}});}createEventFingerprint(e){let t=`${e.type}_${e.page_url}`;if(e.click_data){let r=Math.round((e.click_data.x||0)/10)*10,n=Math.round((e.click_data.y||0)/10)*10;t+=`_click_${r}_${n}`;}return e.scroll_data&&(t+=`_scroll_${e.scroll_data.depth}_${e.scroll_data.direction}`),e.custom_event&&(t+=`_custom_${e.custom_event.name}`,e.custom_event.metadata&&(t+=`_${this.stableStringify(e.custom_event.metadata)}`)),e.web_vitals&&(t+=`_vitals_${e.web_vitals.type}`),e.error_data&&(t+=`_error_${e.error_data.type}_${e.error_data.message}`),t}createEventSignature(e){return this.createEventFingerprint(e)}stableStringify(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r).sort().reduce((n,s)=>(n[s]=r[s],n),{}):r)}addToQueue(e){if(this.emitEvent(e),this.eventsQueue.push(e),this.eventsQueue.length>100){let t=this.eventsQueue.findIndex(n=>n.type!=="session_start"),r=t>=0?this.eventsQueue.splice(t,1)[0]:this.eventsQueue.shift();o("warn","Event queue overflow, oldest non-critical event removed",{data:{maxLength:100,currentLength:this.eventsQueue.length,removedEventType:r?.type,wasCritical:r?.type==="session_start"}});}this.scheduleSendTimeout(),this.eventsQueue.length>=50&&this.consecutiveSendFailures<5&&this.sendEventsQueue();}scheduleSendTimeout(){if(this.sendTimeoutId!==null)return;let e=this.calculateSendDelay();this.sendTimeoutId=window.setTimeout(()=>{this.sendTimeoutId=null,this.eventsQueue.length>0&&this.sendEventsQueue();},e);}calculateSendDelay(){let e=this.get("config")?.sendIntervalMs??1e4;if(this.consecutiveSendFailures===0)return e;let t=e*Math.pow(2,this.consecutiveSendFailures);return Math.min(t,12e4)}shouldSample(){let e=this.get("config")?.samplingRate??1;return Math.random()<e}checkRateLimit(){let e=Date.now();return e-this.rateLimitWindowStart>1e3&&(this.rateLimitCounter=0,this.rateLimitWindowStart=e),this.rateLimitCounter>=50?false:(this.rateLimitCounter++,true)}checkPerEventRateLimit(e,t){let r=Date.now(),s=(this.perEventRateLimits.get(e)??[]).filter(a=>r-a<6e4);return s.length>=t?(o("warn","Per-event rate limit exceeded for custom event",{data:{eventName:e,limit:t,window:`${6e4/1e3}s`}}),false):(s.push(r),this.perEventRateLimits.set(e,s),true)}getTypeLimitForEvent(e){return {click:500,page_view:100,custom:500,viewport_visible:200,scroll:120}[e]??null}removeProcessedEvents(e){let t=new Set(e);this.eventsQueue=this.eventsQueue.filter(r=>!t.has(r.id));}emitEvent(e){if(this.emitter){let{_session_id:t,...r}=e;this.emitter.emit("event",r);}}emitEventsQueue(e){this.emitter&&this.emitter.emit("queue",e);}debounce(e,t){let r=null;return((...n)=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{e(...n),r=null;},t);})}getInitialCounts(){return {total:0,click:0,page_view:0,custom:0,viewport_visible:0,scroll:0}}loadSessionCounts(e){if(typeof window>"u"||typeof localStorage>"u")return this.getInitialCounts();let t=this.get("userId")||"anonymous",r=xe(t,e);try{let n=localStorage.getItem(r);if(!n)return this.getInitialCounts();let s=JSON.parse(n);return s._timestamp&&Date.now()-s._timestamp>De?(o("debug","Session counts expired, clearing",{data:{sessionId:e,age:Date.now()-s._timestamp}}),localStorage.removeItem(r),this.getInitialCounts()):typeof s.total=="number"&&typeof s.click=="number"&&typeof s.page_view=="number"&&typeof s.custom=="number"&&typeof s.viewport_visible=="number"&&typeof s.scroll=="number"?{total:s.total,click:s.click,page_view:s.page_view,custom:s.custom,viewport_visible:s.viewport_visible,scroll:s.scroll}:(o("warn","Invalid session counts structure in localStorage, resetting",{data:{sessionId:e,parsed:s}}),localStorage.removeItem(r),o("debug","Session counts removed due to invalid/corrupted data",{data:{sessionId:e,parsed:s}}),this.getInitialCounts())}catch(n){return o("warn","Failed to load session counts from localStorage",{error:n,data:{sessionId:e}}),this.getInitialCounts()}}cleanupExpiredSessionCounts(){if(!(typeof window>"u"||typeof localStorage>"u"))try{let e=localStorage.getItem(ke);if(e){let s=Date.now()-parseInt(e,10);if(s<Ve){o("debug","Skipping session counts cleanup (throttled)",{data:{timeSinceLastCleanup:s,throttleMs:Ve}});return}}let t=this.get("userId")||"anonymous",r=`${S}:${t}:session_counts:`,n=[];for(let s=0;s<localStorage.length;s++){let a=localStorage.key(s);if(a?.startsWith(r))try{let l=localStorage.getItem(a);if(l){let d=JSON.parse(l);d._timestamp&&Date.now()-d._timestamp>De&&n.push(a);}}catch{}}n.forEach(s=>{localStorage.removeItem(s),o("debug","Cleaned up expired session counts",{data:{key:s}});}),n.length>0&&o("info",`Cleaned up ${n.length} expired session counts entries`),localStorage.setItem(ke,Date.now().toString());}catch(e){o("warn","Failed to cleanup expired session counts",{error:e});}}saveSessionCounts(e){let t=this.get("userId")||"anonymous",r=xe(t,e);try{let n={...this.sessionEventCounts,_timestamp:Date.now(),_version:1};localStorage.setItem(r,JSON.stringify(n));}catch(n){o("warn","Failed to persist session counts to localStorage",{error:n,data:{sessionId:e}});}}};var he=class{static getId(e){let t=e.getItem(U);if(t)return t;let r=ae();return e.setItem(U,r),r}};var gn=/^\d{13}-[a-z0-9]{9}$/,ge=class extends h{storageManager;eventManager;projectId;activityHandler=null;visibilityChangeHandler=null;sessionTimeoutId=null;broadcastChannel=null;isTracking=false;needsRenewal=false;constructor(e,t,r){super(),this.storageManager=e,this.eventManager=t,this.projectId=r;}initCrossTabSync(){if(typeof BroadcastChannel>"u"){o("debug","BroadcastChannel not supported");return}let e=this.getProjectId();this.broadcastChannel=new BroadcastChannel(pt(e)),this.broadcastChannel.onmessage=t=>{let{action:r,sessionId:n,timestamp:s,projectId:a}=t.data??{};a===e&&(r==="session_start"&&n&&typeof s=="number"&&s>Date.now()-5e3?(this.set("sessionId",n),this.persistSession(n,s),this.isTracking&&this.setupSessionTimeout()):r&&r!=="session_start"&&o("debug","Ignored BroadcastChannel message with unknown action",{data:{action:r}}));};}shareSession(e){this.broadcastChannel&&typeof this.broadcastChannel.postMessage=="function"&&this.broadcastChannel.postMessage({action:"session_start",projectId:this.getProjectId(),sessionId:e,timestamp:Date.now()});}cleanupCrossTabSync(){this.broadcastChannel&&(typeof this.broadcastChannel.close=="function"&&this.broadcastChannel.close(),this.broadcastChannel=null);}recoverSession(){let e=this.loadStoredSession();if(!e)return null;if(!gn.test(e.id))return o("warn","Invalid session ID format recovered from storage, clearing",{data:{sessionId:e.id}}),this.clearStoredSession(),null;let t=this.get("config")?.sessionTimeout??9e5;return Date.now()-e.lastActivity>t?(this.clearStoredSession(),null):e.id}persistSession(e,t=Date.now(),r,n){this.saveStoredSession({id:e,lastActivity:t,...r&&{referrer:r},...n&&{utm:n}});}clearStoredSession(){let e=this.getSessionStorageKey();this.storageManager.removeItem(e);}loadStoredSession(){let e=this.getSessionStorageKey(),t=this.storageManager.getItem(e);if(t!==null)try{let n=JSON.parse(t);if(n.id&&typeof n.lastActivity=="number")return n}catch{this.storageManager.removeItem(e);}let r=this.storageManager.getSessionItem(e);if(r!==null)try{let n=JSON.parse(r);if(n.id&&typeof n.lastActivity=="number")return n}catch{this.storageManager.removeSessionItem(e);}return null}saveStoredSession(e){let t=this.getSessionStorageKey(),r=JSON.stringify(e);this.storageManager.setItem(t,r),this.storageManager.setSessionItem(t,r);}getSessionStorageKey(){return mt(this.getProjectId())}getProjectId(){return this.projectId}startTracking(){if(this.isTracking){o("debug","Session tracking already active");return}let e=this.recoverSession(),t=e??this.generateSessionId(),r,n;if(e){let s=this.loadStoredSession();r=s?.referrer??ne(),n=s?.utm??ie();}else r=ne(),n=ie();o("debug","Session tracking initialized",{data:{sessionId:t,wasRecovered:!!e,willEmitSessionStart:!e,sessionReferrer:r,hasUtm:!!n}}),this.isTracking=true;try{this.set("sessionId",t),this.set("sessionReferrer",r),this.set("sessionUtm",n),this.persistSession(t,Date.now(),r,n),this.initCrossTabSync(),this.shareSession(t),e?o("debug","Session recovered, skipping SESSION_START",{data:{sessionId:t}}):(o("debug","Emitting SESSION_START event",{data:{sessionId:t}}),this.eventManager.track({type:"session_start"})),this.setupSessionTimeout(),this.setupActivityListeners(),this.setupLifecycleListeners();}catch(s){throw this.isTracking=false,this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupLifecycleListeners(),this.cleanupCrossTabSync(),this.set("sessionId",null),s}}generateSessionId(){return `${Date.now()}-${Math.random().toString(36).substring(2,11)}`}setupSessionTimeout(){this.clearSessionTimeout();let e=this.get("config")?.sessionTimeout??9e5;this.sessionTimeoutId=setTimeout(()=>{this.enterRenewalMode();},e);}resetSessionTimeout(){this.setupSessionTimeout();let e=this.get("sessionId");e&&this.persistSession(e,Date.now(),this.get("sessionReferrer"),this.get("sessionUtm"));}clearSessionTimeout(){this.sessionTimeoutId&&(clearTimeout(this.sessionTimeoutId),this.sessionTimeoutId=null);}setupActivityListeners(){this.activityHandler=()=>{this.needsRenewal?this.renewSession():this.resetSessionTimeout();},document.addEventListener("click",this.activityHandler,{passive:true}),document.addEventListener("keydown",this.activityHandler,{passive:true}),document.addEventListener("scroll",this.activityHandler,{passive:true});}renewSession(){this.needsRenewal=false;let e=this.generateSessionId(),t=ne(),r=ie();o("debug","Renewing session after timeout",{data:{newSessionId:e}}),this.set("sessionId",e),this.set("sessionReferrer",t),this.set("sessionUtm",r),this.persistSession(e,Date.now(),t,r),this.cleanupCrossTabSync(),this.initCrossTabSync(),this.shareSession(e),this.eventManager.track({type:"session_start"}),this.eventManager.flushPendingEvents(),this.setupSessionTimeout();}cleanupActivityListeners(){this.activityHandler&&(document.removeEventListener("click",this.activityHandler),document.removeEventListener("keydown",this.activityHandler),document.removeEventListener("scroll",this.activityHandler),this.activityHandler=null);}setupLifecycleListeners(){this.visibilityChangeHandler||(this.visibilityChangeHandler=()=>{if(document.hidden)this.clearSessionTimeout();else {if(this.isSessionStale()){o("debug","Session expired during suspend, entering renewal mode"),this.enterRenewalMode();return}this.get("sessionId")&&this.setupSessionTimeout();}},document.addEventListener("visibilitychange",this.visibilityChangeHandler));}isSessionStale(){if(this.needsRenewal||!this.get("sessionId"))return false;let t=this.loadStoredSession();if(!t)return false;let r=this.get("config")?.sessionTimeout??9e5;return Date.now()-t.lastActivity>r}cleanupLifecycleListeners(){this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=null);}enterRenewalMode(){this.clearSessionTimeout(),this.cleanupCrossTabSync(),this.clearStoredSession(),this.set("sessionId",null),this.set("hasStartSession",false),this.set("sessionReferrer",void 0),this.set("sessionUtm",void 0),this.needsRenewal=true,o("debug","Session timed out, entering renewal mode");}resetSessionState(){this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupLifecycleListeners(),this.cleanupCrossTabSync(),this.clearStoredSession(),this.set("sessionId",null),this.set("hasStartSession",false),this.set("sessionReferrer",void 0),this.set("sessionUtm",void 0),this.needsRenewal=false,this.isTracking=false;}stopTracking(){this.resetSessionState();}destroy(){this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupCrossTabSync(),this.cleanupLifecycleListeners(),this.isTracking=false,this.needsRenewal=false,this.set("hasStartSession",false);}};var Ee=class extends h{eventManager;storageManager;sessionManager=null;destroyed=false;constructor(e,t){super(),this.eventManager=t,this.storageManager=e;}startTracking(){if(this.isActive())return;if(this.destroyed){o("debug","Cannot start tracking on destroyed handler");return}let t=this.get("config")?.integrations?.tracelog?.projectId??"custom";try{this.sessionManager=new ge(this.storageManager,this.eventManager,t),this.sessionManager.startTracking(),this.eventManager.flushPendingEvents();}catch(r){if(this.sessionManager){try{this.sessionManager.destroy();}catch{}this.sessionManager=null;}throw o("error","Failed to start session tracking",{error:r}),r}}isActive(){return this.sessionManager!==null&&!this.destroyed}cleanupSessionManager(){this.sessionManager&&(this.sessionManager.stopTracking(),this.sessionManager.destroy(),this.sessionManager=null);}stopTracking(){this.cleanupSessionManager();}destroy(){this.destroyed||(this.sessionManager&&(this.sessionManager.destroy(),this.sessionManager=null),this.destroyed=true);}};var ve=class extends h{eventManager;onTrack;originalPushState;originalReplaceState;lastPageViewTime=0;constructor(e,t){super(),this.eventManager=e,this.onTrack=t;}startTracking(){this.trackInitialPageView(),window.addEventListener("popstate",this.trackCurrentPage,true),window.addEventListener("hashchange",this.trackCurrentPage,true),this.patchHistory("pushState"),this.patchHistory("replaceState");}stopTracking(){window.removeEventListener("popstate",this.trackCurrentPage,true),window.removeEventListener("hashchange",this.trackCurrentPage,true),this.originalPushState&&(window.history.pushState=this.originalPushState),this.originalReplaceState&&(window.history.replaceState=this.originalReplaceState),this.lastPageViewTime=0;}patchHistory(e){let t=window.history[e];e==="pushState"&&!this.originalPushState?this.originalPushState=t:e==="replaceState"&&!this.originalReplaceState&&(this.originalReplaceState=t),window.history[e]=(...r)=>{t.apply(window.history,r),this.trackCurrentPage();};}trackCurrentPage=()=>{let e=window.location.href,t=Q(e,this.get("config").sensitiveQueryParams);if(this.get("pageUrl")===t)return;let r=Date.now(),n=this.get("config").pageViewThrottleMs??1e3;if(r-this.lastPageViewTime<n)return;this.lastPageViewTime=r,this.onTrack();let s=this.get("pageUrl");this.set("pageUrl",t);let a=this.extractPageViewData();this.eventManager.track({type:"page_view",page_url:this.get("pageUrl"),from_page_url:s,...a&&{page_view:a}}),this.get("config").flushOnSpaNavigation===true&&this.eventManager.flushImmediately();};trackInitialPageView(){let e=Q(window.location.href,this.get("config").sensitiveQueryParams),t=this.extractPageViewData();this.lastPageViewTime=Date.now(),this.eventManager.track({type:"page_view",page_url:e,...t&&{page_view:t}}),this.onTrack();}extractPageViewData(){let{pathname:e,search:t,hash:r}=window.location,{referrer:n}=document,{title:s}=document;return !n&&!s&&!e&&!t&&!r?void 0:{...n&&{referrer:n},...s&&{title:s},...e&&{pathname:e},...t&&{search:t},...r&&{hash:r}}}};var Se=class extends h{eventManager;lastClickTimes=new Map;clickHandler;lastPruneTime=0;constructor(e){super(),this.eventManager=e;}startTracking(){this.clickHandler||(this.clickHandler=e=>{let t=e,r=t.target,n=typeof HTMLElement<"u"&&r instanceof HTMLElement?r:typeof HTMLElement<"u"&&r instanceof Node&&r.parentElement instanceof HTMLElement?r.parentElement:null;if(!n){o("debug","Click target not found or not an element");return}if(this.shouldIgnoreElement(n))return;let s=this.get("config")?.clickThrottleMs??300;if(s>0&&!this.checkClickThrottle(n,s))return;let a=this.findTrackingElement(n),l=this.getRelevantClickElement(n),d=this.calculateClickCoordinates(t,n);if(a){let f=this.extractTrackingData(a);if(f){let E=this.createCustomEventData(f);this.eventManager.track({type:"custom",custom_event:{name:E.name,...E.value&&{metadata:{value:E.value}}}});}}if(!d){o("debug","Click skipped: invalid coordinates (likely synthetic)");return}let c=this.generateClickData(n,l,d);this.eventManager.track({type:"click",click_data:c});},window.addEventListener("click",this.clickHandler,true));}stopTracking(){this.clickHandler&&(window.removeEventListener("click",this.clickHandler,true),this.clickHandler=void 0),this.lastClickTimes.clear(),this.lastPruneTime=0;}shouldIgnoreElement(e){return e.hasAttribute(`${_}-ignore`)?true:e.closest(`[${_}-ignore]`)!==null}checkClickThrottle(e,t){let r=this.getElementSignature(e),n=Date.now();this.pruneThrottleCache(n);let s=this.lastClickTimes.get(r);return s!==void 0&&n-s<t?(o("debug","ClickHandler: Click suppressed by throttle",{data:{signature:r,throttleRemaining:t-(n-s)}}),false):(this.lastClickTimes.set(r,n),true)}pruneThrottleCache(e){if(e-this.lastPruneTime<3e4)return;this.lastPruneTime=e;let t=e-3e5;for(let[r,n]of this.lastClickTimes.entries())n<t&&this.lastClickTimes.delete(r);if(this.lastClickTimes.size>1e3){let r=Array.from(this.lastClickTimes.entries()).sort((a,l)=>a[1]-l[1]),n=this.lastClickTimes.size-1e3,s=r.slice(0,n);for(let[a]of s)this.lastClickTimes.delete(a);o("debug","ClickHandler: Pruned throttle cache",{data:{removed:s.length,remaining:this.lastClickTimes.size}});}}getElementSignature(e){if(e.id)return `#${e.id}`;let t=e.getAttribute("data-testid");if(t)return `[data-testid="${t}"]`;let r=e.getAttribute(`${_}-name`);return r?`[${_}-name="${r}"]`:this.getElementPath(e)}getElementPath(e){let t=[],r=e;for(;r&&r!==document.body;){let n=r.tagName.toLowerCase();if(r.className){let s=r.className.split(" ")[0];s&&(n+=`.${s}`);}t.unshift(n),r=r.parentElement;}return t.join(">")||"unknown"}findTrackingElement(e){return e.hasAttribute(`${_}-name`)?e:e.closest(`[${_}-name]`)}getRelevantClickElement(e){for(let t of ot)try{if(e.matches(t))return e;let r=e.closest(t);if(r)return r}catch(r){o("debug","Invalid selector in element search",{error:r,data:{selector:t}});continue}return e}clamp(e){return Math.max(0,Math.min(1,Number(e.toFixed(3))))}calculateClickCoordinates(e,t){let r=e.clientX,n=e.clientY;if(typeof r!="number"||typeof n!="number"||!Number.isFinite(r)||!Number.isFinite(n)||r===0&&n===0&&!e.isTrusted)return null;let s=t.getBoundingClientRect(),a=s.width>0?this.clamp((r-s.left)/s.width):0,l=s.height>0?this.clamp((n-s.top)/s.height):0;return {x:r,y:n,relativeX:a,relativeY:l}}extractTrackingData(e){let t=e.getAttribute(`${_}-name`),r=e.getAttribute(`${_}-value`);if(t)return {element:e,name:t,...r&&{value:r}}}generateClickData(e,t,r){let{x:n,y:s,relativeX:a,relativeY:l}=r,d=this.getRelevantText(e,t),c=this.extractElementAttributes(t);return {x:n,y:s,relativeX:a,relativeY:l,tag:t.tagName.toLowerCase(),...t.id&&{id:t.id},...t.className&&{class:t.className},...d&&{text:d},...c.href&&{href:c.href},...c.title&&{title:c.title},...c.alt&&{alt:c.alt},...c.role&&{role:c.role},...c["aria-label"]&&{ariaLabel:c["aria-label"]},...Object.keys(c).length>0&&{dataAttributes:c}}}sanitizeText(e){let t=e;for(let r of $){let n=new RegExp(r.source,r.flags);t=t.replace(n,"[REDACTED]");}return t}getRelevantText(e,t){let r=e.textContent?.trim()??"",n=t.textContent?.trim()??"";if(!r&&!n)return "";let s="";return r&&r.length<=255?s=r:n.length<=255?s=n:s=n.slice(0,252)+"...",this.sanitizeText(s)}extractElementAttributes(e){let t=["id","class","data-testid","aria-label","title","href","type","name","alt","role"],r={};for(let n of t){let s=e.getAttribute(n);s&&(r[n]=s);}return r}createCustomEventData(e){return {name:e.name,...e.value&&{value:e.value}}}};var ye=class extends h{eventManager;containers=[];limitWarningLogged=false;minDepthChange=5;minIntervalMs=500;maxEventsPerSession=120;containerDiscoveryTimeoutId=null;constructor(e){super(),this.eventManager=e;}startTracking(){this.limitWarningLogged=false,this.applyConfigOverrides(),this.set("scrollEventCount",0),this.tryDetectScrollContainers(0);}stopTracking(){this.containerDiscoveryTimeoutId!==null&&(clearTimeout(this.containerDiscoveryTimeoutId),this.containerDiscoveryTimeoutId=null);for(let e of this.containers)this.clearContainerTimer(e),e.element===window?window.removeEventListener("scroll",e.listener):e.element.removeEventListener("scroll",e.listener);this.containers.length=0,this.set("scrollEventCount",0),this.limitWarningLogged=false;}tryDetectScrollContainers(e){let t=this.findScrollableElements();if(this.isWindowScrollable()&&this.setupScrollContainer(window,"window"),t.length>0){for(let r of t){let n=this.getElementSelector(r);this.setupScrollContainer(r,n);}this.applyPrimaryScrollSelectorIfConfigured();return}if(e<5){this.containerDiscoveryTimeoutId=window.setTimeout(()=>{this.containerDiscoveryTimeoutId=null,this.tryDetectScrollContainers(e+1);},200);return}this.containers.length===0&&this.setupScrollContainer(window,"window"),this.applyPrimaryScrollSelectorIfConfigured();}applyPrimaryScrollSelectorIfConfigured(){let e=this.get("config");e?.primaryScrollSelector&&this.applyPrimaryScrollSelector(e.primaryScrollSelector);}findScrollableElements(){if(!document.body)return [];let e=[],t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{let s=n;if(!s.isConnected||!s.offsetParent)return NodeFilter.FILTER_SKIP;let a=getComputedStyle(s);return a.overflowY==="auto"||a.overflowY==="scroll"||a.overflow==="auto"||a.overflow==="scroll"?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}}),r;for(;(r=t.nextNode())&&e.length<10;){let n=r;this.isElementScrollable(n)&&e.push(n);}return e}getElementSelector(e){if(e===window)return "window";let t=e;if(t.id)return `#${t.id}`;if(t.className&&typeof t.className=="string"){let r=t.className.split(" ").filter(n=>n.trim())[0];if(r)return `.${r}`}return t.tagName.toLowerCase()}determineIfPrimary(e){return this.isWindowScrollable()?e===window:this.containers.length===0}setupScrollContainer(e,t){if(this.containers.some(c=>c.element===e)||e!==window&&!this.isElementScrollable(e))return;let n=this.getScrollTop(e),s=this.calculateScrollDepth(n,this.getScrollHeight(e),this.getViewportHeight(e)),a=this.determineIfPrimary(e),l={element:e,selector:t,isPrimary:a,lastScrollPos:n,lastDepth:s,lastDirection:"down",lastEventTime:0,firstScrollEventTime:null,maxDepthReached:s,debounceTimer:null,listener:null},d=()=>{this.get("suppressNextScroll")||(l.firstScrollEventTime===null&&(l.firstScrollEventTime=Date.now()),this.clearContainerTimer(l),l.debounceTimer=window.setTimeout(()=>{let c=this.calculateScrollData(l);if(c){let f=Date.now();this.processScrollEvent(l,c,f);}l.debounceTimer=null;},250));};l.listener=d,this.containers.push(l),e===window?window.addEventListener("scroll",d,{passive:true}):e.addEventListener("scroll",d,{passive:true});}processScrollEvent(e,t,r){if(!this.shouldEmitScrollEvent(e,t,r))return;e.lastEventTime=r,e.lastDepth=t.depth,e.lastDirection=t.direction;let n=this.get("scrollEventCount")??0;this.set("scrollEventCount",n+1),this.eventManager.track({type:"scroll",scroll_data:{...t,container_selector:e.selector,is_primary:e.isPrimary}});}shouldEmitScrollEvent(e,t,r){return this.hasReachedSessionLimit()?(this.logLimitOnce(),false):!(!this.hasElapsedMinimumInterval(e,r)||!this.hasSignificantDepthChange(e,t.depth))}hasReachedSessionLimit(){return (this.get("scrollEventCount")??0)>=this.maxEventsPerSession}hasElapsedMinimumInterval(e,t){return e.lastEventTime===0?true:t-e.lastEventTime>=this.minIntervalMs}hasSignificantDepthChange(e,t){return Math.abs(t-e.lastDepth)>=this.minDepthChange}logLimitOnce(){this.limitWarningLogged||(this.limitWarningLogged=true,o("debug","Max scroll events per session reached",{data:{limit:this.maxEventsPerSession}}));}applyConfigOverrides(){this.minDepthChange=5,this.minIntervalMs=500,this.maxEventsPerSession=120;}isWindowScrollable(){return document.documentElement.scrollHeight>window.innerHeight}clearContainerTimer(e){e.debounceTimer!==null&&(clearTimeout(e.debounceTimer),e.debounceTimer=null);}getScrollDirection(e,t){return e>t?"down":"up"}calculateScrollDepth(e,t,r){if(t<=r)return 0;let n=t-r;return Math.min(100,Math.max(0,Math.floor(e/n*100)))}calculateScrollData(e){let{element:t,lastScrollPos:r,lastEventTime:n}=e,s=this.getScrollTop(t),a=Date.now(),l=Math.abs(s-r);if(l<10||t===window&&!this.isWindowScrollable())return null;let d=this.getViewportHeight(t),c=this.getScrollHeight(t),f=this.getScrollDirection(s,r),E=this.calculateScrollDepth(s,c,d),m;n>0?m=a-n:e.firstScrollEventTime!==null?m=a-e.firstScrollEventTime:m=250;let g=Math.round(l/m*1e3);return E>e.maxDepthReached&&(e.maxDepthReached=E),e.lastScrollPos=s,{depth:E,direction:f,velocity:g,max_depth_reached:e.maxDepthReached}}getScrollTop(e){return e===window?window.scrollY:e.scrollTop}getViewportHeight(e){return e===window?window.innerHeight:e.clientHeight}getScrollHeight(e){return e===window?document.documentElement.scrollHeight:e.scrollHeight}isElementScrollable(e){let t=getComputedStyle(e),r=t.overflowY==="auto"||t.overflowY==="scroll"||t.overflow==="auto"||t.overflow==="scroll",n=e.scrollHeight>e.clientHeight;return r&&n}applyPrimaryScrollSelector(e){let t;if(e==="window")t=window;else {let n=document.querySelector(e);if(!(n instanceof HTMLElement)){o("debug",`Selector "${e}" did not match an HTMLElement`);return}t=n;}this.containers.forEach(n=>{this.updateContainerPrimary(n,n.element===t);}),!this.containers.some(n=>n.element===t)&&t instanceof HTMLElement&&this.isElementScrollable(t)&&this.setupScrollContainer(t,e);}updateContainerPrimary(e,t){e.isPrimary=t;}};var _e=class extends h{eventManager;trackedElements=new Map;observer=null;mutationObserver=null;mutationDebounceTimer=null;config=null;constructor(e){super(),this.eventManager=e;}startTracking(){let e=this.get("config");if(this.config=e.viewport??null,!this.config?.elements||this.config.elements.length===0)return;let t=this.config.threshold??.5,r=this.config.minDwellTime??1e3;if(t<0||t>1){o("debug","ViewportHandler: Invalid threshold, must be between 0 and 1");return}if(r<0){o("debug","ViewportHandler: Invalid minDwellTime, must be non-negative");return}if(typeof IntersectionObserver>"u"){o("debug","ViewportHandler: IntersectionObserver not supported in this browser");return}this.observer=new IntersectionObserver(this.handleIntersection,{threshold:t}),this.observeElements(),this.setupMutationObserver();}stopTracking(){this.observer&&(this.observer.disconnect(),this.observer=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.mutationDebounceTimer!==null&&(window.clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=null);for(let e of this.trackedElements.values())e.timeoutId!==null&&window.clearTimeout(e.timeoutId);this.trackedElements.clear();}observeElements(){if(!this.config||!this.observer)return;let e=this.config.maxTrackedElements??100,t=this.trackedElements.size;for(let r of this.config.elements)try{let n=document.querySelectorAll(r.selector);for(let s of Array.from(n)){if(t>=e){o("debug","ViewportHandler: Maximum tracked elements reached",{data:{limit:e,selector:r.selector,message:"Some elements will not be tracked. Consider more specific selectors."}});return}s.hasAttribute(`${_}-ignore`)||this.trackedElements.has(s)||(this.trackedElements.set(s,{element:s,selector:r.selector,id:r.id,name:r.name,startTime:null,timeoutId:null,lastFiredTime:null}),this.observer?.observe(s),t++);}}catch(n){o("debug",`ViewportHandler: Invalid selector "${r.selector}"`,{error:n});}o("debug","ViewportHandler: Elements tracked",{data:{count:t,limit:e}});}handleIntersection=e=>{if(!this.config)return;let t=this.config.minDwellTime??1e3;for(let r of e){let n=this.trackedElements.get(r.target);n&&(r.isIntersecting?n.startTime===null&&(n.startTime=performance.now(),n.timeoutId=window.setTimeout(()=>{let s=Math.round(r.intersectionRatio*100)/100;this.fireViewportEvent(n,s);},t)):n.startTime!==null&&(n.timeoutId!==null&&(window.clearTimeout(n.timeoutId),n.timeoutId=null),n.startTime=null));}};fireViewportEvent(e,t){if(e.startTime===null)return;let r=Math.round(performance.now()-e.startTime);if(e.element.hasAttribute(`${_}-ignore`))return;let n=this.config?.cooldownPeriod??6e4,s=Date.now();if(e.lastFiredTime!==null&&s-e.lastFiredTime<n){o("debug","ViewportHandler: Event suppressed by cooldown period",{data:{selector:e.selector,cooldownRemaining:n-(s-e.lastFiredTime)}}),e.startTime=null,e.timeoutId=null;return}let a={selector:e.selector,dwellTime:r,visibilityRatio:t,...e.id!==void 0&&{id:e.id},...e.name!==void 0&&{name:e.name}};this.eventManager.track({type:"viewport_visible",viewport_data:a}),e.startTime=null,e.timeoutId=null,e.lastFiredTime=s;}setupMutationObserver(){if(!(!this.config||typeof MutationObserver>"u")){if(!document.body){o("debug","ViewportHandler: document.body not available, skipping MutationObserver setup");return}this.mutationObserver=new MutationObserver(e=>{let t=false;for(let r of e)r.type==="childList"&&(r.addedNodes.length>0&&(t=true),r.removedNodes.length>0&&this.cleanupRemovedNodes(r.removedNodes));t&&(this.mutationDebounceTimer!==null&&window.clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=window.setTimeout(()=>{this.observeElements(),this.mutationDebounceTimer=null;},100));}),this.mutationObserver.observe(document.body,{childList:true,subtree:true});}}cleanupRemovedNodes(e){e.forEach(t=>{if(t.nodeType!==1)return;let r=t,n=this.trackedElements.get(r);n&&(n.timeoutId!==null&&window.clearTimeout(n.timeoutId),this.observer?.unobserve(r),this.trackedElements.delete(r)),Array.from(this.trackedElements.keys()).filter(a=>r.contains(a)).forEach(a=>{let l=this.trackedElements.get(a);l&&l.timeoutId!==null&&window.clearTimeout(l.timeoutId),this.observer?.unobserve(a),this.trackedElements.delete(a);});});}};var yn="tracelog_session_id",_n="tracelog_user_id",K=class extends h{visibilityHandler=null;pageshowHandler=null;lastSyncedKey=null;activate(){this.cleanupListeners(),this.syncCartAttribute(),this.setupListeners();}deactivate(){this.cleanupListeners(),this.lastSyncedKey=null;}onSessionChange(){this.syncCartAttribute();}syncCartAttribute(){let e=this.get("sessionId");if(!e)return;let t=this.get("userId"),r=typeof t=="string"&&t.length>0?t:"",n=`${e}|${r}`;n!==this.lastSyncedKey&&(this.lastSyncedKey=n,this.postCartUpdate(e,r));}postCartUpdate(e,t){let r={[yn]:e};t.length>0&&(r[_n]=t);try{fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({attributes:r}),credentials:"same-origin"}).then(n=>{n.ok||(this.lastSyncedKey=null,o("debug","Shopify cart attribute update failed",{data:{status:n.status}}));}).catch(()=>{this.lastSyncedKey=null,o("debug","Shopify cart attribute update failed");});}catch{this.lastSyncedKey=null,o("debug","Shopify cart attribute update failed");}}setupListeners(){this.visibilityHandler=()=>{document.hidden||this.syncCartAttribute();},document.addEventListener("visibilitychange",this.visibilityHandler),this.pageshowHandler=e=>{e.persisted&&this.syncCartAttribute();},window.addEventListener("pageshow",this.pageshowHandler);}cleanupListeners(){this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.pageshowHandler&&(window.removeEventListener("pageshow",this.pageshowHandler),this.pageshowHandler=null);}};var Ie=class{storage;sessionStorageRef;fallbackStorage=new Map;fallbackSessionStorage=new Map;hasQuotaExceededError=false;constructor(){this.storage=this.initializeStorage("localStorage"),this.sessionStorageRef=this.initializeStorage("sessionStorage"),this.storage||o("debug","localStorage not available, using memory fallback"),this.sessionStorageRef||o("debug","sessionStorage not available, using memory fallback");}getItem(e){try{return this.storage?this.storage.getItem(e):this.fallbackStorage.get(e)??null}catch{return this.fallbackStorage.get(e)??null}}setItem(e,t){this.fallbackStorage.set(e,t);try{if(this.storage){this.storage.setItem(e,t);return}}catch(r){if(r instanceof DOMException&&r.name==="QuotaExceededError"||r instanceof Error&&r.name==="QuotaExceededError")if(this.hasQuotaExceededError=true,o("warn","localStorage quota exceeded, attempting cleanup",{data:{key:e,valueSize:t.length}}),this.cleanupOldData())try{if(this.storage){this.storage.setItem(e,t);return}}catch(a){o("error","localStorage quota exceeded even after cleanup - data will not persist",{error:a,data:{key:e,valueSize:t.length}});}else o("error","localStorage quota exceeded and no data to cleanup - data will not persist",{error:r,data:{key:e,valueSize:t.length}});}}removeItem(e){try{this.storage&&this.storage.removeItem(e);}catch{}this.fallbackStorage.delete(e);}clear(){if(!this.storage){this.fallbackStorage.clear();return}try{let e=[];for(let t=0;t<this.storage.length;t++){let r=this.storage.key(t);r?.startsWith("tracelog_")&&e.push(r);}e.forEach(t=>{this.storage.removeItem(t);}),this.fallbackStorage.clear();}catch(e){o("error","Failed to clear storage",{error:e}),this.fallbackStorage.clear();}}isAvailable(){return this.storage!==null}hasQuotaError(){return this.hasQuotaExceededError}cleanupOldData(){if(!this.storage)return false;try{let e=[],t=[];for(let s=0;s<this.storage.length;s++){let a=this.storage.key(s);a?.startsWith("tracelog_")&&(e.push(a),a.startsWith("tracelog_persisted_events_")&&t.push(a));}if(t.length>0)return t.forEach(s=>{try{this.storage.removeItem(s);}catch{}}),!0;let r=["tracelog_session_","tracelog_user_id","tracelog_device_id","tracelog_config"],n=e.filter(s=>!r.some(a=>s.startsWith(a)));return n.length>0?(n.slice(0,5).forEach(a=>{try{this.storage.removeItem(a);}catch{}}),!0):!1}catch(e){return o("error","Failed to cleanup old data",{error:e}),false}}initializeStorage(e){if(typeof window>"u")return null;try{let t=e==="localStorage"?window.localStorage:window.sessionStorage,r="__tracelog_test__";return t.setItem(r,"test"),t.removeItem(r),t}catch{return null}}getSessionItem(e){try{return this.sessionStorageRef?this.sessionStorageRef.getItem(e):this.fallbackSessionStorage.get(e)??null}catch{return this.fallbackSessionStorage.get(e)??null}}setSessionItem(e,t){this.fallbackSessionStorage.set(e,t);try{if(this.sessionStorageRef){this.sessionStorageRef.setItem(e,t);return}}catch(r){(r instanceof DOMException&&r.name==="QuotaExceededError"||r instanceof Error&&r.name==="QuotaExceededError")&&o("error","sessionStorage quota exceeded - data will not persist",{error:r,data:{key:e,valueSize:t.length}});}}removeSessionItem(e){try{this.sessionStorageRef&&this.sessionStorageRef.removeItem(e);}catch{}this.fallbackSessionStorage.delete(e);}};var be=class extends h{eventManager;reportedByNav=new Map;navigationHistory=[];observers=[];vitalThresholds;lastLongTaskSentAt=0;navigationCounter=0;constructor(e){super(),this.eventManager=e,this.vitalThresholds=re(W);}async startTracking(){let e=this.get("config"),t=e?.webVitalsMode??W;this.vitalThresholds=re(t),e?.webVitalsThresholds&&(this.vitalThresholds={...this.vitalThresholds,...e.webVitalsThresholds}),await this.initWebVitals(),this.observeLongTasks();}stopTracking(){this.observers.forEach((e,t)=>{try{e.disconnect();}catch(r){o("debug","Failed to disconnect performance observer",{error:r,data:{observerIndex:t}});}}),this.observers.length=0,this.reportedByNav.clear(),this.navigationHistory.length=0;}observeWebVitalsFallback(){this.reportTTFB(),this.safeObserve("largest-contentful-paint",r=>{let n=r.getEntries(),s=n[n.length-1];s&&this.sendVital({type:"LCP",value:Number(s.startTime.toFixed(2))});},{type:"largest-contentful-paint",buffered:true},true);let e=0,t=this.getNavigationId();this.safeObserve("layout-shift",r=>{let n=this.getNavigationId();n!==t&&(e=0,t=n);let s=r.getEntries();for(let a of s){if(a.hadRecentInput===true)continue;let l=typeof a.value=="number"?a.value:0;e+=l;}this.sendVital({type:"CLS",value:Number(e.toFixed(2))});},{type:"layout-shift",buffered:true}),this.safeObserve("paint",r=>{for(let n of r.getEntries())n.name==="first-contentful-paint"&&this.sendVital({type:"FCP",value:Number(n.startTime.toFixed(2))});},{type:"paint",buffered:true},true),this.safeObserve("event",r=>{let n=0,s=r.getEntries();for(let a of s){let l=(a.processingEnd??0)-(a.startTime??0);n=Math.max(n,l);}n>0&&this.sendVital({type:"INP",value:Number(n.toFixed(2))});},{type:"event",buffered:true});}async initWebVitals(){try{let{onLCP:e,onCLS:t,onFCP:r,onTTFB:n,onINP:s}=await import('web-vitals'),a=l=>d=>{let c=Number(d.value.toFixed(2));this.sendVital({type:l,value:c});};e(a("LCP"),{reportAllChanges:!1}),t(a("CLS"),{reportAllChanges:!1}),r(a("FCP"),{reportAllChanges:!1}),n(a("TTFB"),{reportAllChanges:!1}),s(a("INP"),{reportAllChanges:!1});}catch(e){o("debug","Failed to load web-vitals library, using fallback",{error:e}),this.observeWebVitalsFallback();}}reportTTFB(){try{let e=performance.getEntriesByType("navigation")[0];if(!e)return;let t=e.responseStart;typeof t=="number"&&Number.isFinite(t)&&this.sendVital({type:"TTFB",value:Number(t.toFixed(2))});}catch(e){o("debug","Failed to report TTFB",{error:e});}}observeLongTasks(){this.safeObserve("longtask",e=>{let t=e.getEntries();for(let r of t){let n=Number(r.duration.toFixed(2)),s=Date.now();s-this.lastLongTaskSentAt>=bt&&(this.shouldSendVital("LONG_TASK",n)&&this.trackWebVital("LONG_TASK",n),this.lastLongTaskSentAt=s);}},{type:"longtask",buffered:true});}sendVital(e){if(!this.shouldSendVital(e.type,e.value))return;let t=this.getNavigationId();if(t){let r=this.reportedByNav.get(t);if(r?.has(e.type))return;if(r)r.add(e.type);else if(this.reportedByNav.set(t,new Set([e.type])),this.navigationHistory.push(t),this.navigationHistory.length>wt){let s=this.navigationHistory.shift();s&&this.reportedByNav.delete(s);}}this.trackWebVital(e.type,e.value);}trackWebVital(e,t){if(!Number.isFinite(t)){o("debug","Invalid web vital value",{data:{type:e,value:t}});return}this.eventManager.track({type:"web_vitals",web_vitals:{type:e,value:t}});}getNavigationId(){try{let e=performance.getEntriesByType("navigation")[0];if(!e)return null;let t=e.startTime||performance.now(),r=++this.navigationCounter,n=`${t.toFixed(2)}_${window.location.pathname}`;return r>1?`${n}_${r}`:n}catch(e){return o("debug","Failed to get navigation ID",{error:e}),null}}isObserverSupported(e){if(typeof PerformanceObserver>"u")return false;let t=PerformanceObserver.supportedEntryTypes;return !t||t.includes(e)}safeObserve(e,t,r,n=false){try{if(!this.isObserverSupported(e))return !1;let s=new PerformanceObserver((a,l)=>{try{t(a,l);}catch(d){o("debug","Observer callback failed",{error:d,data:{type:e}});}if(n)try{l.disconnect();}catch{}});return s.observe(r??{type:e,buffered:!0}),n||this.observers.push(s),!0}catch(s){return o("debug","Failed to create performance observer",{error:s,data:{type:e}}),false}}shouldSendVital(e,t){if(typeof t!="number"||!Number.isFinite(t))return o("debug","Invalid web vital value",{data:{type:e,value:t}}),false;let r=this.vitalThresholds[e];return !(typeof r=="number"&&t<=r)}};var we=class i extends h{eventManager;recentErrors=new Map;errorBurstCounter=0;burstWindowStart=0;burstBackoffUntil=0;constructor(e){super(),this.eventManager=e;}startTracking(){window.addEventListener("error",this.handleError),window.addEventListener("unhandledrejection",this.handleRejection);}stopTracking(){window.removeEventListener("error",this.handleError),window.removeEventListener("unhandledrejection",this.handleRejection),this.recentErrors.clear(),this.errorBurstCounter=0,this.burstWindowStart=0,this.burstBackoffUntil=0;}shouldSample(){let e=Date.now();if(e<this.burstBackoffUntil)return false;if(e-this.burstWindowStart>1e3&&(this.errorBurstCounter=0,this.burstWindowStart=e),this.errorBurstCounter++,this.errorBurstCounter>10)return this.burstBackoffUntil=e+5e3,o("debug","Error burst detected - entering cooldown",{data:{errorsInWindow:this.errorBurstCounter,cooldownMs:5e3}}),false;let r=this.get("config").errorSampling??1;return Math.random()<r}handleError=e=>{if(!this.shouldSample())return;let t=this.sanitize(e.message||"Unknown error");if(this.shouldSuppressError("js_error",t))return;let r=typeof e.error?.stack=="string"?this.truncateStack(e.error.stack):void 0,n=typeof e.error?.name=="string"&&e.error.name!=="Error"?e.error.name:void 0;this.eventManager.track({type:"error",error_data:{type:"js_error",message:t,...n!==void 0&&{name:n},...e.filename!==""&&{filename:e.filename},...e.lineno!==0&&{line:e.lineno},...e.colno!==0&&{column:e.colno},...r!==void 0&&{stack:r}}});};handleRejection=e=>{if(!this.shouldSample())return;let t=this.extractRejectionMessage(e.reason),r=this.sanitize(t);if(this.shouldSuppressError("promise_rejection",r))return;let n=e.reason instanceof Error&&typeof e.reason.stack=="string"?this.truncateStack(e.reason.stack):void 0,s=e.reason instanceof Error&&e.reason.name!=="Error"?e.reason.name:void 0;this.eventManager.track({type:"error",error_data:{type:"promise_rejection",message:r,...s!==void 0&&{name:s},...n!==void 0&&{stack:n}}});};extractRejectionMessage(e){if(e==null)return "Unknown rejection";if(typeof e=="string")return e;if(e instanceof Error)return e.message;if(typeof e=="object"&&"message"in e)return String(e.message);try{return JSON.stringify(e)}catch{return "Unserializable rejection"}}sanitize(e){let t=e.length>500?e.slice(0,500)+"...":e;return this.sanitizePii(t)}sanitizePii(e){let t=e;for(let r of $){let n=new RegExp(r.source,r.flags);t=t.replace(n,"[REDACTED]");}return t}shouldSuppressError(e,t){let r=Date.now(),n=`${e}:${t}`,s=this.recentErrors.get(n);return s!==void 0&&r-s<5e3?(this.recentErrors.set(n,r),true):(this.recentErrors.set(n,r),this.recentErrors.size>100?(this.recentErrors.clear(),this.recentErrors.set(n,r),false):(this.recentErrors.size>50&&this.pruneOldErrors(),false))}static TRUNCATION_SUFFIX=`
2
- ...truncated`;truncateStack(e){if(e.length<=2e3)return this.sanitizePii(e);let t=2e3-i.TRUNCATION_SUFFIX.length,r=e.slice(0,t)+i.TRUNCATION_SUFFIX;return this.sanitizePii(r)}pruneOldErrors(){let e=Date.now();for(let[n,s]of this.recentErrors.entries())e-s>5e3&&this.recentErrors.delete(n);if(this.recentErrors.size<=50)return;let t=Array.from(this.recentErrors.entries()).sort((n,s)=>n[1]-s[1]),r=this.recentErrors.size-50;for(let n=0;n<r;n+=1){let s=t[n];s&&this.recentErrors.delete(s[0]);}}};var Me=class extends h{isInitialized=false;suppressNextScrollTimer=null;pageUnloadHandler=null;pageShowHandler=null;visibilityFlushHandler=null;emitter=new de;transformers={};customHeadersProvider;managers={};handlers={};integrationInstances={};get initialized(){return this.isInitialized}async init(e={}){if(this.isInitialized)return {sessionId:this.get("sessionId")??""};this.managers.storage=new Ie;try{this.setupState(e);let t=e.integrations?.custom?.headers??{},r=e.integrations?.custom?.fetchCredentials??"include";return this.managers.event=new pe(this.managers.storage,this.emitter,this.transformers,t,this.customHeadersProvider,r),this.loadPersistedIdentity(),this.initializeHandlers(),this.setupPageLifecycleListeners(),await this.managers.event.recoverPersistedEvents().catch(n=>{o("warn","Failed to recover persisted events",{error:n});}),this.isInitialized=!0,{sessionId:this.get("sessionId")??""}}catch(t){this.destroy(true);let r=t instanceof Error?t.message:String(t);throw new Error(`[TraceLog] TraceLog initialization failed: ${r}`)}}async flushImmediately(){return await this.managers.event?.flushImmediately()??false}flushImmediatelySync(){return this.managers.event?.flushImmediatelySync()??false}sendCustomEvent(e,t,r){if(!this.managers.event){o("warn","Cannot send custom event: TraceLog not initialized",{data:{name:e}});return}let n=t;t&&typeof t=="object"&&!Array.isArray(t)&&Object.getPrototypeOf(t)!==Object.prototype&&(n=Object.assign({},t));let{valid:s,error:a,sanitizedMetadata:l}=Bt(e,n);if(!s){if(this.get("mode")==="qa")throw new Error(`[TraceLog] Custom event "${e}" validation failed: ${a}`);o("warn",`Custom event "${e}" dropped: ${a}`);return}this.managers.event.track({type:"custom",custom_event:{name:e,...l&&{metadata:l}}}),r?.critical===true&&(this.managers.event.flushImmediatelySync()||o("debug","Critical event flush returned false (deferred to in-flight send or empty queue)",{data:{name:e}}));}on(e,t){this.emitter.on(e,t);}off(e,t){this.emitter.off(e,t);}setTransformer(e,t){if(typeof t!="function")throw new Error(`[TraceLog] Transformer must be a function, received: ${typeof t}`);this.transformers[e]=t;}removeTransformer(e){delete this.transformers[e];}getTransformer(e){return this.transformers[e]}setCustomHeaders(e){if(typeof e!="function")throw new Error(`[TraceLog] Custom headers provider must be a function, received: ${typeof e}`);this.customHeadersProvider=e,this.managers.event&&this.managers.event.setCustomHeadersProvider(e);}removeCustomHeaders(){this.customHeadersProvider=void 0,this.managers.event&&this.managers.event.removeCustomHeadersProvider();}destroy(e=false){!this.isInitialized&&!e||(Object.values(this.handlers).filter(Boolean).forEach(t=>{try{t.stopTracking();}catch(r){o("warn","Failed to stop tracking",{error:r});}}),this.suppressNextScrollTimer&&(clearTimeout(this.suppressNextScrollTimer),this.suppressNextScrollTimer=null),this.pageUnloadHandler&&(window.removeEventListener("pagehide",this.pageUnloadHandler),window.removeEventListener("beforeunload",this.pageUnloadHandler),this.pageUnloadHandler=null),this.pageShowHandler&&(window.removeEventListener("pageshow",this.pageShowHandler),this.pageShowHandler=null),this.visibilityFlushHandler&&(document.removeEventListener("visibilitychange",this.visibilityFlushHandler),this.visibilityFlushHandler=null),this.managers.event?.flushImmediatelySync(),this.managers.event?.stop(),this.emitter.removeAllListeners(),this.transformers.beforeSend=void 0,this.transformers.beforeBatch=void 0,this.customHeadersProvider=void 0,this.set("suppressNextScroll",false),this.set("sessionId",null),this.set("identity",void 0),this.clearPersistedIdentity(),this.integrationInstances.shopifyCartLinker?.deactivate(),this.integrationInstances={},this.isInitialized=false,this.handlers={},this.managers={});}setupState(e={}){this.set("config",e);let t=he.getId(this.managers.storage);this.set("userId",t);let r=xt(e);this.set("collectApiUrls",r);let n=_t();this.set("device",n);let s=Q(window.location.href,e.sensitiveQueryParams);this.set("pageUrl",s),At()&&this.set("mode","qa");}getConfig(){return this.get("config")}getCollectApiUrls(){return this.get("collectApiUrls")}getEventManager(){return this.managers.event}getSessionId(){return this.get("sessionId")}getUserId(){return this.get("userId")}validateGlobalMetadata(e){if(typeof e!="object"||e===null||Array.isArray(e))return {valid:false,error:"Global metadata must be a plain object"};let t=ce("Global",e,"globalMetadata");return t.valid?{valid:true}:{valid:false,error:t.error}}updateGlobalMetadata(e){let t=this.validateGlobalMetadata(e);if(!t.valid)throw new Error(`[TraceLog] Invalid global metadata: ${t.error}`);let n={...this.get("config"),globalMetadata:e};this.set("config",n),o("debug","Global metadata updated (replaced)",{data:{keys:Object.keys(e)}});}mergeGlobalMetadata(e){let t=this.validateGlobalMetadata(e);if(!t.valid)throw new Error(`[TraceLog] Invalid global metadata: ${t.error}`);let r=this.get("config"),s={...r.globalMetadata??{},...e},a={...r,globalMetadata:s};this.set("config",a),o("debug","Global metadata updated (merged)",{data:{keys:Object.keys(e)}});}identify(e,t){if(!e||typeof e!="string"||e.trim().length===0){o("warn","identify() called with invalid userId",{data:{type:typeof e,length:typeof e=="string"?e.trim().length:0}});return}if(e.trim().length>256){o("warn","identify() userId exceeds 256 characters",{data:{length:e.trim().length}});return}let r=e.trim(),n=le(t),s={userId:r,...n?{traits:n}:{}};this.set("identity",s),this.persistIdentity(s),o("debug","Visitor identified",{data:{userIdLength:r.length,traitKeys:n?Object.keys(n):[]}});}async resetIdentity(){await this.managers.event?.flushImmediately(),this.set("identity",void 0),this.clearPersistedIdentity();let e=ae();this.managers.storage.setItem(U,e),this.set("userId",e),this.set("hasStartSession",false),this.set("sessionId",null),this.handlers.session?.stopTracking(),this.handlers.session?.startTracking(),o("debug","Identity reset, new UUID generated");}getProjectId(){return this.get("config")?.integrations?.tracelog?.projectId??"custom"}persistIdentity(e){try{let t=this.getProjectId(),r=Z(t);this.managers.storage.setItem(r,JSON.stringify(e));}catch{o("debug","Failed to persist identity to localStorage");}}loadPersistedIdentity(){let e=this.managers.storage,t=this.getProjectId(),r=Z(t);try{let n=e.getItem(M);if(n){let s=JSON.parse(n);if(e.removeItem(M),!this.isValidIdentityData(s)){o("debug","Invalid pending identity in localStorage, discarded");return}let a={...s,userId:s.userId.trim()};e.setItem(r,JSON.stringify(a)),this.set("identity",a),o("debug","Migrated pending identity to project-scoped key");return}}catch{e.removeItem(M);}try{let n=e.getItem(r);if(n){let s=JSON.parse(n);if(!this.isValidIdentityData(s)){e.removeItem(r),o("debug","Invalid persisted identity in localStorage, discarded");return}let a={...s,userId:s.userId.trim()};this.set("identity",a),o("debug","Loaded persisted identity");}}catch{o("debug","Failed to load persisted identity");}}isValidIdentityData(e){if(!e||typeof e!="object")return false;let{userId:t,traits:r}=e;if(typeof t!="string"||t.trim().length===0||t.trim().length>256)return false;if(r!==void 0){if(typeof r!="object"||r===null||Array.isArray(r))return false;for(let n of Object.values(r))if(typeof n!="string")return false}return true}clearPersistedIdentity(){try{let e=this.managers.storage,t=this.getProjectId();e.removeItem(Z(t)),e.removeItem(M);}catch{o("debug","Failed to clear persisted identity");}}setupPageLifecycleListeners(){this.pageUnloadHandler=()=>{this.managers.event?.flushImmediatelySync();},this.pageShowHandler=e=>{e.persisted&&this.managers.event?.recoverPersistedEvents().catch(t=>{o("warn","Failed to recover persisted events on bfcache restore",{error:t});});},this.visibilityFlushHandler=()=>{typeof document>"u"||!document.hidden||this.get("config").flushOnPageHidden!==false&&this.managers.event?.flushImmediatelySync();},window.addEventListener("pagehide",this.pageUnloadHandler),window.addEventListener("beforeunload",this.pageUnloadHandler),window.addEventListener("pageshow",this.pageShowHandler),document.addEventListener("visibilitychange",this.visibilityFlushHandler);}initializeHandlers(){let e=this.get("config");this.handlers.session=new Ee(this.managers.storage,this.managers.event),this.handlers.session.startTracking();let t=()=>{this.set("suppressNextScroll",true),this.suppressNextScrollTimer&&clearTimeout(this.suppressNextScrollTimer),this.suppressNextScrollTimer=window.setTimeout(()=>{this.set("suppressNextScroll",false);},500);};if(this.handlers.pageView=new ve(this.managers.event,t),this.handlers.pageView.startTracking(),this.handlers.click=new Se(this.managers.event),this.handlers.click.startTracking(),this.handlers.scroll=new ye(this.managers.event),this.handlers.scroll.startTracking(),this.handlers.performance=new be(this.managers.event),this.handlers.performance.startTracking().catch(r=>{o("warn","Failed to start performance tracking",{error:r});}),this.handlers.error=new we(this.managers.event),this.handlers.error.startTracking(),e.viewport&&(this.handlers.viewport=new _e(this.managers.event),this.handlers.viewport.startTracking()),e.integrations?.tracelog?.shopify){let r=new K;r.activate(),this.integrationInstances.shopifyCartLinker=r,this.emitter.on("event",n=>{n.type==="session_start"&&r.onSessionChange();});}}};var k=[],w=[],D=null,u=null,L=false,T=false,x=null,ar=async i=>typeof window>"u"||typeof document>"u"?{sessionId:""}:(T=false,window.__traceLogDisabled===true?{sessionId:""}:u?{sessionId:u.getSessionId()??""}:(L&&x||(L=true,x=(async()=>{try{let e=Vt(i??{}),t=new Me;try{k.forEach(({event:a,callback:l})=>{t.on(a,l);}),k.length=0,w.forEach(({hook:a,fn:l})=>{a==="beforeSend"?t.setTransformer("beforeSend",l):t.setTransformer("beforeBatch",l);}),w.length=0,D&&(t.setCustomHeaders(D),D=null);let r=t.init(e),n=new Promise((a,l)=>{setTimeout(()=>{l(new Error(`[TraceLog] Initialization timeout after ${1e4}ms`));},1e4);}),s=await Promise.race([r,n]);return u=t,s}catch(r){try{t.destroy(!0);}catch(n){o("error","Failed to cleanup partially initialized app",{error:n});}throw r}}catch(e){throw u=null,e}finally{L=false,x=null;}})()),x)),lr=(i,e,t)=>{if(!(typeof window>"u"||typeof document>"u")){if(!u)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(T)throw new Error("[TraceLog] Cannot send events while TraceLog is being destroyed");u.sendCustomEvent(i,e,t);}},cr=async()=>typeof window>"u"||typeof document>"u"||!u||T?false:u.flushImmediately(),dr=()=>typeof window>"u"||typeof document>"u"||!u||T?false:u.flushImmediatelySync(),ur=(i,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!u||L){k.push({event:i,callback:e});return}u.on(i,e);}},mr=(i,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!u){let t=k.findIndex(r=>r.event===i&&r.callback===e);t!==-1&&k.splice(t,1);return}u.off(i,e);}};function pr(i,e){if(!(typeof window>"u"||typeof document>"u")){if(typeof e!="function")throw new Error(`[TraceLog] Transformer must be a function, received: ${typeof e}`);if(!u||L){let t=w.findIndex(r=>r.hook===i);t!==-1&&w.splice(t,1),w.push({hook:i,fn:e});return}if(T)throw new Error("[TraceLog] Cannot set transformers while TraceLog is being destroyed");i==="beforeSend"?u.setTransformer("beforeSend",e):u.setTransformer("beforeBatch",e);}}var fr=i=>{if(!(typeof window>"u"||typeof document>"u")){if(!u){let e=w.findIndex(t=>t.hook===i);e!==-1&&w.splice(e,1);return}if(T)throw new Error("[TraceLog] Cannot remove transformers while TraceLog is being destroyed");u.removeTransformer(i);}},hr=i=>{if(!(typeof window>"u"||typeof document>"u")){if(typeof i!="function")throw new Error(`[TraceLog] Custom headers provider must be a function, received: ${typeof i}`);if(!u||L){D=i;return}if(T)throw new Error("[TraceLog] Cannot set custom headers while TraceLog is being destroyed");u.setCustomHeaders(i);}},gr=()=>{if(!(typeof window>"u"||typeof document>"u")){if(!u){D=null;return}if(T)throw new Error("[TraceLog] Cannot remove custom headers while TraceLog is being destroyed");u.removeCustomHeaders();}},Er=()=>typeof window>"u"||typeof document>"u"?false:u!==null,vr=()=>typeof window>"u"||typeof document>"u"||!u?null:u.getSessionId(),Sr=()=>typeof window>"u"||typeof document>"u"||!u?null:u.getUserId(),Tr=()=>{if(!(typeof window>"u"||typeof document>"u")){if(T)throw new Error("[TraceLog] Destroy operation already in progress");if(!u){T=false;return}T=true;try{u.destroy(),u=null,L=!1,x=null,k.length=0,w.length=0,D=null,T=!1;}catch(i){u=null,L=false,x=null,k.length=0,w.length=0,D=null,T=false,o("warn","Error during destroy, forced cleanup completed",{error:i});}}},yr=i=>{typeof window>"u"||typeof document>"u"||Ct(i);},_r=i=>{if(!(typeof window>"u"||typeof document>"u")){if(!u)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(T)throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");u.updateGlobalMetadata(i);}},Ir=i=>{if(!(typeof window>"u"||typeof document>"u")){if(!u)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(T)throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");u.mergeGlobalMetadata(i);}},br=(i,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!i||typeof i!="string"||i.trim().length===0){o("warn","identify() called with invalid userId");return}if(i.trim().length>256){o("warn","identify() userId exceeds 256 characters");return}if(T){o("warn","Cannot identify while TraceLog is being destroyed");return}if(u){u.identify(i,e);return}try{let t=le(e),r={userId:i.trim(),...t?{traits:t}:{}};localStorage.setItem(M,JSON.stringify(r)),o("debug","Identity persisted pre-init (will be applied on init)");}catch{o("debug","Failed to persist pre-init identity");}}},wr=async()=>{if(!(typeof window>"u"||typeof document>"u")){if(!u){try{localStorage.removeItem(M);}catch{}return}if(T)throw new Error("[TraceLog] Cannot reset identity while TraceLog is being destroyed");await u.resetIdentity();}};var Fa={init:ar,event:lr,on:ur,off:mr,setTransformer:pr,removeTransformer:fr,setCustomHeaders:hr,removeCustomHeaders:gr,isInitialized:Er,getSessionId:vr,getUserId:Sr,destroy:Tr,setQaMode:yr,updateGlobalMetadata:_r,mergeGlobalMetadata:Ir,identify:br,resetIdentity:wr,flushImmediately:cr,flushImmediatelySync:dr};export{p as AppConfigValidationError,A as DEFAULT_SESSION_TIMEOUT,W as DEFAULT_WEB_VITALS_MODE,ht as DeviceType,Ue as EmitterEvent,Et as ErrorType,I as EventType,vt as InitializationTimeoutError,b as IntegrationValidationError,Ce as MAX_ARRAY_LENGTH,q as MAX_CUSTOM_EVENT_ARRAY_SIZE,Y as MAX_CUSTOM_EVENT_KEYS,X as MAX_CUSTOM_EVENT_NAME_LENGTH,z as MAX_CUSTOM_EVENT_STRING_SIZE,Ae as MAX_NESTED_OBJECT_KEYS,C as MAX_STRING_LENGTH,J as MAX_STRING_LENGTH_IN_ARRAY,He as Mode,$ as PII_PATTERNS,R as PermanentError,H as RateLimitError,B as SamplingRateValidationError,gt as ScrollDirection,ee as SessionTimeoutValidationError,ft as SpecialApiUrl,F as TimeoutError,O as TraceLogValidationError,xr as WEB_VITALS_GOOD_THRESHOLDS,Qe as WEB_VITALS_NEEDS_IMPROVEMENT_THRESHOLDS,It as WEB_VITALS_POOR_THRESHOLDS,re as getWebVitalsThresholds,Un as isPrimaryScrollEvent,Hn as isSecondaryScrollEvent,Fa as tracelog};//# sourceMappingURL=public-api.js.map
1
+ var w=9e5;var j=120,K=49152,W=100,G=500,Me=200;var M=1e3,X=500,Re=1e3;var _="data-tlog",Je=["button","a",'input[type="button"]','input[type="submit"]','input[type="reset"]','input[type="checkbox"]','input[type="radio"]',"select","textarea",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="option"]','[role="checkbox"]','[role="radio"]','[role="switch"]',"[routerLink]","[ng-click]","[data-action]","[data-click]","[data-navigate]","[data-toggle]","[onclick]",".btn",".button",".clickable",".nav-link",".menu-item","[data-testid]",'[tabindex="0"]'],Ze=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],et=["token","auth","key","session","reset","password","api_key","apikey","secret","access_token","refresh_token","verification","code","otp"];var v={INVALID_SESSION_TIMEOUT:"Session timeout must be between 30000ms (30 seconds) and 86400000ms (24 hours)",INVALID_SAMPLING_RATE:"Sampling rate must be between 0 and 1",INVALID_ERROR_SAMPLING_RATE:"Error sampling must be between 0 and 1",INVALID_TRACELOG_PROJECT_ID:"TraceLog project ID is required when integration is enabled",INVALID_GLOBAL_METADATA:"Global metadata must be an object",INVALID_SENSITIVE_QUERY_PARAMS:"Sensitive query params must be an array of strings",INVALID_PAGE_VIEW_THROTTLE:"Page view throttle must be a non-negative number",INVALID_CLICK_THROTTLE:"Click throttle must be a non-negative number",INVALID_MAX_SAME_EVENT_PER_MINUTE:"Max same event per minute must be a positive number",INVALID_SEND_INTERVAL:"Send interval must be between 1000ms (1 second) and 60000ms (60 seconds)"},tt=[/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,/javascript:/gi,/on\w+\s*=/gi,/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,/<embed\b[^>]*>/gi,/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi];var m="tlog",C=`${m}:qa_mode`,P=`${m}:uid`,Ae="tlog_mode",Le="qa",Ce="qa_off",z=i=>i?`${m}:${i}:queue`:`${m}:queue`,Y=i=>i?`${m}:${i}:rate_limit`:`${m}:rate_limit`,rt=i=>i?`${m}:${i}:session`:`${m}:session`;var nt=i=>i?`${m}:${i}:broadcast`:`${m}:broadcast`,Ne=(i,e)=>`${m}:${i}:session_counts:${e}`,Oe=10080*60*1e3,xe=`${m}:session_counts_last_cleanup`,Pe=3600*1e3,q=i=>i?`${m}:${i}:identity`:`${m}:identity`,I=`${m}:pending_identity`;var it=(t=>(t.Localhost="localhost:8080",t.Fail="localhost:9999",t))(it||{});var st=(n=>(n.Mobile="mobile",n.Tablet="tablet",n.Desktop="desktop",n.Unknown="unknown",n))(st||{});var J=(t=>(t.EVENT="event",t.QUEUE="queue",t))(J||{});var b=class i extends Error{constructor(t,r,n){super(t);this.statusCode=r;this.responseCode=n;this.name="PermanentError",Error.captureStackTrace&&Error.captureStackTrace(this,i);}},k=class i extends Error{constructor(e){super(e),this.name="RateLimitError",Error.captureStackTrace&&Error.captureStackTrace(this,i);}},D=class i extends Error{constructor(e){super(e),this.name="TimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,i);}};var T=(l=>(l.PAGE_VIEW="page_view",l.CLICK="click",l.SCROLL="scroll",l.SESSION_START="session_start",l.CUSTOM="custom",l.WEB_VITALS="web_vitals",l.ERROR="error",l))(T||{}),ot=(t=>(t.UP="up",t.DOWN="down",t))(ot||{}),at=(t=>(t.JS_ERROR="js_error",t.PROMISE_REJECTION="promise_rejection",t))(at||{});var ke=(e=>(e.QA="qa",e))(ke||{});var R=class extends Error{constructor(t,r,n){super(t);this.errorCode=r;this.layer=n;this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}},h=class extends R{constructor(e,t="config"){super(e,"APP_CONFIG_INVALID",t);}},Z=class extends R{constructor(e,t="config"){super(e,"SESSION_TIMEOUT_INVALID",t);}},U=class extends R{constructor(e,t="config"){super(e,"SAMPLING_RATE_INVALID",t);}},V=class extends R{constructor(e,t="config"){super(e,"INTEGRATION_INVALID",t);}},lt=class extends R{constructor(t,r,n="runtime"){super(t,"INITIALIZATION_TIMEOUT",n);this.timeoutMs=r;}};var or=["gclid","gbraid","wbraid","fbclid","ttclid"],ee=()=>{let i=new URLSearchParams(window.location.search),e={};return or.forEach(r=>{let n=i.get(r);n&&(e[r]=n);}),Object.keys(e).length?e:void 0};var ct="background: #ff9800; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;",dt="background: #9e9e9e; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;",ut="background: #d32f2f; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;";var ar=(i,e)=>{if(e){if(e instanceof Error){let t=e.message.replace(/\s+at\s+.*$/gm,"").replace(/\s*\([^()]+:\d+:\d+\)/g,"");return `[TraceLog] ${i}: ${t}`}if(e instanceof Error)return `[TraceLog] ${i}: ${e.message}`;if(typeof e=="string")return `[TraceLog] ${i}: ${e}`;if(typeof e=="object")try{return `[TraceLog] ${i}: ${JSON.stringify(e)}`}catch{return `[TraceLog] ${i}: [Unable to serialize error]`}return `[TraceLog] ${i}: ${String(e)}`}return `[TraceLog] ${i}`},lr=()=>{if(typeof window>"u"||typeof sessionStorage>"u")return false;try{return sessionStorage.getItem(C)==="true"}catch{return false}},a=(i,e,t)=>{let{error:r,data:n,showToClient:s=false,style:o,visibility:l}=t??{},c=r?ar(e,r):`[TraceLog] ${e}`,d=i==="error"?"error":i==="warn"?"warn":"log";if(!cr(l,s))return;let f=dr(l,o),be=n!==void 0?De(n):void 0;pt(d,c,f,be);},cr=(i,e)=>i==="critical"?true:i==="qa"||e?lr():false,dr=(i,e)=>e!==void 0&&e!==""?e:i==="critical"?ut:"",pt=(i,e,t,r)=>{let n=t!==void 0&&t!=="",s=n?`%c${e}`:e;r!==void 0?n?console[i](s,t,r):console[i](s,r):n?console[i](s,t):console[i](s);},De=i=>{let e={},t=["token","password","secret","key","apikey","api_key","sessionid","session_id"];for(let[r,n]of Object.entries(i)){let s=r.toLowerCase();if(t.some(o=>s.includes(o))){e[r]="[REDACTED]";continue}n!==null&&typeof n=="object"&&!Array.isArray(n)?e[r]=De(n):Array.isArray(n)?e[r]=n.map(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)?De(o):o):e[r]=n;}return e};var Ue,gt,ur=()=>{typeof window<"u"&&!Ue&&(Ue=window.matchMedia("(pointer: coarse)"),gt=window.matchMedia("(hover: none)"));},te="Unknown",pr=i=>{let e=i.userAgentData?.platform;if(e!=null&&e!==""){if(/windows/i.test(e))return "Windows";if(/macos/i.test(e))return "macOS";if(/android/i.test(e))return "Android";if(/linux/i.test(e))return "Linux";if(/chromeos/i.test(e))return "ChromeOS";if(/ios/i.test(e))return "iOS"}let t=navigator.userAgent;return /Windows/i.test(t)?"Windows":/iPhone|iPad|iPod/i.test(t)?"iOS":/Mac OS X|Macintosh/i.test(t)?"macOS":/Android/i.test(t)?"Android":/CrOS/i.test(t)?"ChromeOS":/Linux/i.test(t)?"Linux":te},gr=i=>{let e=i.userAgentData?.brands;if(e!=null&&e.length>0){let n=e.filter(s=>!/not.?a.?brand|chromium/i.test(s.brand))[0];if(n!=null){let s=n.brand;return /google chrome/i.test(s)?"Chrome":/microsoft edge/i.test(s)?"Edge":/opera/i.test(s)?"Opera":s}}let t=navigator.userAgent;return /Edg\//i.test(t)?"Edge":/OPR\//i.test(t)?"Opera":/Chrome/i.test(t)?"Chrome":/Firefox/i.test(t)?"Firefox":/Safari/i.test(t)&&!/Chrome/i.test(t)?"Safari":te},hr=()=>{try{let i=navigator;if(i.userAgentData!=null&&typeof i.userAgentData.mobile=="boolean"){let c=i.userAgentData.platform;return c!=null&&c!==""&&/ipad|tablet/i.test(c)?"tablet":i.userAgentData.mobile?"mobile":"desktop"}ur();let e=window.innerWidth,t=Ue?.matches??!1,r=gt?.matches??!1,n="ontouchstart"in window||navigator.maxTouchPoints>0,s=navigator.userAgent.toLowerCase(),o=/mobile|android|iphone|ipod|blackberry|iemobile|opera mini/.test(s),l=/tablet|ipad|android(?!.*mobile)/.test(s);return e<=767||o&&n?"mobile":e>=768&&e<=1024||l||t&&r&&n?"tablet":"desktop"}catch(i){return a("debug","Device detection failed, defaulting to desktop",{error:i}),"desktop"}},ht=()=>{try{let i=navigator;return {type:hr(),os:pr(i),browser:gr(i)}}catch(i){return a("debug","Device info detection failed, using defaults",{error:i}),{type:"desktop",os:te,browser:te}}};var mr={LCP:2500,FCP:1800,CLS:.1,INP:200,TTFB:800},Ve={LCP:2500,FCP:1800,CLS:.1,INP:200,TTFB:800},mt={LCP:4e3,FCP:3e3,CLS:.25,INP:500,TTFB:1800},H="needs-improvement",re=(i=H)=>{switch(i){case "all":return {LCP:0,FCP:0,CLS:0,INP:0,TTFB:0};case "needs-improvement":return Ve;case "poor":return mt;default:return Ve}},ft=50;var Et="3.0.0";var vt=Et;var Er=()=>typeof window<"u"&&typeof sessionStorage<"u",vr=()=>{try{let i=new URLSearchParams(window.location.search);i.delete(Ae);let e=i.toString(),t=window.location.pathname+(e?"?"+e:"")+window.location.hash;window.history.replaceState({},"",t);}catch{}},St=()=>{if(!Er())return false;try{let e=new URLSearchParams(window.location.search).get(Ae),t=sessionStorage.getItem(C),r=null;return e===Le?(r=!0,sessionStorage.setItem(C,"true"),a("info","QA Mode ACTIVE",{visibility:"qa",style:ct})):e===Ce&&(r=!1,sessionStorage.setItem(C,"false"),a("info","QA Mode DISABLED",{visibility:"qa",style:dt})),(e===Le||e===Ce)&&vr(),r??t==="true"}catch{return false}};var ne=()=>typeof document<"u"&&document.prerendering===true;var Sr=["co.uk","org.uk","com.au","net.au","com.br","co.nz","co.jp","com.mx","co.in","com.cn","co.za"],Tt=i=>{let e=i.toLowerCase().split(".");if(e.length<=2)return i.toLowerCase();let t=e.slice(-2).join(".");return Sr.includes(t)?e.slice(-3).join("."):e.slice(-2).join(".")},Tr=(i,e)=>i===e?true:Tt(i)===Tt(e),ie=()=>{let i=document.referrer;if(!i)return "Direct";try{let e=new URL(i).hostname.toLowerCase(),t=window.location.hostname.toLowerCase();return Tr(e,t)?"Direct":i}catch(e){return a("debug","Failed to parse referrer URL, using raw value",{error:e,data:{referrer:i}}),i}};var se=()=>{let i=new URLSearchParams(window.location.search),e={};return Ze.forEach(r=>{let n=i.get(r);if(n){let s=r.split("utm_")[1];e[s]=n;}}),Object.keys(e).length?e:void 0};var le=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return (i==="x"?e:e&3|8).toString(16)}),oe=0,ae=0,_t=()=>{let i=Date.now();i<ae&&(i=ae),i===ae?oe=(oe+1)%1e3:oe=0,ae=i;let e=oe.toString().padStart(3,"0"),t="";try{if(typeof crypto<"u"&&crypto.getRandomValues){let r=crypto.getRandomValues(new Uint8Array(3));r&&(t=Array.from(r,n=>n.toString(16).padStart(2,"0")).join(""));}}catch{}return t||(t=Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")),`${i}-${e}-${t}`};var _r=i=>{try{return new URL(i).protocol==="https:"}catch{return false}},yr=i=>{try{let t=new URL(window.location.href).hostname;if(!t||typeof t!="string")throw new Error("Invalid hostname");if(t==="localhost"||t==="127.0.0.1"||/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t))throw new Error("SaaS integration requires a domain hostname; localhost and IP addresses are not supported. For local development, omit `integrations.tracelog` to run in standalone mode (events emitted locally, no network requests), or test against a staging domain that resolves to your dev machine via /etc/hosts.");let r=t.split(".");if(!r||!Array.isArray(r)||r.length===0||r.length===1&&r[0]==="")throw new Error("Invalid hostname structure");if(r.length===1)throw new Error("Single-part domain not supported for SaaS integration");let n=r.length===2?r.join("."):r.slice(-2).join(".");if(!n||n.split(".").length<2)throw new Error("Invalid domain structure for SaaS");let s=`https://${i}.${n}/collect`;if(!_r(s))throw new Error("Generated URL failed validation");return s}catch(e){throw new Error(`Invalid SaaS URL configuration: ${e instanceof Error?e.message:String(e)}`)}},yt=i=>{let e={};return i.integrations?.tracelog?.projectId&&(e.saas=yr(i.integrations.tracelog.projectId)),e},F=(i,e=[])=>{if(!i||typeof i!="string")return a("warn","Invalid URL provided to normalizeUrl",{data:{type:typeof i}}),i||"";try{let t=new URL(i),r=t.searchParams,n=[...new Set([...et,...e])],s=!1,o=[];return n.forEach(l=>{r.has(l)&&(r.delete(l),s=!0,o.push(l));}),!s&&i.includes("?")?i:(t.search=r.toString(),t.toString())}catch(t){return a("warn","URL normalization failed, returning original",{error:t,data:{urlLength:i?.length}}),i}};var It=i=>{if(!i||typeof i!="string"||i.trim().length===0)return "";let e=i;i.length>1e3&&(e=i.slice(0,Math.max(0,1e3)));let t=0;for(let n of tt){let s=e;e=e.replace(n,""),s!==e&&t++;}return t>0&&a("warn","XSS patterns detected and removed",{data:{patternMatches:t,valueLength:i.length}}),e.trim()},He=(i,e=0)=>{if(i==null)return null;if(typeof i=="string")return It(i);if(typeof i=="number")return !Number.isFinite(i)||i<-Number.MAX_SAFE_INTEGER||i>Number.MAX_SAFE_INTEGER?0:i;if(typeof i=="boolean")return i;if(e>10)return null;if(Array.isArray(i))return i.slice(0,1e3).map(n=>He(n,e+1)).filter(n=>n!==null);if(typeof i=="object"){let t={},n=Object.entries(i).slice(0,200);for(let[s,o]of n){let l=It(s);if(l){let c=He(o,e+1);c!==null&&(t[l]=c);}}return t}return null},bt=i=>{if(typeof i!="object"||i===null)return {};try{let e=He(i);return typeof e=="object"&&e!==null?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);throw new Error(`[TraceLog] Metadata sanitization failed: ${t}`)}};var wt=[/\b[A-Za-z0-9._%+-]{1,64}@(?:[A-Za-z0-9-]{1,63}\.)+[A-Za-z]{2,63}\b/gi,/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g,/\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/g,/\b[A-Z]{2}\d{2}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/gi,/\b[sp]k_(test|live)_[a-zA-Z0-9]{10,}\b/gi,/Bearer\s+[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?(?:\.[A-Za-z0-9_-]+)?/gi,/:\/\/[^:/]+:([^@]+)@/gi,/[?&](token|password|passwd|auth|secret|secret_key|private_key|auth_key|api_key|apikey|access_token)=[^&\s]+/gi],N=i=>{let e=i;for(let t of wt)e=e.replace(t,"[REDACTED]");return e};var Lr=i=>{if(i!==void 0&&(i===null||typeof i!="object"))throw new h("Configuration must be an object","config");if(i){if(i.sessionTimeout!==void 0&&(typeof i.sessionTimeout!="number"||i.sessionTimeout<3e4||i.sessionTimeout>864e5))throw new Z(v.INVALID_SESSION_TIMEOUT,"config");if(i.globalMetadata!==void 0&&(typeof i.globalMetadata!="object"||i.globalMetadata===null))throw new h(v.INVALID_GLOBAL_METADATA,"config");if(i.integrations&&Cr(i.integrations),i.sensitiveQueryParams!==void 0){if(!Array.isArray(i.sensitiveQueryParams))throw new h(v.INVALID_SENSITIVE_QUERY_PARAMS,"config");for(let e of i.sensitiveQueryParams)if(typeof e!="string")throw new h("All sensitive query params must be strings","config")}if(i.errorSampling!==void 0&&(typeof i.errorSampling!="number"||i.errorSampling<0||i.errorSampling>1))throw new U(v.INVALID_ERROR_SAMPLING_RATE,"config");if(i.samplingRate!==void 0&&(typeof i.samplingRate!="number"||i.samplingRate<0||i.samplingRate>1))throw new U(v.INVALID_SAMPLING_RATE,"config");if(i.pageViewThrottleMs!==void 0&&(typeof i.pageViewThrottleMs!="number"||i.pageViewThrottleMs<0))throw new h(v.INVALID_PAGE_VIEW_THROTTLE,"config");if(i.clickThrottleMs!==void 0&&(typeof i.clickThrottleMs!="number"||i.clickThrottleMs<0))throw new h(v.INVALID_CLICK_THROTTLE,"config");if(i.maxSameEventPerMinute!==void 0&&(typeof i.maxSameEventPerMinute!="number"||i.maxSameEventPerMinute<=0))throw new h(v.INVALID_MAX_SAME_EVENT_PER_MINUTE,"config");if(i.sendIntervalMs!==void 0&&(!Number.isFinite(i.sendIntervalMs)||i.sendIntervalMs<1e3||i.sendIntervalMs>6e4))throw new h(v.INVALID_SEND_INTERVAL,"config");if(i.flushOnSpaNavigation!==void 0&&typeof i.flushOnSpaNavigation!="boolean")throw new h(`Invalid flushOnSpaNavigation type: ${typeof i.flushOnSpaNavigation}. Must be a boolean`,"config");if(i.flushOnPageHidden!==void 0&&typeof i.flushOnPageHidden!="boolean")throw new h(`Invalid flushOnPageHidden type: ${typeof i.flushOnPageHidden}. Must be a boolean`,"config");if(i.webVitalsMode!==void 0){if(typeof i.webVitalsMode!="string")throw new h(`Invalid webVitalsMode type: ${typeof i.webVitalsMode}. Must be a string`,"config");let e=["all","needs-improvement","poor"];if(!e.includes(i.webVitalsMode))throw new h(`Invalid webVitalsMode: "${i.webVitalsMode}". Must be one of: ${e.join(", ")}`,"config")}if(i.webVitalsThresholds!==void 0){if(typeof i.webVitalsThresholds!="object"||i.webVitalsThresholds===null||Array.isArray(i.webVitalsThresholds))throw new h("webVitalsThresholds must be an object","config");let e=["LCP","FCP","CLS","INP","TTFB"];for(let[t,r]of Object.entries(i.webVitalsThresholds)){if(!e.includes(t))throw new h(`Invalid Web Vitals threshold key: "${t}". Must be one of: ${e.join(", ")}`,"config");if(typeof r!="number"||!Number.isFinite(r)||r<0)throw new h(`Invalid Web Vitals threshold value for ${t}: ${r}. Must be a non-negative finite number`,"config")}}}},Cr=i=>{if(i&&i.tracelog){if(!i.tracelog.projectId||typeof i.tracelog.projectId!="string"||i.tracelog.projectId.trim()==="")throw new V(v.INVALID_TRACELOG_PROJECT_ID,"config");if(i.tracelog.shopify!==void 0&&typeof i.tracelog.shopify!="boolean")throw new V("tracelog.shopify must be a boolean","config")}},Mt=i=>(Lr(i),{...i??{},sessionTimeout:i?.sessionTimeout??9e5,globalMetadata:i?.globalMetadata??{},sensitiveQueryParams:i?.sensitiveQueryParams??[],errorSampling:i?.errorSampling??1,samplingRate:i?.samplingRate??1,pageViewThrottleMs:i?.pageViewThrottleMs??1e3,clickThrottleMs:i?.clickThrottleMs??300,maxSameEventPerMinute:i?.maxSameEventPerMinute??60,sendIntervalMs:i?.sendIntervalMs??1e4,flushOnSpaNavigation:i?.flushOnSpaNavigation??false,flushOnPageHidden:i?.flushOnPageHidden??true});var Ke=(i,e=new Set)=>{if(i==null)return true;let t=typeof i;return t==="string"||t==="number"||t==="boolean"?true:t==="function"||t==="symbol"||t==="bigint"||e.has(i)?false:(e.add(i),Array.isArray(i)?i.every(r=>Ke(r,e)):t==="object"?Object.values(i).every(r=>Ke(r,e)):false)},Rt=i=>typeof i!="object"||i===null?false:Ke(i),$=i=>{if(typeof i!="object"||i===null||Array.isArray(i))return;let e={};for(let[t,r]of Object.entries(i))typeof r=="string"&&(e[t]=r);return Object.keys(e).length>0?e:void 0};var Lt=i=>typeof i!="string"?{valid:false,error:"Event name must be a string"}:i.length===0?{valid:false,error:"Event name cannot be empty"}:i.length>120?{valid:false,error:`Event name is too long (max ${120} characters)`}:i.includes("<")||i.includes(">")||i.includes("&")?{valid:false,error:"Event name contains invalid characters"}:["constructor","prototype","__proto__","eval","function","var","let","const"].includes(i.toLowerCase())?{valid:false,error:"Event name cannot be a reserved word"}:{valid:true},At=(i,e,t)=>{let r=bt(e),n=`${t} "${i}" metadata error`;if(!Rt(r))return {valid:false,error:`${n}: object has invalid types. Valid types are string, number, boolean or string arrays.`};let s;try{s=JSON.stringify(r);}catch{return {valid:false,error:`${n}: object contains circular references or cannot be serialized.`}}if(new TextEncoder().encode(s).byteLength>49152)return {valid:false,error:`${n}: object is too large (max ${49152/1024} KB).`};if(Object.keys(r).length>100)return {valid:false,error:`${n}: object has too many keys (max ${100} keys).`};for(let[c,d]of Object.entries(r)){if(Array.isArray(d)){if(d.length>500)return {valid:false,error:`${n}: array property "${c}" is too large (max ${500} items).`};for(let p of d)if(typeof p=="string"&&p.length>500)return {valid:false,error:`${n}: array property "${c}" contains strings that are too long (max ${500} characters).`}}if(typeof d=="string"&&d.length>1e3)return {valid:false,error:`${n}: property "${c}" is too long (max ${1e3} characters).`}}return {valid:true,sanitizedMetadata:r}},Ct=(i,e,t)=>{if(Array.isArray(e)){let r=[],n=`${t} "${i}" metadata error`;for(let s=0;s<e.length;s++){let o=e[s];if(typeof o!="object"||o===null||Array.isArray(o))return {valid:false,error:`${n}: array item at index ${s} must be an object.`};let l=At(i,o,t);if(!l.valid)return {valid:false,error:`${n}: array item at index ${s} is invalid: ${l.error}`};l.sanitizedMetadata&&r.push(l.sanitizedMetadata);}return {valid:true,sanitizedMetadata:r}}return At(i,e,t)};var Nt=(i,e)=>{let t=Lt(i);if(!t.valid)return a("error","Event name validation failed",{data:{eventName:i,error:t.error}}),t;if(!e)return {valid:true};let r=Ct(i,e,"customEvent");return r.valid||a("error","Event metadata validation failed",{data:{eventName:i,error:r.error}}),r};var ce=class{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);}off(e,t){let r=this.listeners.get(e);if(r){let n=r.indexOf(t);n>-1&&r.splice(n,1);}}emit(e,t){let r=this.listeners.get(e);r&&r.forEach(n=>{n(t);});}removeAllListeners(){this.listeners.clear();}};var Nr=/https?:\/\/\S+/g,Or=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,xr=/0x[0-9a-fA-F]{4,}/g,Pr=/(?<!\d)\d{4,}(?!\d)/g,kr=/(['"])[^'"]{20,}\1/g;function Dr(i){return i.replace(Nr,"[URL]").replace(Or,"[ID]").replace(xr,"[ADDR]").replace(Pr,"[N]").replace(kr,"$1[VAR]$1").toLowerCase().trim()}function Ot(i){let e=Dr(i.message),t=(i.filename??"").trim(),r=t.search(/[?#]/),n=r===-1?t:t.slice(0,r),s=i.line==null?"":String(i.line);return `${e}|${n}|${s}`}var We={config:{}};var u=class{get(e){return We[e]}set(e,t){We[e]=t;}getState(){return {...We}}};var de=class extends u{storeManager;apiUrl;lastPermanentErrorLog=null;recoveryInProgress=false;lastMetadataTimestamp=0;pendingControllers=new Set;consecutiveNetworkFailures=0;circuitOpenedAt=0;rateLimitedUntil=0;rateLimitStorageKeyAtArm=null;constructor(e,t){super(),this.storeManager=e,this.apiUrl=t,this.migrateLegacyV2Keys(),this.rateLimitedUntil=this.loadRateLimitCooldown();}migrateLegacyV2Keys(){let e=this.get("userId")||"anonymous",t=`${z(e)}:saas`,r=`${z(e)}:custom`,n=`${Y(e)}:saas`,s=`${Y(e)}:custom`;try{let o=this.storeManager.getItem(t);if(o){let l=this.getQueueStorageKey(),c=this.storeManager.getItem(l);c?this.mergeLegacyIntoCurrent(l,o,c):(this.storeManager.setItem(l,o),a("debug","Migrated v2 SaaS queue to v3 unscoped key")),this.storeManager.removeItem(t);}}catch(o){a("debug","Failed to migrate v2 SaaS queue, discarding legacy key",{error:o});try{this.storeManager.removeItem(t);}catch{}}[r,n,s].forEach(o=>{try{this.storeManager.getItem(o)!==null&&this.storeManager.removeItem(o);}catch{}});}mergeLegacyIntoCurrent(e,t,r){try{let n=JSON.parse(t),s=JSON.parse(r);if(!Array.isArray(n?.events)||!Array.isArray(s?.events)){a("debug","Legacy or current queue malformed, keeping current only");return}let o=new Set(s.events.map(d=>d.id)),l=[...s.events,...n.events.filter(d=>typeof d.id=="string"&&!o.has(d.id))],c={...s,events:l,timestamp:typeof s.timestamp=="number"&&typeof n.timestamp=="number"?Math.min(s.timestamp,n.timestamp):s.timestamp??n.timestamp??Date.now(),recoveryFailures:Math.max(s.recoveryFailures??0,n.recoveryFailures??0)||void 0};this.storeManager.setItem(e,JSON.stringify(c)),a("debug","Merged v2 SaaS queue into existing v3 queue",{data:{added:l.length-s.events.length,total:l.length}});}catch(n){a("debug","Failed to merge legacy queue, keeping current",{error:n});}}getQueueStorageKey(){let e=this.get("userId")||"anonymous";return z(e)}getRateLimitStorageKey(){let e=this.get("userId")||"anonymous";return Y(e)}getActiveRateLimitKey(){return this.rateLimitStorageKeyAtArm??this.getRateLimitStorageKey()}armRateLimitCooldown(e){this.rateLimitedUntil=e,this.rateLimitStorageKeyAtArm=this.getRateLimitStorageKey(),this.persistRateLimitCooldown(e);}loadRateLimitCooldown(){let e=this.getRateLimitStorageKey();try{let t=this.storeManager.getItem(e);if(!t)return 0;let r=Number(t);return !Number.isFinite(r)||r<=Date.now()?(this.storeManager.removeItem(e),0):(this.rateLimitStorageKeyAtArm=e,r)}catch{return 0}}persistRateLimitCooldown(e){let t=this.getActiveRateLimitKey();try{let r=this.storeManager.getItem(t);if(r){let n=Number(r);if(Number.isFinite(n)&&n>=e)return}this.storeManager.setItem(t,String(e));}catch{}}clearRateLimitCooldown(){let e=this.getActiveRateLimitKey();try{let t=this.storeManager.getItem(e);if(t){let r=Number(t);if(Number.isFinite(r)&&r>Date.now()){this.rateLimitedUntil=r;return}}this.storeManager.removeItem(e);}catch{}this.rateLimitedUntil=0,this.rateLimitStorageKeyAtArm=null;}isRateLimited(){return this.rateLimitedUntil===0&&(this.rateLimitedUntil=this.loadRateLimitCooldown()),!(this.rateLimitedUntil===0||Date.now()>=this.rateLimitedUntil&&(this.clearRateLimitCooldown(),this.rateLimitedUntil===0))}sendEventsQueueSync(e){if(this.isRateLimited()){a("debug","Rate-limit cooldown active, skipping sync send",{data:{cooldownRemainingMs:this.rateLimitedUntil-Date.now(),events:e.events.length}});let t=this.ensureBatchMetadata(e),r=this.getPersistedData(),n=typeof r?.recoveryFailures=="number"&&Number.isFinite(r.recoveryFailures)?r.recoveryFailures:0;return this.persistEventsWithFailureCount(t,n,true),false}return this.apiUrl.includes("localhost:9999")?(a("warn","Fail mode: simulating network failure (sync)",{data:{events:e.events.length}}),false):this.apiUrl.includes("localhost:8080")?(a("debug","Success mode: simulating successful send (sync)",{data:{events:e.events.length}}),true):this.sendQueueSyncInternal(e)}async sendEventsQueue(e,t){let r=this.ensureBatchMetadata(e);try{let n=await this.send(r);return n?(this.clearPersistedEvents(),t?.onSuccess?.(r.events.length,r.events,r)):(this.persistEvents(r),t?.onFailure?.()),n}catch(n){return n instanceof b?(this.logPermanentError("Permanent error, not retrying",n),this.clearPersistedEvents(),t?.onFailure?.(),false):(this.persistEvents(r),t?.onFailure?.(),false)}}async recoverPersistedEvents(e){if(this.recoveryInProgress){a("debug","Recovery already in progress, skipping duplicate attempt");return}this.recoveryInProgress=true;let t=null,r=0;try{let n=this.getPersistedData();if(!n||!this.isDataRecent(n)||n.events.length===0){this.clearPersistedEvents();return}let s=n.recoveryFailures;if(r=typeof s=="number"&&Number.isFinite(s)&&s>=0?s:0,r>=3){a("debug",`Discarding persisted events after ${r} failed recovery attempts`),this.clearPersistedEvents(),e?.onFailure?.();return}if(this.isRateLimited()){a("debug","Rate-limit cooldown active, deferring recovery",{data:{cooldownRemainingMs:this.rateLimitedUntil-Date.now()}}),e?.onFailure?.();return}if(t=this.ensureBatchMetadata(this.createRecoveryBody(n)),t.events.length===0){a("debug","All persisted events exceeded the recovery age cutoff; discarding batch"),this.clearPersistedEvents();return}await this.send(t)?(this.clearPersistedEvents(),e?.onSuccess?.(n.events.length,n.events,t)):(this.persistEventsWithFailureCount(t,r+1,!0),e?.onFailure?.());}catch(n){if(n instanceof b){this.logPermanentError("Permanent error during recovery, clearing persisted events",n),this.clearPersistedEvents(),e?.onFailure?.();return}a("error","Failed to recover persisted events",{error:n}),t&&this.persistEventsWithFailureCount(t,r+1,true),e?.onFailure?.();}finally{this.recoveryInProgress=false;}}stop(){}async backoffDelay(e){let t=100*Math.pow(2,e),r=Math.random()*100;return new Promise(n=>setTimeout(n,t+r))}async send(e){let t=this.ensureBatchMetadata(e,e._metadata?.idempotency_token);if(this.apiUrl.includes("localhost:9999"))return a("debug","Fail mode: simulating network failure",{data:{events:t.events.length}}),false;if(this.apiUrl.includes("localhost:8080"))return a("debug","Success mode: simulating successful send",{data:{events:t.events.length}}),true;if(this.isRateLimited())return a("debug","Rate-limit cooldown active, skipping send",{data:{cooldownRemainingMs:this.rateLimitedUntil-Date.now(),events:t.events.length}}),false;if(this.consecutiveNetworkFailures>=3){let l=Date.now()-this.circuitOpenedAt;if(l<12e4)return a("debug","Network circuit open, skipping send",{data:{consecutiveNetworkFailures:this.consecutiveNetworkFailures,cooldownRemainingMs:12e4-l}}),false}let{url:r,payload:n}=this.prepareRequest(t),s=true,o=false;for(let l=1;l<=3;l++)try{return (await this.sendWithTimeout(r,n)).ok?(l>1&&a("info",`Send succeeded after ${l-1} retry attempt(s)`,{data:{events:t.events.length,attempt:l}}),this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0,!0):!1}catch(c){let d=l===3;if(c instanceof b)throw this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0,c;if(c instanceof k){this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0,s=false,o=true,this.armRateLimitCooldown(Date.now()+6e4),a("warn","Rate limited, skipping retries",{data:{events:e.events.length,attempt:l,cooldownMs:6e4}});break}if(c instanceof D||(s=false),c instanceof TypeError||(o=true),a(d?"error":"warn",`Send attempt ${l} failed${d?" (all retries exhausted)":", will retry"}`,{error:c,data:{events:e.events.length,url:r.replace(/\/\/[^/]+/,"//[DOMAIN]"),attempt:l,maxAttempts:3}}),!d){await this.backoffDelay(l);continue}return s?(a("debug","All retry attempts timed out, preserving batch for retry",{data:{events:t.events.length}}),false):(o?(this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0):(this.consecutiveNetworkFailures=Math.min(this.consecutiveNetworkFailures+1,3),this.consecutiveNetworkFailures>=3&&(this.circuitOpenedAt=Date.now())),false)}return false}async sendWithTimeout(e,t){let r=new AbortController;this.pendingControllers.add(r);let n=false,s=setTimeout(()=>{n=true,r.abort();},15e3);try{let o=await fetch(e,{method:"POST",body:t,keepalive:!0,credentials:"include",signal:r.signal,headers:{"Content-Type":"application/json"}});if(!o.ok){if(o.status>=400&&o.status<500&&o.status!==408&&o.status!==429){let c=await this.readTraceLogErrorCode(o),d=c?`HTTP ${o.status}: ${o.statusText} (${c})`:`HTTP ${o.status}: ${o.statusText}`;throw new b(d,o.status,c)}throw o.status===429?new k(`HTTP 429: ${o.statusText}`):new Error(`HTTP ${o.status}: ${o.statusText}`)}return o}catch(o){throw o instanceof b?o:n?new D("Request timed out"):o}finally{clearTimeout(s),this.pendingControllers.delete(r);}}async readTraceLogErrorCode(e){try{let t=await e.clone().json();if(typeof t.code=="string"&&t.code.length>0&&t.code.length<=64)return t.code}catch{}}sendQueueSyncInternal(e){let t=this.ensureBatchMetadata(e),r=this.ensureBatchMetadata(t,t._metadata?.idempotency_token),{url:n,payload:s}=this.prepareRequest(r);if(s.length>65536)return a("warn","Payload exceeds sendBeacon limit, persisting for recovery",{data:{size:s.length,limit:65536,events:r.events.length}}),this.persistEvents(t),false;let o=new Blob([s],{type:"application/json"});if(!this.isSendBeaconAvailable())return a("warn","sendBeacon not available, persisting events for recovery"),this.persistEvents(t),false;let l=navigator.sendBeacon(n,o);return l||(a("warn","sendBeacon rejected request, persisting events for recovery"),this.persistEvents(t)),l}prepareRequest(e){let t=Date.now();t<this.lastMetadataTimestamp&&(t=this.lastMetadataTimestamp),this.lastMetadataTimestamp=t;let r={...e,_metadata:{...e._metadata,idempotency_token:e._metadata?.idempotency_token??this.computeContentToken(e),referer:typeof window<"u"?window.location.href:void 0,timestamp:t,client_version:vt}};return {url:this.apiUrl,payload:JSON.stringify(r)}}ensureBatchMetadata(e,t){let r=e._metadata?.idempotency_token??t??this.computeContentToken(e);return e._metadata?.idempotency_token===r?e:{...e,_metadata:{...e._metadata,idempotency_token:r}}}computeContentToken(e){let t=e.events.map(s=>s.id).sort().join(","),r=`${e.user_id}|${e.session_id}|${t}`,n=2166136261;for(let s=0;s<r.length;s++)n^=r.charCodeAt(s),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")}getPersistedData(){try{let e=this.getQueueStorageKey(),t=this.storeManager.getItem(e);if(t)return JSON.parse(t)}catch(e){a("debug","Failed to parse persisted data",{error:e}),this.clearPersistedEvents();}return null}isDataRecent(e){return !e.timestamp||typeof e.timestamp!="number"?false:(Date.now()-e.timestamp)/(1e3*60*60)<2}createRecoveryBody(e){let{timestamp:t,recoveryFailures:r,...n}=e,s=n.events??[],o=Date.now()-5184e5,l=s.filter(c=>{let d=typeof c.timestamp=="number"?c.timestamp:new Date(c.timestamp).getTime();return Number.isFinite(d)&&d>=o});return l.length<s.length&&a("debug","Recovery dropped stale events",{data:{dropped:s.length-l.length,kept:l.length}}),{...n,events:l}}persistEvents(e){let t=this.getPersistedData(),r=typeof t?.recoveryFailures=="number"&&Number.isFinite(t.recoveryFailures)?t.recoveryFailures:0;return this.persistEventsWithFailureCount(e,r)}persistEventsWithFailureCount(e,t,r=false){try{let n=this.getPersistedData();if(!r&&n&&n.timestamp){let l=Date.now()-n.timestamp;if(l<1e3)return a("debug","Skipping persistence, another tab recently persisted events",{data:{timeSinceExisting:l}}),!0}let s={...e,timestamp:Date.now(),...t>0&&{recoveryFailures:t}},o=this.getQueueStorageKey();return this.storeManager.setItem(o,JSON.stringify(s)),!!this.storeManager.getItem(o)}catch(n){return a("debug","Failed to persist events",{error:n}),false}}clearPersistedEvents(){try{let e=this.getQueueStorageKey();this.storeManager.removeItem(e);}catch(e){a("debug","Failed to clear persisted events",{error:e});}}isSendBeaconAvailable(){return typeof navigator<"u"&&typeof navigator.sendBeacon=="function"}logPermanentError(e,t){let r=Date.now(),n=`${t.statusCode??"unknown"}:${t.responseCode??""}`;(!this.lastPermanentErrorLog||this.lastPermanentErrorLog.key!==n||r-this.lastPermanentErrorLog.timestamp>=6e4)&&(a("error",e,{data:{status:t.statusCode,code:t.responseCode,message:t.message}}),this.lastPermanentErrorLog={key:n,timestamp:r});}};var ue=class extends u{bootTime;bootTimestamp;hasPerformanceNow;constructor(){if(super(),typeof window>"u"){this.hasPerformanceNow=false,this.bootTime=0,this.bootTimestamp=0;return}this.hasPerformanceNow=typeof performance<"u"&&typeof performance.now=="function",this.hasPerformanceNow?(this.bootTime=performance.now(),this.bootTimestamp=Date.now()):(this.bootTime=0,this.bootTimestamp=Date.now(),a("debug","performance.now() not available, falling back to Date.now()"));}now(){if(!this.hasPerformanceNow)return Date.now();let e=performance.now()-this.bootTime;return Math.round(this.bootTimestamp+e)}validateTimestamp(e){let r=e-this.now();return r>12e4?{valid:false,error:`Timestamp is ${(r/1e3/60).toFixed(2)} minutes in the future (max allowed: 2 minutes)`}:{valid:true}}};var tn=new Set(Object.values(T)),pe=class extends u{dataSenders;emitter;timeManager;recentEventFingerprints=new Map;perEventRateLimits=new Map;eventsQueue=[];pendingEventsBuffer=[];sendTimeoutId=null;sendInProgress=false;consecutiveSendFailures=0;rateLimitCounter=0;rateLimitWindowStart=0;lastSessionId=null;pendingSyncFlush=false;sessionEventCounts={total:0,click:0,page_view:0,custom:0,scroll:0};saveSessionCountsDebounced=null;constructor(e,t=null){super(),this.emitter=t,this.timeManager=new ue,this.dataSenders=[];let r=this.get("collectApiUrls");r?.saas&&this.dataSenders.push(new de(e,r.saas)),this.saveSessionCountsDebounced=this.debounce(n=>{this.saveSessionCounts(n);},500),this.cleanupExpiredSessionCounts();}async recoverPersistedEvents(){let e=this.dataSenders.map(async t=>t.recoverPersistedEvents({onSuccess:(r,n,s)=>{if(n&&n.length>0){let o=n.map(l=>l.id);this.removeProcessedEvents(o),s&&this.emitEventsQueue(s);}},onFailure:()=>{a("debug","Failed to recover persisted events");}}));await Promise.allSettled(e);}track({type:e,page_url:t,from_page_url:r,scroll_data:n,click_data:s,custom_event:o,web_vitals:l,error_data:c,page_view:d}){if(!e){a("error","Event type is required - event will be ignored");return}if(!tn.has(e)){a("error","Invalid event type - event will be ignored",{data:{type:e}});return}let p=this.get("sessionId");if(!p){this.pendingEventsBuffer.length>=100&&(this.pendingEventsBuffer.shift(),a("debug","Pending events buffer full - dropping oldest event",{data:{maxBufferSize:100}})),this.pendingEventsBuffer.push({type:e,page_url:t,from_page_url:r,scroll_data:n,click_data:s,custom_event:o,web_vitals:l,error_data:c,page_view:d});return}this.lastSessionId!==p&&(this.lastSessionId=p,this.sessionEventCounts=this.loadSessionCounts(p));let S=e==="session_start";if(S&&a("debug","Processing SESSION_START event",{data:{sessionId:p}}),!S&&!this.checkRateLimit())return;let f=e;if(!S){if(this.sessionEventCounts.total>=1e3){a("warn","Session event limit reached",{data:{type:f,total:this.sessionEventCounts.total,limit:1e3}});return}let E=this.getTypeLimitForEvent(f);if(E){let we=this.sessionEventCounts[f];if(we!==void 0&&we>=E){a("warn","Session event type limit reached",{data:{type:f,count:we,limit:E}});return}}}if(f==="custom"&&o?.name){let E=this.get("config")?.maxSameEventPerMinute??60;if(!this.checkPerEventRateLimit(o.name,E))return}let be=f==="session_start",sr=t||this.get("pageUrl"),Q=this.buildEventPayload({type:f,page_url:sr,from_page_url:r,scroll_data:n,click_data:s,custom_event:o,web_vitals:l,error_data:c,page_view:d});if(Q&&!(!S&&!this.shouldSample())){if(be){let E=this.get("sessionId");if(!E){a("error","Session start event requires sessionId - event will be ignored");return}if(this.get("hasStartSession")){a("debug","Duplicate session_start detected",{data:{sessionId:E}});return}this.set("hasStartSession",true);}if(!this.isDuplicateEvent(Q)){if(this.get("mode")==="qa"&&f==="custom"&&o){a("info",`Custom Event: ${o.name}`,{visibility:"qa",data:{name:o.name,...o.metadata&&{metadata:o.metadata}}}),this.emitEvent(Q);return}if(this.addToQueue(Q),!S){this.sessionEventCounts.total++,this.sessionEventCounts[f]!==void 0&&this.sessionEventCounts[f]++;let E=this.get("sessionId");E&&this.saveSessionCountsDebounced&&this.saveSessionCountsDebounced(E);}}}}stop(){this.clearSendTimeout(),this.sendInProgress=false,this.pendingSyncFlush=false,this.consecutiveSendFailures=0;let e=this.get("sessionId");e&&this.saveSessionCounts(e),this.eventsQueue=[],this.pendingEventsBuffer=[],this.recentEventFingerprints.clear(),this.rateLimitCounter=0,this.rateLimitWindowStart=0,this.perEventRateLimits.clear(),this.sessionEventCounts={total:0,click:0,page_view:0,custom:0,scroll:0},this.lastSessionId=null,this.set("hasStartSession",false),this.dataSenders.forEach(t=>{t.stop();});}async flushImmediately(){return this.flushEvents(false)}flushImmediatelySync(){return this.flushEvents(true)}getQueueLength(){return this.eventsQueue.length}getQueueEvents(){return this.eventsQueue.map(({_session_id:e,...t})=>t)}async flushQueue(){await this.flushImmediately();}clearQueue(){this.eventsQueue=[];}flushPendingEvents(){if(this.pendingEventsBuffer.length===0)return;if(!this.get("sessionId")){a("debug","Cannot flush pending events: session not initialized - keeping in buffer",{data:{bufferedEventCount:this.pendingEventsBuffer.length}});return}let t=[...this.pendingEventsBuffer];this.pendingEventsBuffer=[],t.forEach(r=>{this.track(r);});}clearSendTimeout(){this.sendTimeoutId!==null&&(clearTimeout(this.sendTimeoutId),this.sendTimeoutId=null);}isSuccessfulResult(e){return e.status==="fulfilled"&&e.value===true}groupQueuedEventsBySession(){let e=new Map,t=[];for(let r of this.eventsQueue){if(!r._session_id){a("debug","Queued event missing _session_id, dropping",{data:{eventId:r.id,type:r.type}}),t.push(r.id);continue}let n=e.get(r._session_id);n?n.push(r):e.set(r._session_id,[r]);}return t.length>0&&this.removeProcessedEvents(t),e}buildBatchesWithIds(){let e=this.groupQueuedEventsBySession();if(e.size===0)return [];let t=[];for(let[r,n]of e)t.push({batch:this.buildBatchFromGroup(r,n),eventIds:n.map(s=>s.id)});return t}flushEvents(e){if(this.eventsQueue.length===0)return e?true:Promise.resolve(true);if(!e&&this.sendInProgress)return a("debug","Async flush skipped: send already in progress"),Promise.resolve(false);let t=this.buildBatchesWithIds();if(t.length===0)return e?true:Promise.resolve(true);if(this.dataSenders.length===0){for(let{batch:r,eventIds:n}of t)this.removeProcessedEvents(n),this.emitEventsQueue(r);return this.clearSendTimeout(),e?true:Promise.resolve(true)}if(e&&this.sendInProgress){let r=t.reduce((n,s)=>n+s.eventIds.length,0);return this.pendingSyncFlush=true,a("debug","Sync flush deferred: async send in-flight, will retry on settle",{data:{eventCount:r}}),false}if(e){let r=t.map(({batch:n,eventIds:s})=>this.sendBatchSync(n,s));return this.settleSendTimeout(),r.some(Boolean)}return this.sendInProgress=true,(async()=>{try{let r=await Promise.all(t.map(async({batch:n,eventIds:s})=>this.sendBatchAsync(n,s)));return this.settleSendTimeout(),r.some(Boolean)}finally{this.sendInProgress=false,this.drainPendingSyncFlush();}})()}settleSendTimeout(){this.eventsQueue.length===0?this.clearSendTimeout():this.scheduleSendTimeout();}drainPendingSyncFlush(){this.pendingSyncFlush&&(this.pendingSyncFlush=false,this.flushImmediatelySync());}sendBatchSync(e,t){let n=this.dataSenders.map(s=>s.sendEventsQueueSync(e)).some(s=>s);return n?(this.removeProcessedEvents(t),this.emitEventsQueue(e)):a("debug","Sync send complete failure, events kept in queue for retry",{data:{eventCount:t.length,sessionId:e.session_id}}),n}async sendBatchAsync(e,t){let r=this.dataSenders.map(async o=>o.sendEventsQueue(e,{onSuccess:()=>{},onFailure:()=>{}})),n=await Promise.allSettled(r),s=n.some(o=>this.isSuccessfulResult(o));if(s){this.removeProcessedEvents(t),this.emitEventsQueue(e);let o=n.filter(l=>!this.isSuccessfulResult(l)).length;o>0&&a("debug","Async send completed with some failures, removed from queue and persisted per-integration",{data:{eventCount:t.length,failedCount:o,sessionId:e.session_id}});}else a("debug","Async send complete failure, events kept in queue for retry",{data:{eventCount:t.length,sessionId:e.session_id}});return s}async sendEventsQueue(){if(!(this.eventsQueue.length===0||this.sendInProgress)){this.sendInProgress=true;try{let e=this.buildBatchesWithIds();if(e.length===0)return;if(this.dataSenders.length===0){for(let{batch:n}of e)this.emitEventsQueue(n);return}(await Promise.all(e.map(async({batch:n,eventIds:s})=>this.sendBatchAsync(n,s)))).some(Boolean)?this.consecutiveSendFailures=0:this.consecutiveSendFailures=Math.min(this.consecutiveSendFailures+1,5),this.eventsQueue.length===0?this.clearSendTimeout():this.scheduleSendTimeout();}finally{this.sendInProgress=false,this.drainPendingSyncFlush();}}}buildBatchFromGroup(e,t){let r=new Map,n=[];for(let d of t){let p=this.createEventSignature(d);r.has(p)||n.push(p),r.set(p,d);}let s=n.map(d=>r.get(d)).filter(d=>!!d).sort((d,p)=>d.type==="session_start"&&p.type!=="session_start"?-1:p.type==="session_start"&&d.type!=="session_start"?1:d.timestamp-p.timestamp).map(({_session_id:d,...p})=>p),o=this.get("config")?.globalMetadata,l=this.get("identity");return {user_id:this.get("userId"),session_id:e,device:this.get("device"),events:s,...o&&{global_metadata:o},...l&&{identify:l}}}buildEventPayload(e){let t=this.get("sessionId");if(!t)return a("error","buildEventPayload reached without sessionId \u2014 event dropped",{data:{type:e.type},visibility:"critical"}),null;let r=e.page_url??this.get("pageUrl"),n=typeof r=="string"&&r.length>0?r:"unknown",s=this.timeManager.now(),o=this.timeManager.validateTimestamp(s);o.valid||a("warn","Event timestamp validation failed",{data:{type:e.type,error:o.error}});let l=this.get("sessionReferrer"),c=this.get("sessionUtm"),d=this.get("sessionClickIds");return {...{id:_t(),type:e.type,page_url:n,timestamp:s,...l&&{referrer:l},...e.from_page_url&&{from_page_url:e.from_page_url},...e.scroll_data&&{scroll_data:e.scroll_data},...e.click_data&&{click_data:e.click_data},...e.custom_event&&{custom_event:e.custom_event},...e.web_vitals&&{web_vitals:e.web_vitals},...e.error_data&&{error_data:e.error_data},...e.page_view&&{page_view:e.page_view},...c&&{utm:c},...d&&{click_ids:d}},_session_id:t}}isDuplicateEvent(e){let t=Date.now(),r=this.createEventFingerprint(e),n=this.recentEventFingerprints.get(r);return n&&t-n<1e3?(this.recentEventFingerprints.set(r,t),true):(this.recentEventFingerprints.set(r,t),this.recentEventFingerprints.size>1500&&this.pruneOldFingerprints(),this.recentEventFingerprints.size>3e3&&(this.recentEventFingerprints.clear(),this.recentEventFingerprints.set(r,t),a("debug","Event fingerprint cache exceeded hard limit, cleared",{data:{hardLimit:3e3}})),false)}pruneOldFingerprints(){let e=Date.now(),t=1e3*10;for(let[r,n]of this.recentEventFingerprints.entries())e-n>t&&this.recentEventFingerprints.delete(r);a("debug","Pruned old event fingerprints",{data:{remaining:this.recentEventFingerprints.size,cutoffMs:t}});}createEventFingerprint(e){let t=`${e.type}_${e.page_url}`;if(e.click_data){let r=Math.round((e.click_data.x||0)/10)*10,n=Math.round((e.click_data.y||0)/10)*10;t+=`_click_${r}_${n}`;}return e.scroll_data&&(t+=`_scroll_${e.scroll_data.depth}_${e.scroll_data.direction}`),e.custom_event&&(t+=`_custom_${e.custom_event.name}`,e.custom_event.metadata&&(t+=`_${this.stableStringify(e.custom_event.metadata)}`)),e.web_vitals&&(t+=`_vitals_${e.web_vitals.type}`),e.error_data&&(t+=`_error_${e.error_data.type}_${e.error_data.message}`),t}createEventSignature(e){return this.createEventFingerprint(e)}stableStringify(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r).sort().reduce((n,s)=>(n[s]=r[s],n),{}):r)}addToQueue(e){if(this.emitEvent(e),this.eventsQueue.push(e),this.eventsQueue.length>100){let t=this.eventsQueue.findIndex(n=>n.type!=="session_start"),r=t>=0?this.eventsQueue.splice(t,1)[0]:this.eventsQueue.shift();a("warn","Event queue overflow, oldest non-critical event removed",{data:{maxLength:100,currentLength:this.eventsQueue.length,removedEventType:r?.type,wasCritical:r?.type==="session_start"}});}this.scheduleSendTimeout(),this.eventsQueue.length>=50&&this.consecutiveSendFailures<5&&this.sendEventsQueue();}scheduleSendTimeout(){if(this.sendTimeoutId!==null)return;let e=this.calculateSendDelay();this.sendTimeoutId=window.setTimeout(()=>{this.sendTimeoutId=null,this.eventsQueue.length>0&&this.sendEventsQueue();},e);}calculateSendDelay(){let e=this.get("config")?.sendIntervalMs??1e4;if(this.consecutiveSendFailures===0)return e;let t=e*Math.pow(2,this.consecutiveSendFailures);return Math.min(t,12e4)}shouldSample(){let e=this.get("config")?.samplingRate??1;return Math.random()<e}checkRateLimit(){let e=Date.now();return e-this.rateLimitWindowStart>1e3&&(this.rateLimitCounter=0,this.rateLimitWindowStart=e),this.rateLimitCounter>=50?false:(this.rateLimitCounter++,true)}checkPerEventRateLimit(e,t){let r=Date.now(),s=(this.perEventRateLimits.get(e)??[]).filter(o=>r-o<6e4);return s.length>=t?(a("warn","Per-event rate limit exceeded for custom event",{data:{eventName:e,limit:t,window:`${6e4/1e3}s`}}),false):(s.push(r),this.perEventRateLimits.set(e,s),true)}getTypeLimitForEvent(e){return {click:500,page_view:100,custom:500,scroll:120}[e]??null}removeProcessedEvents(e){let t=new Set(e);this.eventsQueue=this.eventsQueue.filter(r=>!t.has(r.id));}emitEvent(e){if(this.emitter){let{_session_id:t,...r}=e;this.emitter.emit("event",r);}}emitEventsQueue(e){this.emitter&&this.emitter.emit("queue",e);}debounce(e,t){let r=null;return((...n)=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{e(...n),r=null;},t);})}getInitialCounts(){return {total:0,click:0,page_view:0,custom:0,scroll:0}}loadSessionCounts(e){if(typeof window>"u"||typeof localStorage>"u")return this.getInitialCounts();let t=this.get("userId")||"anonymous",r=Ne(t,e);try{let n=localStorage.getItem(r);if(!n)return this.getInitialCounts();let s=JSON.parse(n);return s._timestamp&&Date.now()-s._timestamp>Oe?(a("debug","Session counts expired, clearing",{data:{sessionId:e,age:Date.now()-s._timestamp}}),localStorage.removeItem(r),this.getInitialCounts()):typeof s.total=="number"&&typeof s.click=="number"&&typeof s.page_view=="number"&&typeof s.custom=="number"&&typeof s.scroll=="number"?{total:s.total,click:s.click,page_view:s.page_view,custom:s.custom,scroll:s.scroll}:(a("warn","Invalid session counts structure in localStorage, resetting",{data:{sessionId:e,parsed:s}}),localStorage.removeItem(r),a("debug","Session counts removed due to invalid/corrupted data",{data:{sessionId:e,parsed:s}}),this.getInitialCounts())}catch(n){return a("warn","Failed to load session counts from localStorage",{error:n,data:{sessionId:e}}),this.getInitialCounts()}}cleanupExpiredSessionCounts(){if(!(typeof window>"u"||typeof localStorage>"u"))try{let e=localStorage.getItem(xe);if(e){let s=Date.now()-parseInt(e,10);if(s<Pe){a("debug","Skipping session counts cleanup (throttled)",{data:{timeSinceLastCleanup:s,throttleMs:Pe}});return}}let t=this.get("userId")||"anonymous",r=`${m}:${t}:session_counts:`,n=[];for(let s=0;s<localStorage.length;s++){let o=localStorage.key(s);if(o?.startsWith(r))try{let l=localStorage.getItem(o);if(l){let c=JSON.parse(l);c._timestamp&&Date.now()-c._timestamp>Oe&&n.push(o);}}catch{}}n.forEach(s=>{localStorage.removeItem(s),a("debug","Cleaned up expired session counts",{data:{key:s}});}),n.length>0&&a("info",`Cleaned up ${n.length} expired session counts entries`),localStorage.setItem(xe,Date.now().toString());}catch(e){a("warn","Failed to cleanup expired session counts",{error:e});}}saveSessionCounts(e){let t=this.get("userId")||"anonymous",r=Ne(t,e);try{let n={...this.sessionEventCounts,_timestamp:Date.now(),_version:1};localStorage.setItem(r,JSON.stringify(n));}catch(n){a("warn","Failed to persist session counts to localStorage",{error:n,data:{sessionId:e}});}}};var he=class{static getId(e){let t=e.getItem(P);if(t)return t;let r=le();return e.setItem(P,r),r}};var rn=/^\d{13}-[a-z0-9]{9}$/,me=class extends u{storageManager;eventManager;projectId;activityHandler=null;visibilityChangeHandler=null;sessionTimeoutId=null;broadcastChannel=null;isTracking=false;needsRenewal=false;prerenderActivationHandler=null;constructor(e,t,r){super(),this.storageManager=e,this.eventManager=t,this.projectId=r;}initCrossTabSync(){if(typeof BroadcastChannel>"u"){a("debug","BroadcastChannel not supported");return}let e=this.getProjectId();this.broadcastChannel=new BroadcastChannel(nt(e)),this.broadcastChannel.onmessage=t=>{let{action:r,sessionId:n,timestamp:s,projectId:o}=t.data??{};if(o===e)if(r==="session_start"&&n&&typeof s=="number"&&s>Date.now()-5e3){this.set("sessionId",n);let l=this.loadStoredSession();this.set("sessionReferrer",l?.referrer),this.set("sessionUtm",l?.utm),this.set("sessionClickIds",l?.clickIds),this.persistSession(n,s,l?.referrer,l?.utm,l?.clickIds),this.isTracking&&this.setupSessionTimeout();}else r&&r!=="session_start"&&a("debug","Ignored BroadcastChannel message with unknown action",{data:{action:r}});};}shareSession(e){this.broadcastChannel&&typeof this.broadcastChannel.postMessage=="function"&&this.broadcastChannel.postMessage({action:"session_start",projectId:this.getProjectId(),sessionId:e,timestamp:Date.now()});}cleanupCrossTabSync(){this.broadcastChannel&&(typeof this.broadcastChannel.close=="function"&&this.broadcastChannel.close(),this.broadcastChannel=null);}recoverSession(){let e=this.loadStoredSession();if(!e)return null;if(!rn.test(e.id))return a("warn","Invalid session ID format recovered from storage, clearing",{data:{sessionId:e.id}}),this.clearStoredSession(),null;let t=this.get("config")?.sessionTimeout??9e5;return Date.now()-e.lastActivity>t?(this.clearStoredSession(),null):e.id}persistSession(e,t=Date.now(),r,n,s){this.saveStoredSession({id:e,lastActivity:t,...r&&{referrer:r},...n&&{utm:n},...s&&{clickIds:s}});}clearStoredSession(){let e=this.getSessionStorageKey();this.storageManager.removeItem(e);}loadStoredSession(){let e=this.getSessionStorageKey(),t=this.storageManager.getItem(e);if(t!==null)try{let n=JSON.parse(t);if(n.id&&typeof n.lastActivity=="number")return n}catch{this.storageManager.removeItem(e);}let r=this.storageManager.getSessionItem(e);if(r!==null)try{let n=JSON.parse(r);if(n.id&&typeof n.lastActivity=="number")return n}catch{this.storageManager.removeSessionItem(e);}return null}saveStoredSession(e){let t=this.getSessionStorageKey(),r=JSON.stringify(e);this.storageManager.setItem(t,r),this.storageManager.setSessionItem(t,r);}getSessionStorageKey(){return rt(this.getProjectId())}getProjectId(){return this.projectId}startTracking(){if(this.isTracking){a("debug","Session tracking already active");return}let e=this.recoverSession(),t=e??this.generateSessionId(),r,n,s;if(e){let o=this.loadStoredSession();r=o?.referrer??ie(),n=o?.utm??se(),s=o?.clickIds??ee();}else r=ie(),n=se(),s=ee();a("debug","Session tracking initialized",{data:{sessionId:t,wasRecovered:!!e,willEmitSessionStart:!e,sessionReferrer:r,hasUtm:!!n,hasClickIds:!!s}}),this.isTracking=true;try{if(this.set("sessionId",t),this.set("sessionReferrer",r),this.set("sessionUtm",n),this.set("sessionClickIds",s),ne()){this.prerenderActivationHandler=()=>{this.prerenderActivationHandler=null,this.activateSession(t,e,r,n,s);},document.addEventListener("prerenderingchange",this.prerenderActivationHandler,{once:!0});return}this.activateSession(t,e,r,n,s);}catch(o){throw this.isTracking=false,this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupLifecycleListeners(),this.cleanupCrossTabSync(),this.set("sessionId",null),o}}activateSession(e,t,r,n,s){this.persistSession(e,Date.now(),r,n,s),this.initCrossTabSync(),this.shareSession(e),t?a("debug","Session recovered, skipping SESSION_START",{data:{sessionId:e}}):(a("debug","Emitting SESSION_START event",{data:{sessionId:e}}),this.eventManager.track({type:"session_start"})),this.setupSessionTimeout(),this.setupActivityListeners(),this.setupLifecycleListeners();}generateSessionId(){return `${Date.now()}-${Math.random().toString(36).substring(2,11)}`}setupSessionTimeout(){this.clearSessionTimeout();let e=this.get("config")?.sessionTimeout??9e5;this.sessionTimeoutId=setTimeout(()=>{this.enterRenewalMode();},e);}resetSessionTimeout(){this.setupSessionTimeout();let e=this.get("sessionId");e&&this.persistSession(e,Date.now(),this.get("sessionReferrer"),this.get("sessionUtm"),this.get("sessionClickIds"));}clearSessionTimeout(){this.sessionTimeoutId&&(clearTimeout(this.sessionTimeoutId),this.sessionTimeoutId=null);}setupActivityListeners(){this.activityHandler=()=>{this.needsRenewal?this.renewSession():this.resetSessionTimeout();},document.addEventListener("click",this.activityHandler,{passive:true}),document.addEventListener("keydown",this.activityHandler,{passive:true}),document.addEventListener("scroll",this.activityHandler,{passive:true});}renewSession(){this.needsRenewal=false;let e=this.generateSessionId(),t=ie(),r=se(),n=ee();a("debug","Renewing session after timeout",{data:{newSessionId:e}}),this.set("sessionId",e),this.set("sessionReferrer",t),this.set("sessionUtm",r),this.set("sessionClickIds",n),this.persistSession(e,Date.now(),t,r,n),this.cleanupCrossTabSync(),this.initCrossTabSync(),this.shareSession(e),this.eventManager.track({type:"session_start"}),this.eventManager.flushPendingEvents(),this.setupSessionTimeout();}cleanupActivityListeners(){this.activityHandler&&(document.removeEventListener("click",this.activityHandler),document.removeEventListener("keydown",this.activityHandler),document.removeEventListener("scroll",this.activityHandler),this.activityHandler=null);}setupLifecycleListeners(){this.visibilityChangeHandler||(this.visibilityChangeHandler=()=>{if(document.hidden)this.clearSessionTimeout();else {if(this.isSessionStale()){a("debug","Session expired during suspend, entering renewal mode"),this.enterRenewalMode();return}this.get("sessionId")&&this.setupSessionTimeout();}},document.addEventListener("visibilitychange",this.visibilityChangeHandler));}isSessionStale(){if(this.needsRenewal||!this.get("sessionId"))return false;let t=this.loadStoredSession();if(!t)return false;let r=this.get("config")?.sessionTimeout??9e5;return Date.now()-t.lastActivity>r}cleanupLifecycleListeners(){this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=null);}enterRenewalMode(){this.clearSessionTimeout(),this.cleanupCrossTabSync(),this.clearStoredSession(),this.set("sessionId",null),this.set("hasStartSession",false),this.set("sessionReferrer",void 0),this.set("sessionUtm",void 0),this.set("sessionClickIds",void 0),this.needsRenewal=true,a("debug","Session timed out, entering renewal mode");}resetSessionState(){this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupLifecycleListeners(),this.cleanupCrossTabSync(),this.cleanupPrerenderActivation(),this.clearStoredSession(),this.set("sessionId",null),this.set("hasStartSession",false),this.set("sessionReferrer",void 0),this.set("sessionUtm",void 0),this.set("sessionClickIds",void 0),this.needsRenewal=false,this.isTracking=false;}stopTracking(){this.resetSessionState();}destroy(){this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupCrossTabSync(),this.cleanupLifecycleListeners(),this.cleanupPrerenderActivation(),this.isTracking=false,this.needsRenewal=false,this.set("hasStartSession",false);}cleanupPrerenderActivation(){this.prerenderActivationHandler&&(document.removeEventListener("prerenderingchange",this.prerenderActivationHandler),this.prerenderActivationHandler=null);}};var fe=class extends u{eventManager;storageManager;sessionManager=null;destroyed=false;constructor(e,t){super(),this.eventManager=t,this.storageManager=e;}startTracking(){if(this.isActive())return;if(this.destroyed){a("debug","Cannot start tracking on destroyed handler");return}let t=this.get("config")?.integrations?.tracelog?.projectId??"custom";try{this.sessionManager=new me(this.storageManager,this.eventManager,t),this.sessionManager.startTracking(),this.eventManager.flushPendingEvents();}catch(r){if(this.sessionManager){try{this.sessionManager.destroy();}catch{}this.sessionManager=null;}throw a("error","Failed to start session tracking",{error:r}),r}}isActive(){return this.sessionManager!==null&&!this.destroyed}cleanupSessionManager(){this.sessionManager&&(this.sessionManager.stopTracking(),this.sessionManager.destroy(),this.sessionManager=null);}stopTracking(){this.cleanupSessionManager();}destroy(){this.destroyed||(this.sessionManager&&(this.sessionManager.destroy(),this.sessionManager=null),this.destroyed=true);}};var Ee=class extends u{eventManager;onTrack;originalPushState;originalReplaceState;lastPageViewTime=0;constructor(e,t){super(),this.eventManager=e,this.onTrack=t;}startTracking(){this.trackInitialPageView(),window.addEventListener("popstate",this.trackCurrentPage,true),window.addEventListener("hashchange",this.trackCurrentPage,true),this.patchHistory("pushState"),this.patchHistory("replaceState");}stopTracking(){window.removeEventListener("popstate",this.trackCurrentPage,true),window.removeEventListener("hashchange",this.trackCurrentPage,true),this.originalPushState&&(window.history.pushState=this.originalPushState),this.originalReplaceState&&(window.history.replaceState=this.originalReplaceState),this.lastPageViewTime=0;}patchHistory(e){let t=window.history[e];e==="pushState"&&!this.originalPushState?this.originalPushState=t:e==="replaceState"&&!this.originalReplaceState&&(this.originalReplaceState=t),window.history[e]=(...r)=>{t.apply(window.history,r),this.trackCurrentPage();};}trackCurrentPage=()=>{let e=window.location.href,t=F(e,this.get("config").sensitiveQueryParams);if(this.get("pageUrl")===t)return;let r=Date.now(),n=this.get("config").pageViewThrottleMs??1e3;if(r-this.lastPageViewTime<n)return;this.lastPageViewTime=r,this.onTrack();let s=this.get("pageUrl");this.set("pageUrl",t);let o=this.extractPageViewData();this.eventManager.track({type:"page_view",page_url:this.get("pageUrl"),from_page_url:s,...o&&{page_view:o}}),this.get("config").flushOnSpaNavigation===true&&this.eventManager.flushImmediately();};trackInitialPageView(){let e=F(window.location.href,this.get("config").sensitiveQueryParams),t=this.extractPageViewData();this.lastPageViewTime=Date.now(),this.eventManager.track({type:"page_view",page_url:e,...t&&{page_view:t}}),this.onTrack();}extractPageViewData(){let{referrer:e}=document,{title:t}=document;if(!(!e&&!t))return {...e&&{referrer:e},...t&&{title:t}}}};var ve=class extends u{eventManager;lastClickTimes=new Map;clickHandler;lastPruneTime=0;constructor(e){super(),this.eventManager=e;}startTracking(){this.clickHandler||(this.clickHandler=e=>{let t=e,r=t.target,n=typeof HTMLElement<"u"&&r instanceof HTMLElement?r:typeof HTMLElement<"u"&&r instanceof Node&&r.parentElement instanceof HTMLElement?r.parentElement:null;if(!n){a("debug","Click target not found or not an element");return}if(this.shouldIgnoreElement(n))return;let s=this.get("config")?.clickThrottleMs??300;if(s>0&&!this.checkClickThrottle(n,s))return;let o=this.findTrackingElement(n),l=this.getRelevantClickElement(n),c=this.calculateClickCoordinates(t);if(o){let p=this.extractTrackingData(o);if(p){let S=this.createCustomEventData(p);this.eventManager.track({type:"custom",custom_event:{name:S.name,...S.value&&{metadata:{value:S.value}}}});}}if(!c){a("debug","Click skipped: invalid coordinates (likely synthetic)");return}let d=this.generateClickData(n,l,c);this.eventManager.track({type:"click",click_data:d});},window.addEventListener("click",this.clickHandler,true));}stopTracking(){this.clickHandler&&(window.removeEventListener("click",this.clickHandler,true),this.clickHandler=void 0),this.lastClickTimes.clear(),this.lastPruneTime=0;}shouldIgnoreElement(e){return e.hasAttribute(`${_}-ignore`)?true:e.closest(`[${_}-ignore]`)!==null}checkClickThrottle(e,t){let r=this.getElementSignature(e),n=Date.now();this.pruneThrottleCache(n);let s=this.lastClickTimes.get(r);return s!==void 0&&n-s<t?(a("debug","ClickHandler: Click suppressed by throttle",{data:{signature:r,throttleRemaining:t-(n-s)}}),false):(this.lastClickTimes.set(r,n),true)}pruneThrottleCache(e){if(e-this.lastPruneTime<3e4)return;this.lastPruneTime=e;let t=e-3e5;for(let[r,n]of this.lastClickTimes.entries())n<t&&this.lastClickTimes.delete(r);if(this.lastClickTimes.size>1e3){let r=Array.from(this.lastClickTimes.entries()).sort((o,l)=>o[1]-l[1]),n=this.lastClickTimes.size-1e3,s=r.slice(0,n);for(let[o]of s)this.lastClickTimes.delete(o);a("debug","ClickHandler: Pruned throttle cache",{data:{removed:s.length,remaining:this.lastClickTimes.size}});}}getElementSignature(e){if(e.id)return `#${e.id}`;let t=e.getAttribute("data-testid");if(t)return `[data-testid="${t}"]`;let r=e.getAttribute(`${_}-name`);return r?`[${_}-name="${r}"]`:this.getElementPath(e)}getElementPath(e){let t=[],r=e;for(;r&&r!==document.body;){let n=r.tagName.toLowerCase();if(r.className){let s=r.className.split(" ")[0];s&&(n+=`.${s}`);}t.unshift(n),r=r.parentElement;}return t.join(">")||"unknown"}findTrackingElement(e){return e.hasAttribute(`${_}-name`)?e:e.closest(`[${_}-name]`)}getRelevantClickElement(e){for(let t of Je)try{if(e.matches(t))return e;let r=e.closest(t);if(r)return r}catch(r){a("debug","Invalid selector in element search",{error:r,data:{selector:t}});continue}return e}calculateClickCoordinates(e){let t=e.clientX,r=e.clientY;return typeof t!="number"||typeof r!="number"||!Number.isFinite(t)||!Number.isFinite(r)||t===0&&r===0&&!e.isTrusted?null:{x:t,y:r}}extractTrackingData(e){let t=e.getAttribute(`${_}-name`),r=e.getAttribute(`${_}-value`);if(t)return {element:e,name:t,...r&&{value:r}}}generateClickData(e,t,r){let{x:n,y:s}=r,o=this.getRelevantText(e,t),l=t.getAttribute("href")??void 0;return {x:n,y:s,tag:t.tagName.toLowerCase(),...t.id&&{id:t.id},...t.className&&{class:t.className},...o&&{text:o},...l&&{href:l}}}getRelevantText(e,t){let r=e.textContent?.trim()??"",n=t.textContent?.trim()??"";if(!r&&!n)return "";let s="";return r&&r.length<=255?s=r:n.length<=255?s=n:s=n.slice(0,252)+"...",N(s)}createCustomEventData(e){return {name:e.name,...e.value&&{value:e.value}}}};var Se=class extends u{eventManager;containers=[];limitWarningLogged=false;containerDiscoveryTimeoutId=null;constructor(e){super(),this.eventManager=e;}startTracking(){this.limitWarningLogged=false,this.set("scrollEventCount",0),this.tryDetectScrollContainers(0);}stopTracking(){this.containerDiscoveryTimeoutId!==null&&(clearTimeout(this.containerDiscoveryTimeoutId),this.containerDiscoveryTimeoutId=null);for(let e of this.containers)this.clearContainerTimer(e),e.element===window?window.removeEventListener("scroll",e.listener):e.element.removeEventListener("scroll",e.listener);this.containers.length=0,this.set("scrollEventCount",0),this.limitWarningLogged=false;}tryDetectScrollContainers(e){let t=this.findScrollableElements();if(this.isWindowScrollable()&&this.setupScrollContainer(window,"window"),t.length>0){for(let r of t){let n=this.getElementSelector(r);this.setupScrollContainer(r,n);}return}if(e<5){this.containerDiscoveryTimeoutId=window.setTimeout(()=>{this.containerDiscoveryTimeoutId=null,this.tryDetectScrollContainers(e+1);},200);return}this.containers.length===0&&this.setupScrollContainer(window,"window");}findScrollableElements(){if(!document.body)return [];let e=[],t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{let s=n;if(!s.isConnected||!s.offsetParent)return NodeFilter.FILTER_SKIP;let o=getComputedStyle(s);return o.overflowY==="auto"||o.overflowY==="scroll"||o.overflow==="auto"||o.overflow==="scroll"?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}}),r;for(;(r=t.nextNode())&&e.length<10;){let n=r;this.isElementScrollable(n)&&e.push(n);}return e}getElementSelector(e){if(e===window)return "window";let t=e;if(t.id)return `#${t.id}`;if(t.className&&typeof t.className=="string"){let r=t.className.split(" ").filter(n=>n.trim())[0];if(r)return `.${r}`}return t.tagName.toLowerCase()}setupScrollContainer(e,t){if(this.containers.some(c=>c.element===e)||e!==window&&!this.isElementScrollable(e))return;let n=this.getScrollTop(e),s=this.calculateScrollDepth(n,this.getScrollHeight(e),this.getViewportHeight(e)),o={element:e,selector:t,lastScrollPos:n,lastDepth:s,lastEventTime:0,debounceTimer:null,listener:null},l=()=>{this.get("suppressNextScroll")||(this.clearContainerTimer(o),o.debounceTimer=window.setTimeout(()=>{let c=this.calculateScrollData(o);c&&this.processScrollEvent(o,c,Date.now()),o.debounceTimer=null;},250));};o.listener=l,this.containers.push(o),e===window?window.addEventListener("scroll",l,{passive:true}):e.addEventListener("scroll",l,{passive:true});}processScrollEvent(e,t,r){if(!this.shouldEmitScrollEvent(e,t,r))return;e.lastEventTime=r,e.lastDepth=t.depth;let n=this.get("scrollEventCount")??0;this.set("scrollEventCount",n+1),this.eventManager.track({type:"scroll",scroll_data:{...t,container_selector:e.selector}});}shouldEmitScrollEvent(e,t,r){return this.hasReachedSessionLimit()?(this.logLimitOnce(),false):!(!this.hasElapsedMinimumInterval(e,r)||!this.hasSignificantDepthChange(e,t.depth))}hasReachedSessionLimit(){return (this.get("scrollEventCount")??0)>=120}hasElapsedMinimumInterval(e,t){return e.lastEventTime===0?true:t-e.lastEventTime>=500}hasSignificantDepthChange(e,t){return Math.abs(t-e.lastDepth)>=5}logLimitOnce(){this.limitWarningLogged||(this.limitWarningLogged=true,a("debug","Max scroll events per session reached",{data:{limit:120}}));}isWindowScrollable(){return document.documentElement.scrollHeight>window.innerHeight}clearContainerTimer(e){e.debounceTimer!==null&&(clearTimeout(e.debounceTimer),e.debounceTimer=null);}getScrollDirection(e,t){return e>t?"down":"up"}calculateScrollDepth(e,t,r){if(t<=r)return 0;let n=t-r;return Math.min(100,Math.max(0,Math.floor(e/n*100)))}calculateScrollData(e){let{element:t,lastScrollPos:r}=e,n=this.getScrollTop(t);if(Math.abs(n-r)<10||t===window&&!this.isWindowScrollable())return null;let o=this.getViewportHeight(t),l=this.getScrollHeight(t),c=this.getScrollDirection(n,r),d=this.calculateScrollDepth(n,l,o);return e.lastScrollPos=n,{depth:d,direction:c}}getScrollTop(e){return e===window?window.scrollY:e.scrollTop}getViewportHeight(e){return e===window?window.innerHeight:e.clientHeight}getScrollHeight(e){return e===window?document.documentElement.scrollHeight:e.scrollHeight}isElementScrollable(e){let t=getComputedStyle(e),r=t.overflowY==="auto"||t.overflowY==="scroll"||t.overflow==="auto"||t.overflow==="scroll",n=e.scrollHeight>e.clientHeight;return r&&n}};var cn="tracelog_session_id",dn="tracelog_user_id",B=class extends u{visibilityHandler=null;pageshowHandler=null;lastSyncedKey=null;activate(){this.cleanupListeners(),this.syncCartAttribute(),this.setupListeners();}deactivate(){this.cleanupListeners(),this.lastSyncedKey=null;}onSessionChange(){this.syncCartAttribute();}syncCartAttribute(){let e=this.get("sessionId");if(!e)return;let t=this.get("userId"),r=typeof t=="string"&&t.length>0?t:"",n=`${e}|${r}`;n!==this.lastSyncedKey&&(this.lastSyncedKey=n,this.postCartUpdate(e,r));}postCartUpdate(e,t){let r={[cn]:e};t.length>0&&(r[dn]=t);try{fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({attributes:r}),credentials:"same-origin"}).then(n=>{n.ok||(this.lastSyncedKey=null,a("debug","Shopify cart attribute update failed",{data:{status:n.status}}));}).catch(()=>{this.lastSyncedKey=null,a("debug","Shopify cart attribute update failed");});}catch{this.lastSyncedKey=null,a("debug","Shopify cart attribute update failed");}}setupListeners(){this.visibilityHandler=()=>{document.hidden||this.syncCartAttribute();},document.addEventListener("visibilitychange",this.visibilityHandler),this.pageshowHandler=e=>{e.persisted&&this.syncCartAttribute();},window.addEventListener("pageshow",this.pageshowHandler);}cleanupListeners(){this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.pageshowHandler&&(window.removeEventListener("pageshow",this.pageshowHandler),this.pageshowHandler=null);}};var Te=class{storage;sessionStorageRef;fallbackStorage=new Map;fallbackSessionStorage=new Map;constructor(){this.storage=this.initializeStorage("localStorage"),this.sessionStorageRef=this.initializeStorage("sessionStorage"),this.storage||a("debug","localStorage not available, using memory fallback"),this.sessionStorageRef||a("debug","sessionStorage not available, using memory fallback");}getItem(e){try{return this.storage?this.storage.getItem(e):this.fallbackStorage.get(e)??null}catch{return this.fallbackStorage.get(e)??null}}setItem(e,t){if(this.fallbackStorage.set(e,t),!!this.storage)try{this.storage.setItem(e,t);return}catch(r){if(!(r instanceof DOMException&&r.name==="QuotaExceededError"||r instanceof Error&&r.name==="QuotaExceededError"))return;if(a("warn","localStorage quota exceeded, attempting cleanup",{data:{key:e,valueSize:t.length}}),!this.cleanupOldData()){a("error","localStorage quota exceeded and no data to cleanup - data will not persist",{error:r,data:{key:e,valueSize:t.length}});return}try{this.storage.setItem(e,t);}catch(s){a("error","localStorage quota exceeded even after cleanup - data will not persist",{error:s,data:{key:e,valueSize:t.length}});}}}removeItem(e){try{this.storage&&this.storage.removeItem(e);}catch{}this.fallbackStorage.delete(e);}cleanupOldData(){if(!this.storage)return false;try{let e=["tracelog_session_","tracelog_user_id","tracelog_device_id","tracelog_config"],t=[],r=[];for(let s=0;s<this.storage.length;s++){let o=this.storage.key(s);o?.startsWith("tracelog_")&&(o.startsWith("tracelog_persisted_events_")?t.push(o):e.some(l=>o.startsWith(l))||r.push(o));}let n=[...t,...r.slice(0,5)];return n.length===0?!1:(n.forEach(s=>{try{this.storage.removeItem(s);}catch{}}),!0)}catch(e){return a("error","Failed to cleanup old data",{error:e}),false}}initializeStorage(e){if(typeof window>"u")return null;try{let t=e==="localStorage"?window.localStorage:window.sessionStorage,r="__tracelog_test__";return t.setItem(r,"test"),t.removeItem(r),t}catch{return null}}getSessionItem(e){try{return this.sessionStorageRef?this.sessionStorageRef.getItem(e):this.fallbackSessionStorage.get(e)??null}catch{return this.fallbackSessionStorage.get(e)??null}}setSessionItem(e,t){this.fallbackSessionStorage.set(e,t);try{if(this.sessionStorageRef){this.sessionStorageRef.setItem(e,t);return}}catch(r){(r instanceof DOMException&&r.name==="QuotaExceededError"||r instanceof Error&&r.name==="QuotaExceededError")&&a("error","sessionStorage quota exceeded - data will not persist",{error:r,data:{key:e,valueSize:t.length}});}}removeSessionItem(e){try{this.sessionStorageRef&&this.sessionStorageRef.removeItem(e);}catch{}this.fallbackSessionStorage.delete(e);}};var _e=class extends u{eventManager;reportedByNav=new Map;navigationHistory=[];observers=[];vitalThresholds;navigationCounter=0;constructor(e){super(),this.eventManager=e,this.vitalThresholds=re(H);}async startTracking(){let e=this.get("config"),t=e?.webVitalsMode??H;this.vitalThresholds=re(t),e?.webVitalsThresholds&&(this.vitalThresholds={...this.vitalThresholds,...e.webVitalsThresholds}),await this.initWebVitals();}stopTracking(){this.observers.forEach((e,t)=>{try{e.disconnect();}catch(r){a("debug","Failed to disconnect performance observer",{error:r,data:{observerIndex:t}});}}),this.observers.length=0,this.reportedByNav.clear(),this.navigationHistory.length=0;}observeWebVitalsFallback(){this.reportTTFB(),this.safeObserve("largest-contentful-paint",r=>{let n=r.getEntries(),s=n[n.length-1];s&&this.sendVital({type:"LCP",value:Number(s.startTime.toFixed(2))});},{type:"largest-contentful-paint",buffered:true},true);let e=0,t=this.getNavigationId();this.safeObserve("layout-shift",r=>{let n=this.getNavigationId();n!==t&&(e=0,t=n);let s=r.getEntries();for(let o of s){if(o.hadRecentInput===true)continue;let l=typeof o.value=="number"?o.value:0;e+=l;}this.sendVital({type:"CLS",value:Number(e.toFixed(2))});},{type:"layout-shift",buffered:true}),this.safeObserve("paint",r=>{for(let n of r.getEntries())n.name==="first-contentful-paint"&&this.sendVital({type:"FCP",value:Number(n.startTime.toFixed(2))});},{type:"paint",buffered:true},true),this.safeObserve("event",r=>{let n=0,s=r.getEntries();for(let o of s){let l=(o.processingEnd??0)-(o.startTime??0);n=Math.max(n,l);}n>0&&this.sendVital({type:"INP",value:Number(n.toFixed(2))});},{type:"event",buffered:true});}async initWebVitals(){try{let{onLCP:e,onCLS:t,onFCP:r,onTTFB:n,onINP:s}=await import('web-vitals'),o=l=>c=>{let d=Number(c.value.toFixed(2));this.sendVital({type:l,value:d});};e(o("LCP"),{reportAllChanges:!1}),t(o("CLS"),{reportAllChanges:!1}),r(o("FCP"),{reportAllChanges:!1}),n(o("TTFB"),{reportAllChanges:!1}),s(o("INP"),{reportAllChanges:!1});}catch(e){a("debug","Failed to load web-vitals library, using fallback",{error:e}),this.observeWebVitalsFallback();}}reportTTFB(){try{let e=performance.getEntriesByType("navigation")[0];if(!e)return;let t=e.responseStart;typeof t=="number"&&Number.isFinite(t)&&this.sendVital({type:"TTFB",value:Number(t.toFixed(2))});}catch(e){a("debug","Failed to report TTFB",{error:e});}}sendVital(e){if(!this.shouldSendVital(e.type,e.value))return;let t=this.getNavigationId();if(t){let r=this.reportedByNav.get(t);if(r?.has(e.type))return;if(r)r.add(e.type);else if(this.reportedByNav.set(t,new Set([e.type])),this.navigationHistory.push(t),this.navigationHistory.length>ft){let s=this.navigationHistory.shift();s&&this.reportedByNav.delete(s);}}this.trackWebVital(e.type,e.value);}trackWebVital(e,t){if(!Number.isFinite(t)){a("debug","Invalid web vital value",{data:{type:e,value:t}});return}this.eventManager.track({type:"web_vitals",web_vitals:{type:e,value:t}});}getNavigationId(){try{let e=performance.getEntriesByType("navigation")[0];if(!e)return null;let t=e.startTime||performance.now(),r=++this.navigationCounter,n=`${t.toFixed(2)}_${window.location.pathname}`;return r>1?`${n}_${r}`:n}catch(e){return a("debug","Failed to get navigation ID",{error:e}),null}}isObserverSupported(e){if(typeof PerformanceObserver>"u")return false;let t=PerformanceObserver.supportedEntryTypes;return !t||t.includes(e)}safeObserve(e,t,r,n=false){try{if(!this.isObserverSupported(e))return !1;let s=new PerformanceObserver((o,l)=>{try{t(o,l);}catch(c){a("debug","Observer callback failed",{error:c,data:{type:e}});}if(n)try{l.disconnect();}catch{}});return s.observe(r??{type:e,buffered:!0}),n||this.observers.push(s),!0}catch(s){return a("debug","Failed to create performance observer",{error:s,data:{type:e}}),false}}shouldSendVital(e,t){if(typeof t!="number"||!Number.isFinite(t))return a("debug","Invalid web vital value",{data:{type:e,value:t}}),false;let r=this.vitalThresholds[e];return !(typeof r=="number"&&t<=r)}};var ye=class i extends u{eventManager;emitter;recentErrors=new Map;pageviewSignatureCounts=new Map;errorBurstCounter=0;burstWindowStart=0;burstBackoffUntil=0;pagehideHandler=null;pageviewResetListener=null;constructor(e,t){super(),this.eventManager=e,this.emitter=t;}startTracking(){window.addEventListener("error",this.handleError),window.addEventListener("unhandledrejection",this.handleRejection),this.pagehideHandler=()=>{this.resetPageviewCounter();},window.addEventListener("pagehide",this.pagehideHandler,{passive:true}),this.emitter&&(this.pageviewResetListener=e=>{(e.type==="session_start"||e.type==="page_view")&&this.resetPageviewCounter();},this.emitter.on("event",this.pageviewResetListener));}stopTracking(){window.removeEventListener("error",this.handleError),window.removeEventListener("unhandledrejection",this.handleRejection),this.pagehideHandler&&(window.removeEventListener("pagehide",this.pagehideHandler),this.pagehideHandler=null),this.emitter&&this.pageviewResetListener&&(this.emitter.off("event",this.pageviewResetListener),this.pageviewResetListener=null),this.recentErrors.clear(),this.pageviewSignatureCounts.clear(),this.errorBurstCounter=0,this.burstWindowStart=0,this.burstBackoffUntil=0;}resetPageviewCounter(){this.pageviewSignatureCounts.clear();}shouldSample(){let e=Date.now();if(e<this.burstBackoffUntil)return false;if(e-this.burstWindowStart>1e3&&(this.errorBurstCounter=0,this.burstWindowStart=e),this.errorBurstCounter++,this.errorBurstCounter>10)return this.burstBackoffUntil=e+5e3,a("debug","Error burst detected - entering cooldown",{data:{errorsInWindow:this.errorBurstCounter,cooldownMs:5e3}}),false;let r=this.get("config").errorSampling??1;return Math.random()<r}shouldThrottleBySignature(e){let t=Ot({message:e.message,filename:e.filename,line:e.line}),r=this.pageviewSignatureCounts.get(t)??0;if(r>=3)return a("debug","Error throttled (pageview cap)",{data:{signature:t,count:r}}),true;let n=r+1;return this.pageviewSignatureCounts.set(t,n),this.pageviewSignatureCounts.size>200&&(this.pageviewSignatureCounts.clear(),this.pageviewSignatureCounts.set(t,n)),false}handleError=e=>{if(!this.shouldSample())return;let t=this.sanitize(e.message||"Unknown error");if(this.shouldSuppressError("js_error",t)||this.shouldThrottleBySignature({message:t,filename:e.filename,line:e.lineno}))return;let r=typeof e.error?.stack=="string"?this.truncateStack(e.error.stack):void 0,n=typeof e.error?.name=="string"&&e.error.name!=="Error"?e.error.name:void 0;this.eventManager.track({type:"error",error_data:{type:"js_error",message:t,...n!==void 0&&{name:n},...e.filename!==""&&{filename:e.filename},...e.lineno!==0&&{line:e.lineno},...e.colno!==0&&{column:e.colno},...r!==void 0&&{stack:r}}});};handleRejection=e=>{if(!this.shouldSample())return;let t=this.extractRejectionMessage(e.reason),r=this.sanitize(t);if(this.shouldSuppressError("promise_rejection",r)||this.shouldThrottleBySignature({message:r}))return;let n=e.reason instanceof Error&&typeof e.reason.stack=="string"?this.truncateStack(e.reason.stack):void 0,s=e.reason instanceof Error&&e.reason.name!=="Error"?e.reason.name:void 0;this.eventManager.track({type:"error",error_data:{type:"promise_rejection",message:r,...s!==void 0&&{name:s},...n!==void 0&&{stack:n}}});};extractRejectionMessage(e){if(e==null)return "Unknown rejection";if(typeof e=="string")return e;if(e instanceof Error)return e.message;if(typeof e=="object"&&"message"in e)return String(e.message);try{return JSON.stringify(e)}catch{return "Unserializable rejection"}}sanitize(e){let t=e.length>500?e.slice(0,500)+"...":e;return N(t)}shouldSuppressError(e,t){let r=Date.now(),n=`${e}:${t}`,s=this.recentErrors.get(n);return s!==void 0&&r-s<5e3?(this.recentErrors.set(n,r),true):(this.recentErrors.set(n,r),this.recentErrors.size>100?(this.recentErrors.clear(),this.recentErrors.set(n,r),false):(this.recentErrors.size>50&&this.pruneOldErrors(),false))}static TRUNCATION_SUFFIX=`
2
+ ...truncated`;truncateStack(e){if(e.length<=2e3)return N(e);let t=2e3-i.TRUNCATION_SUFFIX.length,r=e.slice(0,t)+i.TRUNCATION_SUFFIX;return N(r)}pruneOldErrors(){let e=Date.now();for(let[n,s]of this.recentErrors.entries())e-s>5e3&&this.recentErrors.delete(n);if(this.recentErrors.size<=50)return;let t=Array.from(this.recentErrors.entries()).sort((n,s)=>n[1]-s[1]),r=this.recentErrors.size-50;for(let n=0;n<r;n+=1){let s=t[n];s&&this.recentErrors.delete(s[0]);}}};var Ie=class extends u{isInitialized=false;suppressNextScrollTimer=null;pageUnloadHandler=null;pageShowHandler=null;visibilityFlushHandler=null;prerenderActivationHandler=null;emitter=new ce;managers={};handlers={};integrationInstances={};get initialized(){return this.isInitialized}async init(e={}){if(this.isInitialized)return {sessionId:this.get("sessionId")??""};this.managers.storage=new Te;try{return this.setupState(e),this.managers.event=new pe(this.managers.storage,this.emitter),this.loadPersistedIdentity(),this.initializeHandlers(),this.setupPageLifecycleListeners(),await this.managers.event.recoverPersistedEvents().catch(t=>{a("warn","Failed to recover persisted events",{error:t});}),this.isInitialized=!0,{sessionId:this.get("sessionId")??""}}catch(t){this.destroy(true);let r=t instanceof Error?t.message:String(t);throw new Error(`[TraceLog] TraceLog initialization failed: ${r}`)}}sendCustomEvent(e,t,r){if(!this.managers.event){a("warn","Cannot send custom event: TraceLog not initialized",{data:{name:e}});return}let n=t;t&&typeof t=="object"&&!Array.isArray(t)&&Object.getPrototypeOf(t)!==Object.prototype&&(n=Object.assign({},t));let{valid:s,error:o,sanitizedMetadata:l}=Nt(e,n);if(!s){if(this.get("mode")==="qa")throw new Error(`[TraceLog] Custom event "${e}" validation failed: ${o}`);a("warn",`Custom event "${e}" dropped: ${o}`);return}this.managers.event.track({type:"custom",custom_event:{name:e,...l&&{metadata:l}}}),r?.critical===true&&(this.managers.event.flushImmediatelySync()||a("debug","Critical event flush returned false (deferred to in-flight send or empty queue)",{data:{name:e}}));}on(e,t){this.emitter.on(e,t);}off(e,t){this.emitter.off(e,t);}destroy(e=false){!this.isInitialized&&!e||(Object.values(this.handlers).filter(Boolean).forEach(t=>{try{t.stopTracking();}catch(r){a("warn","Failed to stop tracking",{error:r});}}),this.suppressNextScrollTimer&&(clearTimeout(this.suppressNextScrollTimer),this.suppressNextScrollTimer=null),this.pageUnloadHandler&&(window.removeEventListener("pagehide",this.pageUnloadHandler),window.removeEventListener("beforeunload",this.pageUnloadHandler),this.pageUnloadHandler=null),this.pageShowHandler&&(window.removeEventListener("pageshow",this.pageShowHandler),this.pageShowHandler=null),this.visibilityFlushHandler&&(document.removeEventListener("visibilitychange",this.visibilityFlushHandler),this.visibilityFlushHandler=null),this.prerenderActivationHandler&&(document.removeEventListener("prerenderingchange",this.prerenderActivationHandler),this.prerenderActivationHandler=null),this.managers.event?.flushImmediatelySync(),this.managers.event?.stop(),this.emitter.removeAllListeners(),this.set("suppressNextScroll",false),this.set("sessionId",null),this.set("identity",void 0),this.clearPersistedIdentity(),this.integrationInstances.shopifyCartLinker?.deactivate(),this.integrationInstances={},this.isInitialized=false,this.handlers={},this.managers={});}setupState(e={}){this.set("config",e);let t=he.getId(this.managers.storage);this.set("userId",t);let r=yt(e);this.set("collectApiUrls",r);let n=ht();this.set("device",n);let s=F(window.location.href,e.sensitiveQueryParams);this.set("pageUrl",s),St()&&this.set("mode","qa");}getConfig(){return this.get("config")}getCollectApiUrls(){return this.get("collectApiUrls")}getEventManager(){return this.managers.event}getSessionId(){return this.get("sessionId")}getUserId(){return this.get("userId")}identify(e,t){if(!e||typeof e!="string"||e.trim().length===0){a("warn","identify() called with invalid userId",{data:{type:typeof e,length:typeof e=="string"?e.trim().length:0}});return}if(e.trim().length>256){a("warn","identify() userId exceeds 256 characters",{data:{length:e.trim().length}});return}let r=e.trim(),n=$(t),s={userId:r,...n?{traits:n}:{}};this.set("identity",s),this.persistIdentity(s),a("debug","Visitor identified",{data:{userIdLength:r.length,traitKeys:n?Object.keys(n):[]}});}async resetIdentity(){await this.managers.event?.flushImmediately().catch(t=>(a("debug","Failed to flush before identity reset",{error:t}),false)),this.set("identity",void 0),this.clearPersistedIdentity();let e=le();this.managers.storage.setItem(P,e),this.set("userId",e),this.set("hasStartSession",false),this.set("sessionId",null),this.handlers.session?.stopTracking(),this.handlers.session?.startTracking(),a("debug","Identity reset, new UUID generated");}getProjectId(){return this.get("config")?.integrations?.tracelog?.projectId??"custom"}persistIdentity(e){try{let t=this.getProjectId(),r=q(t);this.managers.storage.setItem(r,JSON.stringify(e));}catch{a("debug","Failed to persist identity to localStorage");}}loadPersistedIdentity(){let e=this.managers.storage,t=this.getProjectId(),r=q(t);try{let n=e.getItem(I);if(n){let s=JSON.parse(n);if(e.removeItem(I),!this.isValidIdentityData(s)){a("debug","Invalid pending identity in localStorage, discarded");return}let o=this.normalizePersistedIdentity(s);e.setItem(r,JSON.stringify(o)),this.set("identity",o),a("debug","Migrated pending identity to project-scoped key");return}}catch{e.removeItem(I);}try{let n=e.getItem(r);if(n){let s=JSON.parse(n);if(!this.isValidIdentityData(s)){e.removeItem(r),a("debug","Invalid persisted identity in localStorage, discarded");return}let o=this.normalizePersistedIdentity(s);this.set("identity",o),a("debug","Loaded persisted identity");}}catch{a("debug","Failed to load persisted identity");}}isValidIdentityData(e){if(!e||typeof e!="object")return false;let{userId:t}=e;return !(typeof t!="string"||t.trim().length===0||t.trim().length>256)}normalizePersistedIdentity(e){let t=$(e.traits);return {userId:e.userId.trim(),...t?{traits:t}:{}}}clearPersistedIdentity(){try{let e=this.managers.storage,t=this.getProjectId();e.removeItem(q(t)),e.removeItem(I);}catch{a("debug","Failed to clear persisted identity");}}setupPageLifecycleListeners(){this.pageUnloadHandler=()=>{this.managers.event?.flushImmediatelySync();},this.pageShowHandler=e=>{e.persisted&&this.managers.event?.recoverPersistedEvents().catch(t=>{a("warn","Failed to recover persisted events on bfcache restore",{error:t});});},this.visibilityFlushHandler=()=>{typeof document>"u"||!document.hidden||this.get("config").flushOnPageHidden!==false&&this.managers.event?.flushImmediatelySync();},window.addEventListener("pagehide",this.pageUnloadHandler),window.addEventListener("beforeunload",this.pageUnloadHandler),window.addEventListener("pageshow",this.pageShowHandler),document.addEventListener("visibilitychange",this.visibilityFlushHandler);}initializeHandlers(){let e=this.get("config");this.handlers.session=new fe(this.managers.storage,this.managers.event),this.handlers.session.startTracking();let t=()=>{this.set("suppressNextScroll",true),this.suppressNextScrollTimer&&clearTimeout(this.suppressNextScrollTimer),this.suppressNextScrollTimer=window.setTimeout(()=>{this.set("suppressNextScroll",false);},500);};this.handlers.pageView=new Ee(this.managers.event,t),this.handlers.click=new ve(this.managers.event),this.handlers.scroll=new Se(this.managers.event),this.handlers.performance=new _e(this.managers.event),this.handlers.error=new ye(this.managers.event,this.emitter);let r=()=>{if(this.handlers.pageView?.startTracking(),this.handlers.click?.startTracking(),this.handlers.scroll?.startTracking(),this.handlers.performance?.startTracking().catch(n=>{a("warn","Failed to start performance tracking",{error:n});}),this.handlers.error?.startTracking(),e.integrations?.tracelog?.shopify){let n=new B;n.activate(),this.integrationInstances.shopifyCartLinker=n,this.emitter.on("event",s=>{s.type==="session_start"&&n.onSessionChange();});}};ne()?(this.prerenderActivationHandler=()=>{this.prerenderActivationHandler=null,r();},document.addEventListener("prerenderingchange",this.prerenderActivationHandler,{once:true})):r();}};var L=[],g=null,x=false,y=false,A=null,zt=async i=>typeof window>"u"||typeof document>"u"?{sessionId:""}:(y=false,window.__traceLogDisabled===true?{sessionId:""}:g?{sessionId:g.getSessionId()??""}:(x&&A||(x=true,A=(async()=>{try{let e=Mt(i??{}),t=new Ie;try{L.forEach(({event:o,callback:l})=>{t.on(o,l);}),L.length=0;let r=t.init(e),n=new Promise((o,l)=>{setTimeout(()=>{l(new Error(`[TraceLog] Initialization timeout after ${1e4}ms`));},1e4);}),s=await Promise.race([r,n]);return g=t,s}catch(r){try{t.destroy(!0);}catch(n){a("error","Failed to cleanup partially initialized app",{error:n});}throw r}}catch(e){throw g=null,e}finally{x=false,A=null;}})()),A)),Yt=(i,e,t)=>{if(!(typeof window>"u"||typeof document>"u")){if(!g)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(y)throw new Error("[TraceLog] Cannot send events while TraceLog is being destroyed");g.sendCustomEvent(i,e,t);}},qt=(i,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!g||x){L.push({event:i,callback:e});return}g.on(i,e);}},Jt=(i,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!g){let t=L.findIndex(r=>r.event===i&&r.callback===e);t!==-1&&L.splice(t,1);return}g.off(i,e);}},Zt=()=>typeof window>"u"||typeof document>"u"?false:g!==null,er=()=>typeof window>"u"||typeof document>"u"||!g?null:g.getSessionId(),tr=()=>typeof window>"u"||typeof document>"u"||!g?null:g.getUserId(),rr=()=>{if(!(typeof window>"u"||typeof document>"u")){if(y)throw new Error("[TraceLog] Destroy operation already in progress");if(!g){y=false;return}y=true;try{g.destroy(),g=null,x=!1,A=null,L.length=0,y=!1;}catch(i){g=null,x=false,A=null,L.length=0,y=false,a("warn","Error during destroy, forced cleanup completed",{error:i});}}},nr=(i,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!i||typeof i!="string"||i.trim().length===0){a("warn","identify() called with invalid userId");return}if(i.trim().length>256){a("warn","identify() userId exceeds 256 characters");return}if(y){a("warn","Cannot identify while TraceLog is being destroyed");return}if(g){g.identify(i,e);return}try{let t=$(e),r={userId:i.trim(),...t?{traits:t}:{}};localStorage.setItem(I,JSON.stringify(r)),a("debug","Identity persisted pre-init (will be applied on init)");}catch{a("debug","Failed to persist pre-init identity");}}},ir=async()=>{if(!(typeof window>"u"||typeof document>"u")){if(!g){try{localStorage.removeItem(I);}catch{}return}if(y)throw new Error("[TraceLog] Cannot reset identity while TraceLog is being destroyed");await g.resetIdentity();}};var da={init:zt,event:Yt,on:qt,off:Jt,isInitialized:Zt,getSessionId:er,getUserId:tr,destroy:rr,identify:nr,resetIdentity:ir};export{h as AppConfigValidationError,w as DEFAULT_SESSION_TIMEOUT,H as DEFAULT_WEB_VITALS_MODE,st as DeviceType,J as EmitterEvent,at as ErrorType,T as EventType,lt as InitializationTimeoutError,V as IntegrationValidationError,Re as MAX_ARRAY_LENGTH,G as MAX_CUSTOM_EVENT_ARRAY_SIZE,W as MAX_CUSTOM_EVENT_KEYS,j as MAX_CUSTOM_EVENT_NAME_LENGTH,K as MAX_CUSTOM_EVENT_STRING_SIZE,Me as MAX_NESTED_OBJECT_KEYS,M as MAX_STRING_LENGTH,X as MAX_STRING_LENGTH_IN_ARRAY,ke as Mode,wt as PII_PATTERNS,b as PermanentError,k as RateLimitError,U as SamplingRateValidationError,ot as ScrollDirection,Z as SessionTimeoutValidationError,it as SpecialApiUrl,D as TimeoutError,R as TraceLogValidationError,mr as WEB_VITALS_GOOD_THRESHOLDS,Ve as WEB_VITALS_NEEDS_IMPROVEMENT_THRESHOLDS,mt as WEB_VITALS_POOR_THRESHOLDS,re as getWebVitalsThresholds,da as tracelog};//# sourceMappingURL=public-api.js.map
3
3
  //# sourceMappingURL=public-api.js.map