@datalyr/web 1.7.6 → 1.7.9

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.
Files changed (46) hide show
  1. package/README.md +542 -476
  2. package/dist/attribution-lyr.test.d.ts +2 -0
  3. package/dist/attribution-lyr.test.d.ts.map +1 -0
  4. package/dist/attribution-oppref.test.d.ts +2 -0
  5. package/dist/attribution-oppref.test.d.ts.map +1 -0
  6. package/dist/attribution.d.ts.map +1 -1
  7. package/dist/config.d.ts +1 -0
  8. package/dist/config.d.ts.map +1 -1
  9. package/dist/container.d.ts +7 -3
  10. package/dist/container.d.ts.map +1 -1
  11. package/dist/container.test.d.ts +2 -0
  12. package/dist/container.test.d.ts.map +1 -0
  13. package/dist/datalyr.cjs.js +816 -51
  14. package/dist/datalyr.cjs.js.map +1 -1
  15. package/dist/datalyr.esm.js +816 -52
  16. package/dist/datalyr.esm.js.map +1 -1
  17. package/dist/datalyr.esm.min.js +1 -1
  18. package/dist/datalyr.esm.min.js.map +1 -1
  19. package/dist/datalyr.js +816 -51
  20. package/dist/datalyr.js.map +1 -1
  21. package/dist/datalyr.min.js +1 -1
  22. package/dist/datalyr.min.js.map +1 -1
  23. package/dist/identify-dedupe.test.d.ts +2 -0
  24. package/dist/identify-dedupe.test.d.ts.map +1 -0
  25. package/dist/identity-pii.test.d.ts +2 -0
  26. package/dist/identity-pii.test.d.ts.map +1 -0
  27. package/dist/identity.d.ts +46 -0
  28. package/dist/identity.d.ts.map +1 -1
  29. package/dist/index.d.ts +68 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.test.d.ts +3 -0
  32. package/dist/index.test.d.ts.map +1 -0
  33. package/dist/queue-403.test.d.ts +2 -0
  34. package/dist/queue-403.test.d.ts.map +1 -0
  35. package/dist/queue.d.ts +17 -0
  36. package/dist/queue.d.ts.map +1 -1
  37. package/dist/storage-migration.test.d.ts +2 -0
  38. package/dist/storage-migration.test.d.ts.map +1 -0
  39. package/dist/storage.d.ts.map +1 -1
  40. package/dist/stripe-session.d.ts +75 -0
  41. package/dist/stripe-session.d.ts.map +1 -0
  42. package/dist/stripe-session.test.d.ts +2 -0
  43. package/dist/stripe-session.test.d.ts.map +1 -0
  44. package/dist/types.d.ts +1 -0
  45. package/dist/types.d.ts.map +1 -1
  46. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- function t(t,e,i,s){return new(i||(i=Promise))(function(n,o){function r(t){try{c(s.next(t))}catch(t){o(t)}}function a(t){try{c(s.throw(t))}catch(t){o(t)}}function c(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,a)}c((s=s.apply(t,e||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const e=new class{constructor(){this.key=null,this.salt=null}initialize(e,i){return t(this,void 0,void 0,function*(){if(!crypto.subtle){const t=new Error("Web Crypto API not available - encryption cannot be initialized");throw console.error("[Datalyr Encryption]",t.message),t}try{const t=new TextEncoder,s="dl_encryption_salt";let n=localStorage.getItem(s);n?this.salt=this.base64ToArrayBuffer(n):(this.salt=crypto.getRandomValues(new Uint8Array(32)),n=this.arrayBufferToBase64(this.salt),localStorage.setItem(s,n));const o=`datalyr:${e}:${i}`,r=t.encode(o),a=yield crypto.subtle.importKey("raw",r,"PBKDF2",!1,["deriveKey"]);this.key=yield crypto.subtle.deriveKey({name:"PBKDF2",salt:this.salt,iterations:1e5,hash:"SHA-256"},a,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(t){throw console.error("[Datalyr Encryption] Failed to initialize:",t),this.key=null,t}})}encrypt(e){return t(this,void 0,void 0,function*(){if(!this.key||!crypto.subtle)throw new Error("Encryption not initialized - cannot encrypt sensitive data");try{const t="string"==typeof e?e:JSON.stringify(e),i=(new TextEncoder).encode(t),s=crypto.getRandomValues(new Uint8Array(12)),n=yield crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.key,i),o=new Uint8Array(s.length+n.byteLength);return o.set(s,0),o.set(new Uint8Array(n),s.length),this.arrayBufferToBase64(o)}catch(t){throw console.error("[Datalyr Encryption] Encryption failed:",t),t}})}decrypt(e){return t(this,void 0,void 0,function*(){if(!this.key||!crypto.subtle){console.warn("[Datalyr Encryption] Decryption not available - reading potentially unencrypted data");try{return JSON.parse(e)}catch(t){return e}}try{const t=this.base64ToArrayBuffer(e),i=t.slice(0,12),s=t.slice(12),n=yield crypto.subtle.decrypt({name:"AES-GCM",iv:i},this.key,s),o=(new TextDecoder).decode(n);try{return JSON.parse(o)}catch(t){return o}}catch(t){console.warn("[Datalyr Encryption] Decryption failed - attempting to read as unencrypted data (migration mode)");try{return JSON.parse(e)}catch(t){return e}}})}isAvailable(){return null!==this.key&&void 0!==crypto.subtle}arrayBufferToBase64(t){let e="";const i=new Uint8Array(t),s=i.byteLength;for(let t=0;t<s;t++)e+=String.fromCharCode(i[t]);return btoa(e)}base64ToArrayBuffer(t){const e=atob(t),i=e.length,s=new Uint8Array(i);for(let t=0;t<i;t++)s[t]=e.charCodeAt(t);return s}destroy(){this.key=null,this.salt=null}};class i{constructor(t){this.memory=new Map,this.prefix="dl_";try{if(!t)throw new Error("no storage");const e="dl_test__"+Math.random();t.setItem(e,"1"),t.removeItem(e),this.storage=t}catch(t){this.storage=null,"undefined"!=typeof window&&console.warn("[Datalyr] Storage not available, using memory fallback")}}get(t,e=null){const i=this.prefix+t;try{if(this.storage){const t=this.storage.getItem(i);if(null===t)return e;try{return JSON.parse(t)}catch(e){return t}}else{const t=this.memory.get(i);if(void 0===t)return e;try{return JSON.parse(t)}catch(e){return t}}}catch(t){return e}}getString(t,e=null){const i=this.prefix+t;try{const t=this.storage?this.storage.getItem(i):this.memory.has(i)?this.memory.get(i):null;if(null==t)return e;if(t.length>=2&&'"'===t[0]&&'"'===t[t.length-1])try{const e=JSON.parse(t);if("string"==typeof e)return e}catch(t){}return t}catch(t){return e}}set(t,e){const i=this.prefix+t,s="string"==typeof e?e:JSON.stringify(e);try{return this.storage?(this.storage.setItem(i,s),!0):(this.memory.set(i,s),!0)}catch(e){return console.warn("[Datalyr] Failed to store:",t,e),this.memory.set(i,s),!1}}remove(t){const e=this.prefix+t;try{return this.storage?(this.storage.removeItem(e),!0):(this.memory.delete(e),!0)}catch(t){return!1}}keys(){try{if(this.storage){const t=[];for(let e=0;e<this.storage.length;e++){const i=this.storage.key(e);i&&i.startsWith(this.prefix)&&t.push(i.slice(this.prefix.length))}return t}return Array.from(this.memory.keys()).filter(t=>t.startsWith(this.prefix)).map(t=>t.slice(this.prefix.length))}catch(t){return[]}}migrateFromLegacyPrefix(){if(!this.storage)return 0;let t=0;try{const e=[];for(let t=0;t<this.storage.length;t++){const i=this.storage.key(t);i&&i.startsWith("__dl_dl_")&&e.push(i)}e.forEach(e=>{try{const i=this.storage.getItem(e);if(i){const s=e.slice(5);this.storage.getItem(s)||(this.storage.setItem(s,i),t++),this.storage.removeItem(e)}}catch(t){console.warn(`[Datalyr Storage] Failed to migrate legacy key: ${e}`,t)}}),t>0&&console.log(`[Datalyr Storage] Migrated ${t} keys from legacy prefix`)}catch(t){console.warn("[Datalyr Storage] Error during legacy key migration:",t)}return t}getEncrypted(i){return t(this,arguments,void 0,function*(t,i=null){const s=this.prefix+t;try{let t=null;if(t=this.storage?this.storage.getItem(s):this.memory.get(s)||null,!t)return i;return yield e.decrypt(t)}catch(e){return console.warn("[Datalyr Storage] Failed to decrypt:",t,e),i}})}setEncrypted(i,s){return t(this,void 0,void 0,function*(){const t=this.prefix+i,n=yield e.encrypt(s);return this.storage?(this.storage.setItem(t,n),!0):(this.memory.set(t,n),!0)})}}class s{constructor(t={}){this.domain=t.domain||"auto",this.maxAge=t.maxAge||365,this.sameSite=t.sameSite||"Lax",this.secure=t.secure||"auto"}get(t){const e="undefined"!=typeof document?document.cookie:"";if(!e)return null;for(const i of e.split(";")){const e=i.trim(),s=e.indexOf("=");if(-1===s)continue;if(e.slice(0,s)!==t)continue;const n=e.slice(s+1);if(!n)return null;try{return decodeURIComponent(n)}catch(t){return n}}return null}set(t,e,i){try{const s=86400*(i||this.maxAge),n="auto"===this.secure?"https:"===location.protocol:this.secure;let o="";"auto"===this.domain?o=this.getAutoDomain():this.domain&&(o=`;domain=${this.domain}`);const r=[`${t}=${encodeURIComponent(e)}`,`max-age=${s}`,"path=/",`SameSite=${this.sameSite}`,n?"Secure":"",o].filter(Boolean).join(";");return document.cookie=r,!0}catch(e){return console.warn("[Datalyr] Failed to set cookie:",t,e),!1}}remove(t){try{const e=["",location.hostname],i=location.hostname.split(".");return i.length>2&&(e.push(`.${i.slice(-2).join(".")}`),e.push(`.${location.hostname}`)),e.forEach(e=>{const i=e?`;domain=${e}`:"";document.cookie=`${t}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${i}`}),!0}catch(t){return!1}}getAutoDomain(){const t=location.hostname;if("localhost"===t||/^[\d.]+$/.test(t)||/^\[[\d:]+\]$/.test(t))return"";const e=t.split(".");for(let t=e.length-2;t>=0;t--){const i="."+e.slice(t).join("."),s="__dl_test_"+Math.random();if(document.cookie=`${s}=1;domain=${i};path=/`,-1!==document.cookie.indexOf(s))return document.cookie=`${s}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;domain=${i};path=/`,`;domain=${i}`}return""}}const n="undefined"!=typeof window?window.localStorage:void 0,o="undefined"!=typeof window?window.sessionStorage:void 0,r=new i(n);new i(o);const a=new s;function c(e){return t(this,void 0,void 0,function*(){if("undefined"==typeof crypto||!crypto.subtle)return null;if(!e)return null;try{const t=(new TextEncoder).encode(e.toLowerCase().trim()),i=yield crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("")}catch(t){return null}})}function l(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function h(t=window.location.search){const e={};try{if("URLSearchParams"in window){return new URLSearchParams(t).forEach((t,i)=>{e[i]=t}),e}}catch(t){}const i=(t||"").replace(/^\?/,"").split("&");for(const t of i){const[i,s=""]=t.split("=");try{const t=decodeURIComponent((i||"").replace(/\+/g," ")),n=decodeURIComponent((s||"").replace(/\+/g," "));t&&(e[t]=n)}catch(t){}}return e}const d=new Set(["pass","password","passwd","pwd","secret","token","auth","authorization","bearer","signature","cvv","cvc","ssn"]),u=["apikey","accesskey","secretkey","privatekey","publickey","accesstoken","refreshtoken","idtoken","clientsecret","creditcard","cardnumber"];function f(t){if(t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[\s._\-]+/).map(t=>t.toLowerCase()).filter(Boolean).some(t=>d.has(t)))return!0;const e=t.toLowerCase().replace(/[\s._\-]+/g,"");return u.some(t=>e.includes(t))}function p(t,e=5,i=0){if(i>=e)return"[Max depth reached]";if(null==t)return t;if("undefined"!=typeof Element&&t instanceof Element||"undefined"!=typeof Document&&t instanceof Document||"function"==typeof t)return"[Removed]";if(Array.isArray(t))return t.map(t=>p(t,e,i+1));if("object"==typeof t){const s={};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(f(n))continue;s[n]=p(t[n],e,i+1)}return s}return"string"==typeof t?t.length>1e3?t.slice(0,1e3)+"...[truncated]":/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t)?"[Redacted]":t:t}const g=new Set(["token","access_token","refresh_token","id_token","auth","authorization","password","pass","pwd","secret","api_key","apikey","key","session","session_id","sid","email","e","phone","tel","signature","sig","otp","reset","hash"]),m=new Set(["state","client_id","redirect_uri","response_type","grant_type","code_challenge","session_state","scope","iss","access_token","id_token","refresh_token","token"]);function y(t){const e=new URLSearchParams(t);let i=!1;const s=Array.from(new Set(e.keys())).map(t=>t.toLowerCase()).some(t=>m.has(t));for(const t of Array.from(new Set(e.keys()))){const n=t.toLowerCase();("code"===n?s:g.has(n))&&(e.set(t,"__redacted__"),i=!0)}return{out:e.toString(),mutated:i}}function v(t){if(!t||"string"!=typeof t)return t;const e=t.indexOf("#"),i=t.indexOf("?"),s=-1!==i&&(-1===e||i<e)?i:-1;if(-1===s&&-1===e)return t;try{const i=t.slice(0,-1!==s?s:-1!==e?e:t.length),n=-1===s?"":t.slice(s+1,-1===e?t.length:e),o=-1===e?"":t.slice(e+1);let r=!1,a=n;if(n){const t=y(n);t.mutated&&(a=t.out,r=!0)}let c=o;if(o){const t=o.indexOf("?");if(-1!==t){const e=y(o.slice(t+1));e.mutated&&(c=o.slice(0,t+1)+e.out,r=!0)}else if(/[\w-]+=/.test(o)){const t=y(o);t.mutated&&(c=t.out,r=!0)}}return r?i+(-1===s?"":"?"+a)+(-1===e?"":"#"+c):t}catch(e){return t}}function _(t,...e){if(!e.length)return t;const i=e.shift();if(w(t)&&w(i))for(const e in i)w(i[e])?(t[e]||Object.assign(t,{[e]:{}}),_(t[e],i[e])):Object.assign(t,{[e]:i[e]});return _(t,...e)}function w(t){return t&&"object"==typeof t&&!Array.isArray(t)}const b=new Set(["co.uk","org.uk","net.uk","ac.uk","gov.uk","me.uk","com.au","net.au","org.au","edu.au","gov.au","co.nz","net.nz","org.nz","govt.nz","co.jp","ne.jp","or.jp","ac.jp","go.jp","co.in","net.in","org.in","gov.in","ac.in","co.za","net.za","org.za","gov.za","com.br","net.br","org.br","gov.br","edu.br","co.kr","ne.kr","or.kr","go.kr","ac.kr","com.cn","net.cn","org.cn","gov.cn","edu.cn","co.id","co.th","com.sg","com.my","com.ph","com.vn","com.tw","com.hk","com.mx","com.ar","com.co","com.pe","com.cl","co.il","co.at","co.hu","co.pl"]);function k(t){if(!t)return t;const e=t.toLowerCase();if("localhost"===e||/^[0-9]{1,3}(\.[0-9]{1,3}){3}$/.test(e)||/^\[?[0-9a-fA-F:]+\]?$/.test(e))return t;const i=e.split(".");if(i.length<2)return t;const s=i.slice(-2).join(".");return b.has(s)&&i.length>=3?i.slice(-3).join("."):i.slice(-2).join(".")}function S(t){const e={google:["google.com","google."],facebook:["facebook.com","fb.com"],twitter:["twitter.com","t.co","x.com"],linkedin:["linkedin.com","lnkd.in"],instagram:["instagram.com"],youtube:["youtube.com","youtu.be"],tiktok:["tiktok.com"],reddit:["reddit.com"],pinterest:["pinterest.com"],bing:["bing.com"],yahoo:["yahoo.com"],duckduckgo:["duckduckgo.com"],baidu:["baidu.com"]};for(const[i,s]of Object.entries(e))if(s.some(e=>t.includes(e)))return i;return"other"}class I{constructor(t={}){this.userId=null,this.sessionId=null,this.persistNewId=!1!==t.persistNewId,this.anonymousId=this.getOrCreateAnonymousId(),this.userId=this.getStoredUserId()}getOrCreateAnonymousId(){let t=a.get("__dl_visitor_id");if(t)return r.set("dl_anonymous_id",t),t;if(t=r.getString("dl_anonymous_id"),t)return this.setRootDomainCookie("__dl_visitor_id",t),t;try{new URLSearchParams(window.location.search).has("_dl_vid")&&this.stripUrlParam("_dl_vid")}catch(t){console.warn("[Datalyr] Failed to parse URL for _dl_vid:",t)}return t=`anon_${l()}`,this.persistAnonymousId(t),t}persistAnonymousId(t){this.persistNewId&&(this.setRootDomainCookie("__dl_visitor_id",t),r.set("dl_anonymous_id",t))}enablePersistence(){this.persistNewId||(this.persistNewId=!0,this.persistAnonymousId(this.anonymousId))}stripUrlParam(t){var e;try{if("undefined"==typeof window||"function"!=typeof(null===(e=window.history)||void 0===e?void 0:e.replaceState))return;const i=new URL(window.location.href);if(!i.searchParams.has(t))return;i.searchParams.delete(t);const s=i.searchParams.toString(),n=i.pathname+(s?"?"+s:"")+i.hash;window.history.replaceState(window.history.state,"",n)}catch(t){}}setRootDomainCookie(t,e){try{const i=function(){const t=window.location.hostname;return"localhost"===t||t.match(/^[0-9]{1,3}\./)||t.match(/^\[?[0-9a-fA-F:]+\]?$/)||t.split(".").length<2?t:"."+k(t)}(),s="https:"===location.protocol?"; Secure":"",n=encodeURIComponent(e);document.cookie=`${t}=${n}; domain=${i}; path=/; max-age=31536000; SameSite=Lax${s}`;a.get(t)!==e&&(document.cookie=`${t}=${n}; path=/; max-age=31536000; SameSite=Lax${s}`)}catch(i){console.error("[Datalyr] Error setting root domain cookie:",i);try{const i="https:"===location.protocol?"; Secure":"",s=encodeURIComponent(e);document.cookie=`${t}=${s}; path=/; max-age=31536000; SameSite=Lax${i}`}catch(t){console.error("[Datalyr] Failed to set cookie even without domain:",t)}}}getStoredUserId(){return r.getString("dl_user_id")}getAnonymousId(){return this.anonymousId}getUserId(){return this.userId}getDistinctId(){return this.userId||this.anonymousId}getCanonicalId(){return this.getDistinctId()}setSessionId(t){this.sessionId=t}getSessionId(){return this.sessionId}identify(t,e={}){if(!t)return console.warn("[Datalyr] identify() called without userId"),{};const i=this.userId;return this.userId=t,r.set("dl_user_id",t),{anonymous_id:this.anonymousId,user_id:t,previous_id:i,traits:e,identified_at:(new Date).toISOString(),resolution_method:"identify_call"}}alias(t,e){const i={userId:t,previousId:e||this.anonymousId,aliased_at:(new Date).toISOString()};return e&&e!==this.anonymousId||(this.userId=t,r.set("dl_user_id",t)),i}reset(){this.userId=null,r.remove("dl_user_id"),r.remove("dl_user_traits"),this.anonymousId=`anon_${l()}`,r.set("dl_anonymous_id",this.anonymousId),this.setRootDomainCookie("__dl_visitor_id",this.anonymousId)}getIdentityFields(){return{distinct_id:this.getDistinctId(),anonymous_id:this.anonymousId,user_id:this.userId,visitor_id:this.anonymousId,visitorId:this.anonymousId,canonical_id:this.getCanonicalId(),session_id:this.sessionId,sessionId:this.sessionId,resolution_method:"browser_sdk",resolution_confidence:1}}}class C{constructor(t=36e5){this.sessionId=null,this.sessionData=null,this.lastActivity=Date.now(),this.SESSION_KEY="dl_session_data",this.activityCheckInterval=null,this.activityListeners=[],this.sessionCreationLock=!1,this.sessionTimeout=t,this.initSession(),this.setupActivityMonitor()}initSession(){const t=r.get(this.SESSION_KEY),e=Date.now();t&&this.isSessionValid(t,e)?(this.sessionData=t,this.sessionId=t.id,this.lastActivity=e):this.createNewSession()}isSessionValid(t,e){return e-t.lastActivity<this.sessionTimeout&&t.isActive}createNewSession(){if(this.sessionCreationLock)return console.log("[Datalyr Session] Session creation already in progress, returning existing ID"),this.sessionId||"";this.sessionCreationLock=!0;try{const t=Date.now();return this.sessionId=`sess_${l()}`,this.sessionData={id:this.sessionId,startTime:t,lastActivity:t,pageViews:0,events:0,duration:0,isActive:!0},this.saveSession(),this.incrementSessionCount(),this.sessionId}finally{this.sessionCreationLock=!1}}rotateSessionId(){const t=Date.now(),e=this.sessionId;return this.sessionId=`sess_${l()}`,this.sessionData?(this.sessionData.id=this.sessionId,this.sessionData.lastActivity=t,this.saveSession(),e&&r.remove(`dl_session_${e}_attribution`),console.log(`[Datalyr Session] Rotated session ID from ${e} to ${this.sessionId}`)):this.createNewSession(),this.sessionId}getSessionId(){return this.sessionId&&this.isSessionActive()||this.createNewSession(),this.sessionId}getSessionData(){return this.sessionData}updateActivity(t){const e=Date.now();this.sessionData&&this.isSessionValid(this.sessionData,e)?(this.lastActivity=e,this.sessionData.lastActivity=e,this.sessionData.duration=e-this.sessionData.startTime,"pageview"!==t&&"page_view"!==t||this.sessionData.pageViews++,this.sessionData.events++,this.saveSession()):this.createNewSession()}isSessionActive(){if(!this.sessionData)return!1;const t=Date.now();return this.isSessionValid(this.sessionData,t)}endSession(){this.sessionData&&(this.sessionData.isActive=!1,this.saveSession()),this.sessionId=null,this.sessionData=null,this.destroy()}saveSession(){this.sessionData&&r.set(this.SESSION_KEY,this.sessionData)}getTimeout(){return this.sessionTimeout}setTimeout(t){this.sessionTimeout=t}storeAttribution(t){r.set("dl_current_session_attribution",Object.assign(Object.assign({},t),{sessionId:this.sessionId,timestamp:Date.now()}))}getAttribution(){if(!this.sessionId)return null;if(!this.isSessionActive())return null;const t=r.get("dl_current_session_attribution");return t&&t.sessionId===this.sessionId?t:null}getMetrics(){return this.sessionData?{session_id:this.sessionId,session_duration:this.sessionData.duration,session_page_views:this.sessionData.pageViews,session_events:this.sessionData.events,session_start:this.sessionData.startTime,time_since_session_start:Date.now()-this.sessionData.startTime}:{}}setupActivityMonitor(){const t=()=>{const t=Date.now();this.sessionData&&t-this.lastActivity>1e3&&this.updateActivity()};["mousedown","keydown","scroll","touchstart"].forEach(e=>{window.addEventListener(e,t,{passive:!0,capture:!0}),this.activityListeners.push({event:e,handler:t})}),this.activityCheckInterval=setInterval(()=>{this.sessionData&&!this.isSessionActive()&&this.createNewSession()},6e4)}destroy(){this.activityListeners.forEach(({event:t,handler:e})=>{window.removeEventListener(t,e)}),this.activityListeners=[],this.activityCheckInterval&&(clearInterval(this.activityCheckInterval),this.activityCheckInterval=null)}getSessionNumber(){return r.get("dl_session_count",0)+1}incrementSessionCount(){const t=r.get("dl_session_count",0);r.set("dl_session_count",t+1)}}class E{constructor(t={}){this.queryParamsCache=null,this.UTM_PARAMS=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],this.CLICK_IDS=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","twclid","li_fat_id","sclid","dclid","epik","rdt_cid","obclid","irclid","ko_click_id"],this.CLICK_ID_ALIASES={ScCid:"sclid",sccid:"sclid",irclickid:"irclid"},this.DEFAULT_TRACKED_PARAMS=["lyr","ref","source","campaign","medium","gad_source"],this.MARKETING_COOKIES=["_fbp","_fbc","_gcl_aw","_gcl_dc","_gcl_gb","_gcl_ha","_gac","_ttp","_ttc","_scid"],this.attributionWindow=t.attributionWindow||7776e6,this.trackedParams=[...this.DEFAULT_TRACKED_PARAMS,...t.trackedParams||[]],this.marketingAllowedFn=t.marketingAllowed}isMarketingAllowed(){return!this.marketingAllowedFn||!1!==this.marketingAllowedFn()}clearCache(){this.queryParamsCache=null}captureAttribution(){const t=this.queryParamsCache||h();this.queryParamsCache||(this.queryParamsCache=t);const e={timestamp:Date.now()};for(const i of this.UTM_PARAMS){const s=t[i];if(s){e[i]=s;e[i.replace("utm_","")]=s}}for(const i of this.CLICK_IDS){const s=t[i];s&&(e.clickId||(e.clickId=s,e.clickIdType=i),e[i]=s)}for(const[i,s]of Object.entries(this.CLICK_ID_ALIASES)){const n=t[i];n&&!e[s]&&(e.clickId||(e.clickId=n,e.clickIdType=s),e[s]=n)}for(const i of this.trackedParams){const s=t[i];s&&(e[i]=s)}return document.referrer&&(e.referrer=v(document.referrer),e.referrerHost=this.extractHostname(document.referrer)),e.landingPage=v(window.location.href),e.landingPath=window.location.pathname,e.source||(e.source=this.determineSource(e)),e.medium||(e.medium=this.determineMedium(e)),e}storeFirstTouch(t){const e=r.get("dl_first_touch");let i=!1;e?e.expires_at&&Date.now()>=e.expires_at&&(i=!0):i=!0,i&&r.set("dl_first_touch",Object.assign(Object.assign({},t),{captured_at:Date.now(),expires_at:Date.now()+this.attributionWindow}))}getFirstTouch(){const t=r.get("dl_first_touch");return t&&t.expires_at&&Date.now()>=t.expires_at?(r.remove("dl_first_touch"),null):t}storeLastTouch(t){r.set("dl_last_touch",Object.assign(Object.assign({},t),{captured_at:Date.now(),expires_at:Date.now()+this.attributionWindow}))}getLastTouch(){const t=r.get("dl_last_touch");return t&&t.expires_at&&Date.now()>=t.expires_at?(r.remove("dl_last_touch"),null):t}addTouchpoint(t,e){const i=this.getJourney(),s={timestamp:Date.now(),sessionId:t,source:e.source||void 0,medium:e.medium||void 0,campaign:e.campaign||void 0};i.push(s),i.length>30&&i.shift(),r.set("dl_journey",i)}getJourney(){return r.get("dl_journey",[])}captureAdCookies(){var t,e;const i={},s=this.isMarketingAllowed();if(i._fbp=a.get("_fbp"),i._fbc=a.get("_fbc"),i._gcl_aw=a.get("_gcl_aw"),i._gcl_dc=a.get("_gcl_dc"),i._gcl_gb=a.get("_gcl_gb"),i._gcl_ha=a.get("_gcl_ha"),i._gac=a.get("_gac"),i._ga=a.get("_ga"),i._gid=a.get("_gid"),i._ttp=a.get("_ttp"),i._ttc=a.get("_ttc"),i._scid=a.get("_scid"),s&&!i._fbp&&(this.hasClickId("fbclid")||i._fbc)){const t=Date.now(),e=Math.floor(1e10*Math.random()).toString();i._fbp=`fb.1.${t}.${e}`,a.set("_fbp",i._fbp,90)}const n=this.getCurrentFbclid();if(s&&n){const t=i._fbc,e=this.extractFbclidFromFbc(t);if(t){if(e&&e!==n){const t=Date.now();i._fbc=`fb.1.${t}.${n}`,a.set("_fbc",i._fbc,90),a.set("_dl_fbclid_at",String(t),90)}}else{const t=a.get("_dl_fbclid_at"),e=t?Number(t):NaN,s=Number.isFinite(e)&&e>0?e:Date.now();t||a.set("_dl_fbclid_at",String(s),90),i._fbc=`fb.1.${s}.${n}`,a.set("_fbc",i._fbc,90)}}const o=this.hasClickId("gclid")&&null!==(e=null===(t=this.queryParamsCache)||void 0===t?void 0:t.gclid)&&void 0!==e?e:null;return s&&o&&!a.get("_dl_gclid_at")&&a.set("_dl_gclid_at",String(Date.now()),90),Object.fromEntries(Object.entries(i).filter(([t,e])=>null!==e))}hasClickId(t){return!!(this.queryParamsCache||h())[t]}getCurrentFbclid(){return(this.queryParamsCache||h()).fbclid||null}extractFbclidFromFbc(t){if(!t)return null;const e=t.split(".");return e.length<4||"fb"!==e[0]?null:e.slice(3).join(".")||null}getAttributionData(){const t=this.getFirstTouch(),e=this.getLastTouch(),i=this.getJourney();let s=this.captureAttribution();const n=!!(s.clickId||s.campaign||s.source&&"direct"!==s.source);if(!n){const i=e||t;i&&(s=Object.assign(Object.assign({},i),{referrer:s.referrer,referrerHost:s.referrerHost,landingPage:s.landingPage,landingPath:s.landingPath}))}const o=this.captureAdCookies();!t&&n&&this.storeFirstTouch(s),n&&this.storeLastTouch(s);const r=Object.assign(Object.assign(Object.assign({},s),o),{first_touch_source:null==t?void 0:t.source,first_touch_medium:null==t?void 0:t.medium,first_touch_campaign:null==t?void 0:t.campaign,first_touch_timestamp:null==t?void 0:t.timestamp,firstTouchSource:null==t?void 0:t.source,firstTouchMedium:null==t?void 0:t.medium,firstTouchCampaign:null==t?void 0:t.campaign,last_touch_source:null==e?void 0:e.source,last_touch_medium:null==e?void 0:e.medium,last_touch_campaign:null==e?void 0:e.campaign,last_touch_timestamp:null==e?void 0:e.timestamp,lastTouchSource:null==e?void 0:e.source,lastTouchMedium:null==e?void 0:e.medium,lastTouchCampaign:null==e?void 0:e.campaign,touchpoint_count:i.length,touchpointCount:i.length,days_since_first_touch:(null==t?void 0:t.timestamp)?Math.floor((Date.now()-t.timestamp)/864e5):0,daysSinceFirstTouch:(null==t?void 0:t.timestamp)?Math.floor((Date.now()-t.timestamp)/864e5):0});if(!this.isMarketingAllowed()){const t=[...this.CLICK_IDS,...Object.values(this.CLICK_ID_ALIASES),"clickId","clickIdType",...this.MARKETING_COOKIES];for(const e of t)delete r[e]}return r}determineSource(t){if(t.clickIdType){return{fbclid:"facebook",gclid:"google",gbraid:"google",wbraid:"google",ttclid:"tiktok",msclkid:"bing",twclid:"twitter",li_fat_id:"linkedin",sclid:"snapchat",dclid:"doubleclick",epik:"pinterest",rdt_cid:"reddit",obclid:"outbrain",irclid:"impact",ko_click_id:"klaviyo"}[t.clickIdType]||"paid"}if(t.referrerHost){const e=t.referrerHost.toLowerCase(),i=("undefined"!=typeof window?window.location.hostname:"").toLowerCase();return i&&(e===i||this.isSameRootDomain(e,i))?"direct":e.includes("facebook.com")||e.includes("fb.com")?"facebook":e.includes("twitter.com")||e.includes("t.co")||e.includes("x.com")?"twitter":e.includes("linkedin.com")||e.includes("lnkd.in")?"linkedin":e.includes("instagram.com")?"instagram":e.includes("youtube.com")||e.includes("youtu.be")?"youtube":e.includes("tiktok.com")?"tiktok":e.includes("reddit.com")?"reddit":e.includes("pinterest.com")?"pinterest":e.includes("google.")?"google":e.includes("bing.com")?"bing":e.includes("yahoo.com")?"yahoo":e.includes("duckduckgo.com")?"duckduckgo":e.includes("baidu.com")?"baidu":"referral"}return"direct"}determineMedium(t){if(t.clickId)return"cpc";const e=t.source;if(!e||"direct"===e)return"none";if(["facebook","twitter","linkedin","instagram","youtube","tiktok","reddit","pinterest"].includes(e))return"social";return["google","bing","yahoo","duckduckgo","baidu"].includes(e)?"organic":"referral"}isSameRootDomain(t,e){return k(t)===k(e)}extractHostname(t){try{return new URL(t).hostname}catch(t){return""}}isAttributionExpired(t){return!t.timestamp||Date.now()-t.timestamp>this.attributionWindow}clearExpiredAttribution(){const t=this.getFirstTouch(),e=this.getLastTouch();t&&this.isAttributionExpired(t)&&r.remove("dl_first_touch"),e&&this.isAttributionExpired(e)&&r.remove("dl_last_touch")}}const A=["purchase","signup","subscribe","lead","conversion"],D=["add_to_cart","begin_checkout","view_item","search"];class T extends Error{}class x extends Error{constructor(t,e){super(e||`HTTP ${t}`),this.status=t}}class P{constructor(t){this.queue=[],this.offlineQueue=[],this.batchTimer=null,this.periodicFlushInterval=null,this.flushPromise=null,this.recentEventIds=new Set,this.MAX_RECENT_EVENT_IDS=1e3,this.OFFLINE_QUEUE_KEY="dl_offline_queue",this.flushLock=!1,this.offlineQueueLock=!1,this.offlineProcessing=!1,this.inFlight=[],this.enabled=!0,this.rateLimitedUntil=0;const e=(t,e,i,s)=>{const n=Number(t);return Number.isFinite(n)?Math.min(Math.max(Math.floor(n),i),s):e};this.config={batchSize:e(t.batchSize,10,1,1e3),flushInterval:e(t.flushInterval,5e3,250,36e5),maxRetries:e(t.maxRetries,5,0,20),retryDelay:e(t.retryDelay,1e3,0,6e4),endpoint:t.endpoint||"https://ingest.datalyr.com",fallbackEndpoints:Array.isArray(t.fallbackEndpoints)?t.fallbackEndpoints:[],workspaceId:t.workspaceId,debug:t.debug||!1,criticalEvents:t.criticalEvents||A,highPriorityEvents:t.highPriorityEvents||D,maxOfflineQueueSize:e(t.maxOfflineQueueSize,100,1,1e5)},this.networkStatus={isOnline:!1!==navigator.onLine,lastOfflineAt:null,lastOnlineAt:null},this.loadOfflineQueue(),this.setupNetworkListeners(),this.startPeriodicFlush(),this.networkStatus.isOnline&&this.offlineQueue.length>0&&setTimeout(()=>this.processOfflineQueue(),1e3)}enqueue(t){if(!this.enabled)return;const e=t.event_name;if(this.isDuplicateEvent(t))this.log("Duplicate event suppressed:",e);else{if(this.config.criticalEvents.includes(e))return this.log("Critical event, sending immediately:",e),this.persistCriticalEvent(t),void this.sendBatch([t]).then(()=>{this.removeFromOfflineQueue(t.event_id)}).catch(i=>{if(i instanceof x)return this.log("Critical event permanently rejected, dropping:",e,i),void this.removeFromOfflineQueue(t.event_id);this.log("Critical event send failed, retained in offline queue:",e,i)});this.queue.push(t),this.log("Event queued:",e),this.shouldFlush(e)&&this.flush()}}isDuplicateEvent(t){const e=this.createEventHash(t);if(this.recentEventIds.has(e))return!0;if(this.recentEventIds.add(e),this.recentEventIds.size>this.MAX_RECENT_EVENT_IDS){const t=this.recentEventIds.size-this.MAX_RECENT_EVENT_IDS,e=this.recentEventIds.values();for(let i=0;i<t;i++){const t=e.next();t.done||this.recentEventIds.delete(t.value)}}return!1}createEventHash(t){const e=[t.event_name,t.timestamp,JSON.stringify(t.event_data||{})].join("|");let i=0;for(let t=0;t<e.length;t++){i=(i<<5)-i+e.charCodeAt(t),i&=i}return i.toString(36)}shouldFlush(t){return this.queue.length>=this.config.batchSize||(t&&this.config.highPriorityEvents.includes(t)?(this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(()=>this.flush(),1e3),!1):(this.batchTimer||(this.batchTimer=setTimeout(()=>this.flush(),this.config.flushInterval)),!1))}flush(){return t(this,void 0,void 0,function*(){if(this.enabled&&!(Date.now()<this.rateLimitedUntil)){if(this.flushPromise||this.flushLock)return this.flushPromise||Promise.resolve();this.flushLock=!0;try{this.flushPromise=this._flush(),yield this.flushPromise}finally{this.flushPromise=null,this.flushLock=!1}}})}_flush(){return t(this,void 0,void 0,function*(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),0===this.queue.length)return;if(!this.networkStatus.isOnline)return this.log("Network offline, queuing events"),void this.moveToOfflineQueue();const t=Math.min(this.config.batchSize,this.queue.length),e=this.queue.slice(0,t);this.inFlight=e;try{yield this.sendBatch(e),this.queue.splice(0,t),this.log(`Successfully sent and removed ${t} events from queue`)}catch(i){this.log("Failed to send batch:",i),this.queue.splice(0,t),i instanceof x?this.log(`Dropping ${e.length} events — permanent error ${i.status}`):this.moveToOfflineQueue(e)}finally{this.inFlight=[]}})}sendBatch(e){return t(this,arguments,void 0,function*(t,e=0,i=0){const s={events:t,batchId:l(),timestamp:(new Date).toISOString()},n=[this.config.endpoint,...this.config.fallbackEndpoints],o=n[i]||this.config.endpoint,r=JSON.stringify(s),a=new Blob([r]).size<=6e4;let c=!1;try{c=!/(^|\.)datalyr\.com$/i.test(new URL(o).hostname)}catch(t){}try{const e=yield fetch(o,Object.assign({method:"POST",headers:{"Content-Type":"application/json","X-Batch-Size":t.length.toString()},body:r,keepalive:a},c?{credentials:"include"}:{}));if(!e.ok){if(429===e.status){const t=parseInt(e.headers.get("Retry-After")||"60");throw this.rateLimitedUntil=Date.now()+1e3*Math.max(t,1),this.log(`Rate limited; backing off ${t}s`),new T("Rate limited (429)")}if(e.status>=400&&e.status<500&&408!==e.status)throw new x(e.status,`HTTP ${e.status}: ${e.statusText}`);throw new Error(`HTTP ${e.status}: ${e.statusText}`)}this.log(`Batch sent successfully to ${o}: ${t.length} events`)}catch(s){if(s instanceof T||s instanceof x)throw s;if(i<n.length-1)return this.log(`Failed on ${o}, trying fallback ${i+1}`),this.sendBatch(t,0,i+1);if(e<this.config.maxRetries){const s=function(t,e=1e3){const i=.1*Math.random();return Math.min(e*Math.pow(2,t)*(1+i),3e4)}(e,this.config.retryDelay);return this.log(`Retrying batch in ${s}ms (attempt ${e+1}/${this.config.maxRetries})`),yield new Promise(t=>setTimeout(t,s)),this.sendBatch(t,e+1,i)}throw s}})}setupNetworkListeners(){window.addEventListener("online",()=>{this.networkStatus.isOnline=!0,this.networkStatus.lastOnlineAt=Date.now(),this.log("Network connection restored"),setTimeout(()=>this.processOfflineQueue(),1e3)}),window.addEventListener("offline",()=>{this.networkStatus.isOnline=!1,this.networkStatus.lastOfflineAt=Date.now(),this.log("Network connection lost")})}startPeriodicFlush(){this.periodicFlushInterval=setInterval(()=>{this.queue.length>0&&this.flush(),this.networkStatus.isOnline&&this.offlineQueue.length>0&&this.processOfflineQueue()},this.config.flushInterval)}stopPeriodicFlush(){this.periodicFlushInterval&&(clearInterval(this.periodicFlushInterval),this.periodicFlushInterval=null)}moveToOfflineQueue(t){if(this.enabled)if(this.offlineQueueLock)console.warn("[Datalyr Queue] Offline queue operation already in progress");else{this.offlineQueueLock=!0;try{if(t?this.offlineQueue.push(...t):(this.offlineQueue.push(...this.queue),this.queue=[]),this.offlineQueue.length>this.config.maxOfflineQueueSize){const t=this.offlineQueue.length-this.config.maxOfflineQueueSize;this.offlineQueue.splice(0,t)}this.saveOfflineQueue()}finally{this.offlineQueueLock=!1}}}persistCriticalEvent(t){this.enabled&&(this.offlineQueue.some(e=>e.event_id===t.event_id)||(this.offlineQueue.push(t),this.offlineQueue.length>this.config.maxOfflineQueueSize&&this.offlineQueue.splice(0,this.offlineQueue.length-this.config.maxOfflineQueueSize),this.saveOfflineQueue()))}removeFromOfflineQueue(t){const e=this.offlineQueue.length;this.offlineQueue=this.offlineQueue.filter(e=>e.event_id!==t),this.offlineQueue.length!==e&&(0===this.offlineQueue.length?r.remove(this.OFFLINE_QUEUE_KEY):this.saveOfflineQueue())}loadOfflineQueue(){const t=r.get(this.OFFLINE_QUEUE_KEY,[]);Array.isArray(t)&&(this.offlineQueue=t,this.log(`Loaded ${this.offlineQueue.length} offline events`))}saveOfflineQueue(){if(!this.enabled)return;const t=this.offlineQueue.slice(-this.config.maxOfflineQueueSize);r.set(this.OFFLINE_QUEUE_KEY,t)}processOfflineQueue(){return t(this,void 0,void 0,function*(){if(this.enabled){if(this.consentCheck&&!1===this.consentCheck())return this.enabled=!1,void this.clearOffline();if(!(Date.now()<this.rateLimitedUntil)&&!this.offlineProcessing&&0!==this.offlineQueue.length&&this.networkStatus.isOnline){this.offlineProcessing=!0;try{for(this.log(`Processing ${this.offlineQueue.length} offline events`);this.offlineQueue.length>0&&this.enabled;){const t=this.offlineQueue.splice(0,this.config.batchSize);try{yield this.sendBatch(t),this.saveOfflineQueue()}catch(e){if(e instanceof x){this.log(`Dropping poison offline batch (${t.length}) — permanent error ${e.status}`),this.saveOfflineQueue();continue}this.log("Failed to send offline batch:",e),this.offlineQueue.unshift(...t),this.saveOfflineQueue();break}}0===this.offlineQueue.length&&r.remove(this.OFFLINE_QUEUE_KEY)}finally{this.offlineProcessing=!1}}}})}getQueueSize(){return this.queue.length}getOfflineQueueSize(){return this.offlineQueue.length}getNetworkStatus(){return Object.assign({},this.networkStatus)}buildBatch(t){return{events:t,batchId:l(),timestamp:(new Date).toISOString()}}forceFlush(){return t(this,arguments,void 0,function*(t=!1){if(!this.enabled)return;if(!t){if(Date.now()<this.rateLimitedUntil)return;return yield this.flush(),void(yield this.processOfflineQueue())}const e=this.queue.slice(this.inFlight.length),i=[...e,...this.offlineQueue];if(this.queue=this.queue.slice(0,this.inFlight.length),this.offlineQueue=[],0===i.length)return;if(this.enabled){const t=i.slice(-this.config.maxOfflineQueueSize);i.length>t.length&&this.log(`Offline cap dropped ${i.length-t.length} oldest events at unload`),r.set(this.OFFLINE_QUEUE_KEY,t)}if(0===e.length)return;if(Date.now()<this.rateLimitedUntil)return;if(!navigator.sendBeacon)return;const s=[];let n=[],o=2;for(const t of e){const e=new Blob([JSON.stringify(t)]).size+1;n.length>0&&(n.length>=this.config.batchSize||o+e>6e4)&&(s.push(n),n=[],o=2),n.push(t),o+=e}n.length>0&&s.push(n);let a=0;for(const t of s){const e=new Blob([JSON.stringify(this.buildBatch(t))],{type:"application/json"});if(!navigator.sendBeacon(this.config.endpoint,e))break;a+=t.length}this.log(`forceFlush(terminal): beaconed ${a}/${e.length} live events; backlog (${i.length-e.length}) persisted for next-load drain`)})}clear(){this.queue=[],this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null)}setEnabled(t){this.enabled=t}setConsentCheck(t){this.consentCheck=t}clearOffline(){this.offlineQueue=[],r.remove(this.OFFLINE_QUEUE_KEY)}log(...t){this.config.debug&&console.log("[Datalyr Queue]",...t)}destroy(){this.stopPeriodicFlush(),this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.queue.length>0&&this.moveToOfflineQueue()}}class O{constructor(t={}){this.privacyMode=t.privacyMode||"standard",this.enableFingerprinting=!1!==t.enableFingerprinting}collect(){return"strict"!==this.privacyMode&&this.enableFingerprinting?this.collectStandard():this.collectMinimal()}collectMinimal(){const t={timezone:this.getTimezone(),language:navigator.language||null,screen_bucket:this.getScreenBucket(),dnt:"1"===navigator.doNotTrack||!0===window.globalPrivacyControl||null,userAgent:navigator.userAgent||null};if("userAgentData"in navigator){const e=navigator.userAgentData;t.userAgentData={brands:e.brands||[],mobile:e.mobile||!1,platform:e.platform||null}}return t}collectStandard(){const t={};try{if(t.timezone=this.getTimezone(),t.language=navigator.language||null,t.screen_bucket=this.getScreenBucket(),t.dnt="1"===navigator.doNotTrack||!0===window.globalPrivacyControl||null,t.userAgent=navigator.userAgent||null,"userAgentData"in navigator){const e=navigator.userAgentData;t.userAgentData={brands:e.brands||[],mobile:e.mobile||!1,platform:e.platform||null}}}catch(t){console.warn("[Datalyr] Error collecting fingerprint:",t)}return t}getTimezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch(t){return null}}getScreenBucket(){try{if(!window.screen)return null;const t=100*Math.round(screen.width/100);return`${t}x${100*Math.round(screen.height/100)}`}catch(t){return null}}generateHash(e){return t(this,void 0,void 0,function*(){try{const t=Object.keys(e).sort().reduce((t,i)=>(t[i]=e[i],t),{}),i=JSON.stringify(t);if(window.crypto&&window.crypto.subtle){const t=(new TextEncoder).encode(i),e=yield crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}let s=0;for(let t=0;t<i.length;t++){s=(s<<5)-s+i.charCodeAt(t),s&=s}return Math.abs(s).toString(16)}catch(t){return""}})}}class L{constructor(t){this.scripts=[],this.loadedScripts=new Set,this.sessionLoadedScripts=new Set,this.pixels=null,this.initialized=!1,this.sandboxedIframes=[],this.iframeCleanupTimeouts=new Map,this.messageHandler=null,this.workspaceId=t.workspaceId,this.endpoint=t.endpoint||"https://ingest.datalyr.com",this.debug=t.debug||!1,this.getIdentity=t.getIdentity;const e=r.get("dl_session_scripts",[]);this.sessionLoadedScripts=new Set(e),this.messageHandler=t=>{if(t.data&&"datalyr_script_complete"===t.data.type){const e=t.data.scriptId;this.log("Received script completion signal:",e);const i=this.sandboxedIframes.find(t=>t.dataset.datalyrScript===e);i&&this.cleanupIframe(i)}},window.addEventListener("message",this.messageHandler)}init(){return t(this,void 0,void 0,function*(){if(!this.initialized)try{const t="undefined"!=typeof AbortController?new AbortController:null,e=t?setTimeout(()=>t.abort(),3e3):null;let i;try{i=yield fetch(`${this.endpoint}/container-scripts`,{method:"POST",headers:{"Content-Type":"application/json","X-Container-Version":"1.0"},body:JSON.stringify({workspaceId:this.workspaceId}),signal:t?t.signal:void 0})}finally{e&&clearTimeout(e)}if(!i.ok)throw new Error(`Failed to fetch container scripts: ${i.status}`);const s=yield i.json();this.scripts=s.scripts||[],this.pixels=s.pixels||null,this.remoteConfig=s.config&&"object"==typeof s.config?s.config:void 0,this.pixels&&(yield this.initializePixels()),this.loadScriptsByTrigger("page_load"),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{this.loadScriptsByTrigger("dom_ready")}):this.loadScriptsByTrigger("dom_ready"),window.addEventListener("load",()=>{this.loadScriptsByTrigger("window_load")}),this.initialized=!0,this.log("Container manager initialized with",this.scripts.length,"scripts")}catch(t){this.log("Error initializing container:",t)}})}getRemoteConfig(){return this.remoteConfig}loadScriptsByTrigger(t){this.scripts.filter(e=>e.enabled&&e.trigger===t&&this.shouldLoadScript(e)).forEach(t=>this.loadScript(t))}shouldLoadScript(t){return("once_per_page"!==t.frequency||!this.loadedScripts.has(t.id))&&(("once_per_session"!==t.frequency||!this.sessionLoadedScripts.has(t.id))&&(!(t.conditions&&t.conditions.length>0)||this.evaluateConditions(t.conditions)))}evaluateConditions(t){return t.every(t=>{try{const{type:e,operator:i,value:s}=t;switch(e){case"url_path":return this.evaluateStringCondition(window.location.pathname,i,s);case"url_host":return this.evaluateStringCondition(window.location.hostname,i,s);case"url_parameter":const e=new URLSearchParams(window.location.search);return this.evaluateStringCondition(e.get(t.parameter)||"",i,s);case"referrer":return this.evaluateStringCondition(document.referrer,i,s);case"device_type":const n=/Mobile|Android|iPhone|iPad/i.test(navigator.userAgent);return this.evaluateStringCondition(n?"mobile":"desktop",i,s);default:return!0}}catch(t){return!1}})}evaluateStringCondition(t,e,i){switch(e){case"equals":return t===i;case"not_equals":return t!==i;case"contains":return t.includes(i);case"not_contains":return!t.includes(i);case"starts_with":return t.startsWith(i);case"ends_with":return t.endsWith(i);case"matches_regex":try{return new RegExp(i).test(t)}catch(t){return!1}default:return!1}}loadScript(t){try{switch(t.type){case"inline":this.loadInlineScript(t);break;case"external":this.loadExternalScript(t);break;case"pixel":this.loadPixel(t)}this.loadedScripts.add(t.id),"once_per_session"===t.frequency&&(this.sessionLoadedScripts.add(t.id),r.set("dl_session_scripts",Array.from(this.sessionLoadedScripts))),this.log("Loaded script:",t.name)}catch(e){this.log("Error loading script:",t.name,e)}}loadInlineScript(t){const e=document.createElement("iframe");e.style.display="none",e.setAttribute("sandbox","allow-scripts"),e.dataset.datalyrScript=t.id,this.sandboxedIframes.push(e);const i=`\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset="UTF-8">\n </head>\n <body>\n <script>\n // User-provided script runs here in isolation\n try {\n ${t.content}\n } catch (error) {\n console.error('[Datalyr Container] Script execution error:', error);\n }\n\n // FIXED (ISSUE-02): Signal completion for cleanup\n // Scripts have 5 seconds to execute before iframe is removed\n setTimeout(function() {\n try {\n parent.postMessage({ type: 'datalyr_script_complete', scriptId: '${t.id}' }, '*');\n } catch (e) {\n // Ignore postMessage errors from sandbox\n }\n }, 5000);\n <\/script>\n </body>\n </html>\n `;document.body.appendChild(e),e.contentDocument&&(e.contentDocument.open(),e.contentDocument.write(i),e.contentDocument.close());const s=window.setTimeout(()=>{this.cleanupIframe(e)},3e4);this.iframeCleanupTimeouts.set(e,s),this.log("Loaded inline script in sandbox:",t.id)}cleanupIframe(t){try{const e=this.iframeCleanupTimeouts.get(t);e&&(clearTimeout(e),this.iframeCleanupTimeouts.delete(t));const i=this.sandboxedIframes.indexOf(t);i>-1&&this.sandboxedIframes.splice(i,1),t.parentNode&&(t.parentNode.removeChild(t),this.log("Cleaned up sandboxed iframe:",t.dataset.datalyrScript))}catch(t){this.log("Error cleaning up iframe:",t)}}cleanupAllIframes(){const t=[...this.sandboxedIframes];t.forEach(t=>this.cleanupIframe(t)),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.iframeCleanupTimeouts.forEach(t=>clearTimeout(t)),this.iframeCleanupTimeouts.clear(),this.log(`Cleaned up ${t.length} sandboxed iframes`)}loadExternalScript(t){var e;if(!this.isValidScriptUrl(t.content))return void this.log("Blocked invalid script URL:",t.content);if(!(null===(e=t.settings)||void 0===e?void 0:e.integrity))return void console.error(`[Datalyr Container] SECURITY: External script "${t.id}" blocked - missing SRI hash.\nAll external scripts MUST include an integrity hash to prevent CDN compromise attacks.\nGenerate SRI hash at: https://www.srihash.org/\nExample: { integrity: "sha384-..." }`);const i=document.createElement("script");i.src=t.content,i.dataset.datalyrScript=t.id,t.settings?(i.integrity=t.settings.integrity,i.crossOrigin=t.settings.crossorigin||"anonymous",!1!==t.settings.async&&(i.async=!0),t.settings.defer&&(i.defer=!0)):i.async=!0,document.head.appendChild(i)}loadPixel(t){const e=new Image;e.src=t.content,e.style.display="none",e.dataset.datalyrPixel=t.id,document.body.appendChild(e)}initializePixels(){return t(this,void 0,void 0,function*(){var t,e,i;this.pixels&&((null===(t=this.pixels.meta)||void 0===t?void 0:t.enabled)&&this.pixels.meta.pixel_id&&(yield this.initializeMetaPixel(this.pixels.meta)),(null===(e=this.pixels.google)||void 0===e?void 0:e.enabled)&&this.pixels.google.tag_id&&this.initializeGoogleTag(this.pixels.google),(null===(i=this.pixels.tiktok)||void 0===i?void 0:i.enabled)&&this.pixels.tiktok.pixel_id&&this.initializeTikTokPixel(this.pixels.tiktok))})}initializeMetaPixel(e){return t(this,void 0,void 0,function*(){var t,i,s,n,o,r,a;try{i=window,s=document,n="script",i.fbq||(o=i.fbq=function(){o.callMethod?o.callMethod.apply(o,arguments):o.queue.push(arguments)},i._fbq||(i._fbq=o),o.push=o,o.loaded=!0,o.version="2.0",o.queue=[],(r=s.createElement(n)).async=!0,r.src="https://connect.facebook.net/en_US/fbevents.js",(a=s.getElementsByTagName(n)[0]).parentNode.insertBefore(r,a));const l={},h=null===(t=this.getIdentity)||void 0===t?void 0:t.call(this);if(null==h?void 0:h.externalId){const t=yield c(String(h.externalId));t&&(l.external_id=t)}if(null==h?void 0:h.email){const t=yield c(String(h.email).toLowerCase().trim());t&&(l.em=t)}Object.keys(l).length>0?(window.fbq("init",e.pixel_id,l),this.log("Meta Pixel initialized with advanced matching:",e.pixel_id,Object.keys(l))):(window.fbq("init",e.pixel_id),this.log("Meta Pixel initialized (no advanced matching):",e.pixel_id))}catch(t){this.log("Error initializing Meta Pixel:",t)}})}initializeGoogleTag(t){try{const e=document.createElement("script");function i(...t){window.dataLayer.push(t)}e.async=!0,e.src=`https://www.googletagmanager.com/gtag/js?id=${t.tag_id}`,document.head.appendChild(e),window.dataLayer=window.dataLayer||[],window.gtag=i,i("js",new Date),i("config",t.tag_id,{allow_enhanced_conversions:!1!==t.enhanced_conversions}),this.log("Google Tag initialized:",t.tag_id)}catch(s){this.log("Error initializing Google Tag:",s)}}initializeTikTokPixel(t){try{!function(t,e,i){t.TiktokAnalyticsObject=i;var s=t[i]=t[i]||[];s.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],s.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var n=0;n<s.methods.length;n++)s.setAndDefer(s,s.methods[n]);s.instance=function(t){for(var e=s._i[t]||[],i=0;i<s.methods.length;i++)s.setAndDefer(e,s.methods[i]);return e},s.load=function(t,e){var n;s._i=s._i||{},s._i[t]=[],s._o=s._o||{},s._o[t]=e||{};var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src="https://analytics.tiktok.com/i18n/pixel/events.js?sdkid="+t+"&lib="+i;var r=document.getElementsByTagName("script")[0];null===(n=r.parentNode)||void 0===n||n.insertBefore(o,r)}}(window,document,"ttq"),window.ttq.load(t.pixel_id),window.ttq.page(),this.log("TikTok Pixel initialized:",t.pixel_id)}catch(t){this.log("Error initializing TikTok Pixel:",t)}}hasMetaPixel(){var t,e;return!(!(null===(e=null===(t=this.pixels)||void 0===t?void 0:t.meta)||void 0===e?void 0:e.enabled)||!window.fbq)}trackToPixels(t,e={},i){var s,n,o,r,a,c,l,h,d,u;if(t.startsWith("$"))return;const f=this.sanitizeEventName(t),p=this.sanitizeProperties(e);if((null===(n=null===(s=this.pixels)||void 0===s?void 0:s.meta)||void 0===n?void 0:n.enabled)&&window.fbq)try{const e={page_view:"PageView",pageview:"PageView",view_content:"ViewContent",product_viewed:"ViewContent",view_item:"ViewContent",add_to_cart:"AddToCart",product_added:"AddToCart",add_to_wishlist:"AddToWishlist",initiate_checkout:"InitiateCheckout",begin_checkout:"InitiateCheckout",checkout_started:"InitiateCheckout",add_payment_info:"AddPaymentInfo",purchase:"Purchase",order_completed:"Purchase",order_paid:"Purchase",lead:"Lead",complete_registration:"CompleteRegistration",sign_up:"CompleteRegistration",signup:"CompleteRegistration",search:"Search",subscribe:"Subscribe",subscription_created:"Subscribe",start_trial:"StartTrial",trial_started:"StartTrial",contact:"Contact",schedule:"Schedule"},s=null===(r=null===(o=this.pixels)||void 0===o?void 0:o.meta)||void 0===r?void 0:r.event_mappings,n=(null==s?void 0:s[t])||e[String(t).toLowerCase()]||f;i?window.fbq("track",n,p,{eventID:i}):window.fbq("track",n,p)}catch(t){this.log("Error tracking Meta Pixel event:",t)}if((null===(c=null===(a=this.pixels)||void 0===a?void 0:a.google)||void 0===c?void 0:c.enabled)&&window.gtag)try{window.gtag("event",f,p)}catch(t){this.log("Error tracking Google Tag event:",t)}if((null===(h=null===(l=this.pixels)||void 0===l?void 0:l.tiktok)||void 0===h?void 0:h.enabled)&&window.ttq)try{const e={view_content:"ViewContent",product_viewed:"ViewContent",view_item:"ViewContent",search:"Search",add_to_wishlist:"AddToWishlist",add_to_cart:"AddToCart",product_added:"AddToCart",initiate_checkout:"InitiateCheckout",begin_checkout:"InitiateCheckout",checkout_started:"InitiateCheckout",add_payment_info:"AddPaymentInfo",purchase:"CompletePayment",order_completed:"CompletePayment",order_paid:"CompletePayment",place_an_order:"PlaceAnOrder",contact:"Contact",download:"Download",lead:"SubmitForm",submit_form:"SubmitForm",complete_registration:"CompleteRegistration",sign_up:"CompleteRegistration",signup:"CompleteRegistration",subscribe:"Subscribe",subscription_created:"Subscribe"},i=null===(u=null===(d=this.pixels)||void 0===d?void 0:d.tiktok)||void 0===u?void 0:u.event_mappings,s=(null==i?void 0:i[t])||e[String(t).toLowerCase()]||f;window.ttq.track(s,p)}catch(t){this.log("Error tracking TikTok Pixel event:",t)}}triggerCustomScript(t){const e=this.scripts.find(e=>e.id===t&&"custom"===e.trigger);e&&this.shouldLoadScript(e)&&this.loadScript(e)}getLoadedScripts(){return Array.from(this.loadedScripts)}isValidScriptUrl(t){try{const e=new URL(t);return!("https:"!==e.protocol&&!e.hostname.includes("localhost"))&&!["data:","javascript:","file:"].includes(e.protocol)}catch(t){return!1}}sanitizeEventName(t){return"string"!=typeof t?"unknown_event":t.replace(/[^a-zA-Z0-9_$ ]/g,"").substring(0,100)}sanitizeProperties(t){if(null==t)return{};if("object"!=typeof t)return this.sanitizeValue(t);if(Array.isArray(t))return t.map(t=>this.sanitizeValue(t));const e={};for(const[i,s]of Object.entries(t)){const t=i.replace(/[^a-zA-Z0-9_]/g,"").substring(0,100);t&&(e[t]=this.sanitizeValue(s))}return e}sanitizeValue(t){return null==t?t:"string"==typeof t?t.replace(/<script[^>]*>.*?<\/script>/gi,"").replace(/<[^>]+>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").substring(0,1e3):"number"==typeof t||"boolean"==typeof t?t:"object"==typeof t?this.sanitizeProperties(t):String(t).substring(0,1e3)}log(...t){this.debug&&console.log("[Datalyr Container]",...t)}}class F{constructor(t={}){this.formListeners=[],this.lastIdentifyTime=0,this.RATE_LIMIT_MS=5e3,this.destroyed=!1,this.config={enabled:!1!==t.enabled,captureFromForms:!1!==t.captureFromForms,captureFromAPI:!0===t.captureFromAPI,captureFromShopify:!1!==t.captureFromShopify,trustedDomains:t.trustedDomains||[],debug:t.debug||!1}}initialize(e){return t(this,void 0,void 0,function*(){if(!this.config.enabled)return void this.log("Auto-identify disabled");this.identifyCallback=e;const t=yield r.getEncrypted("dl_auto_identified_email");if(t){const e=r.get("dl_auto_identified_email");if("string"==typeof e&&e.includes("@"))try{yield r.setEncrypted("dl_auto_identified_email",t),this.log("Migrated legacy plaintext auto-identified email to encrypted storage")}catch(t){this.log("Failed to migrate legacy auto-identified email:",t)}return void this.log("User already auto-identified")}this.config.captureFromForms&&this.setupFormMonitoring(),this.config.captureFromAPI&&(this.setupFetchInterception(),this.setupXHRInterception()),this.config.captureFromShopify&&this.setupShopifyMonitoring(),this.log("Auto-identify initialized")})}setupFormMonitoring(){this.scanForEmailForms(),this.formObserver=new MutationObserver(()=>{this.scanForEmailForms()}),this.formObserver.observe(document.body,{childList:!0,subtree:!0}),this.log("Form monitoring active")}findVisitorEmailInput(t){const e=Array.from(t.querySelectorAll('input[type="email"], input[name*="email" i], input[id*="email" i], input[autocomplete="email"]')).filter(t=>!this.isThirdPartyEmailField(t));if(0===e.length)return null;if(1===e.length)return e[0];const i=e.filter(t=>"email"===(t.getAttribute("autocomplete")||"").toLowerCase());return 1===i.length?i[0]:(this.log("Multiple email inputs in form; skipping auto-identify (ambiguous)"),null)}isThirdPartyEmailField(t){const e=[t.name,t.id,t.getAttribute("autocomplete"),t.getAttribute("aria-label"),t.placeholder].filter(Boolean).join(" ");return F.THIRD_PARTY_EMAIL_FIELD.test(e)}scanForEmailForms(){if(this.destroyed)return;document.querySelectorAll("form").forEach(t=>{if(this.formListeners.some(e=>e.element===t))return;if(this.findVisitorEmailInput(t)){const e=e=>this.handleFormSubmit(e,t);t.addEventListener("submit",e),this.formListeners.push({element:t,handler:e}),this.log("Monitoring form:",t)}})}handleFormSubmit(t,e){try{const t=this.findVisitorEmailInput(e);if(!t)return;const i=t.value.trim();this.isValidEmail(i)&&(this.log("Email captured from form:",i),this.triggerIdentify(i,"form"))}catch(t){this.log("Error handling form submit:",t)}}setupFetchInterception(){if("function"!=typeof window.fetch)return;this.originalFetch=window.fetch;const e=this;window.fetch=function(i,s){return t(this,void 0,void 0,function*(){const n="string"==typeof i?i:i instanceof URL?i.href:i.url;if(!e.isTrustedDomain(n))return e.originalFetch.call(window,i,s);try{(null==s?void 0:s.body)&&e.extractEmailFromData(s.body,"api-request");const n=e.originalFetch.call(window,i,s);return n.then(i=>t(this,void 0,void 0,function*(){var t;if(i.ok&&(null===(t=i.headers.get("content-type"))||void 0===t?void 0:t.includes("application/json")))try{const t=i.clone(),s=yield t.json();e.extractEmailFromData(s,"api-response")}catch(t){}})).catch(()=>{}),n}catch(t){return e.log("Error intercepting fetch:",t),e.originalFetch.call(window,i,s)}})},this.log("Fetch interception active")}setupXHRInterception(){if("undefined"==typeof XMLHttpRequest)return;const t=this;this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send,XMLHttpRequest.prototype.open=function(e,i,...s){return this._datalyrUrl="string"==typeof i?i:i.href,t.originalXHROpen.apply(this,[e,i,...s])},XMLHttpRequest.prototype.send=function(e){const i=this._datalyrUrl;return i&&t.isTrustedDomain(i)&&(e&&t.extractEmailFromData(e,"api-request"),this.addEventListener("load",function(){if(this.status>=200&&this.status<300)try{const e=this.getResponseHeader("content-type");if(null==e?void 0:e.includes("application/json")){const e=JSON.parse(this.responseText);t.extractEmailFromData(e,"api-response")}}catch(t){}})),t.originalXHRSend.call(this,e)},this.log("XHR interception active")}setupShopifyMonitoring(){if(!this.isShopify())return;this.log("Shopify detected, setting up monitoring"),this.checkShopifyCustomer();let t=0;this.shopifyCheckInterval=setInterval(()=>{t++,this.checkShopifyCustomer(),t>=12&&this.shopifyCheckInterval&&(clearInterval(this.shopifyCheckInterval),this.shopifyCheckInterval=void 0,this.log("Shopify monitoring stopped after max checks (no login detected)"))},1e4),this.log("Shopify monitoring active")}isShopify(){return!!(window.Shopify||document.querySelector('meta[name="shopify-checkout-api-token"]')||window.location.hostname.includes(".myshopify.com"))}checkShopifyCustomer(){return t(this,void 0,void 0,function*(){var t;try{const e=yield fetch("/account.json",{credentials:"same-origin"});if(e.ok){const i=yield e.json();(null===(t=null==i?void 0:i.customer)||void 0===t?void 0:t.email)&&(this.log("Email captured from Shopify:",i.customer.email),this.triggerIdentify(i.customer.email,"shopify"),this.shopifyCheckInterval&&(clearInterval(this.shopifyCheckInterval),this.shopifyCheckInterval=void 0))}}catch(t){this.log("Shopify customer check failed:",t)}})}extractEmailFromData(t,e){try{let i=[];if("string"==typeof t)try{const e=JSON.parse(t);i=this.findEmailsInObject(e)}catch(e){const s=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,n=t.match(s);n&&(i=n)}else t instanceof FormData?t.forEach(t=>{"string"==typeof t&&this.isValidEmail(t)&&i.push(t)}):"object"==typeof t&&null!==t&&(i=this.findEmailsInObject(t));if(i.length>0){const t=i[0];this.log(`Email found in ${e}:`,t),this.triggerIdentify(t,"api")}}catch(t){this.log("Error extracting email from data:",t)}}findEmailsInObject(t,e=0){if(e>5)return[];const i=[];for(const s in t){if(!t.hasOwnProperty(s))continue;const n=t[s];/email/i.test(s)&&"string"==typeof n&&this.isValidEmail(n)?i.push(n):"object"==typeof n&&null!==n&&i.push(...this.findEmailsInObject(n,e+1))}return i}isTrustedDomain(t){try{const e=new URL(t,window.location.origin);return e.origin===window.location.origin||0!==this.config.trustedDomains.length&&this.config.trustedDomains.some(t=>e.hostname===t||e.hostname.endsWith(`.${t}`))}catch(t){return!1}}isValidEmail(t){if(!t||"string"!=typeof t)return!1;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t))return!1;return![/test@/i,/example@/i,/demo@/i,/fake@/i,/@test\./i,/@example\./i].some(e=>e.test(t))}triggerIdentify(e,i){return t(this,void 0,void 0,function*(){if(this.destroyed)return;const t=Date.now();if(t-this.lastIdentifyTime<this.RATE_LIMIT_MS)return void this.log("Rate limited, skipping identify");this.lastIdentifyTime=t;if((yield r.getEncrypted("dl_auto_identified_email"))!==e){if(!this.destroyed){try{yield r.setEncrypted("dl_auto_identified_email",e)}catch(t){this.log("Failed to persist auto-identified email:",t)}this.identifyCallback&&(this.log(`Auto-identifying user: ${e} (source: ${i})`),this.identifyCallback(e,i))}}else this.log("Already identified with this email")})}destroy(){this.destroyed=!0,this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=void 0),this.originalXHROpen&&(XMLHttpRequest.prototype.open=this.originalXHROpen,this.originalXHROpen=void 0),this.originalXHRSend&&(XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHRSend=void 0),this.formObserver&&(this.formObserver.disconnect(),this.formObserver=void 0),this.formListeners.forEach(({element:t,handler:e})=>{t.removeEventListener("submit",e)}),this.formListeners=[],this.shopifyCheckInterval&&(clearInterval(this.shopifyCheckInterval),this.shopifyCheckInterval=void 0),this.log("Auto-identify destroyed")}log(...t){this.config.debug&&console.log("[Datalyr Auto-Identify]",...t)}}F.THIRD_PARTY_EMAIL_FIELD=/(recipient|friend|gift|refer|invite|colleague|coworker|share|to[-_]?email|email[-_]?to|second(ary)?[-_]?email)/i;const z=["autoIdentify","autoIdentifyForms","autoIdentifyAPI","autoIdentifyShopify","shopifyCartAttributes","checkoutChampDomains","respectGlobalPrivacyControl","respectDoNotTrack","privacyMode"];const M="undefined"!=typeof window&&window.datalyr||new class{constructor(){this.explicitConfigKeys=new Set,this.superProperties={},this.userProperties={},this.optedOut=!1,this.consent=null,this.initialized=!1,this.errors=[],this.MAX_ERRORS=50,this.lastSpaPath=null,this.initializationPromise=null}init(t){if(this.initialized)return void console.warn("[Datalyr] SDK already initialized");if(!t.workspaceId)throw new Error("[Datalyr] workspaceId is required");this.explicitConfigKeys=new Set(Object.keys(t)),this.config=Object.assign({endpoint:"https://ingest.datalyr.com",debug:!1,batchSize:10,flushInterval:5e3,flushAt:10,criticalEvents:void 0,highPriorityEvents:void 0,sessionTimeout:36e5,trackSessions:!0,attributionWindow:7776e6,trackedParams:[],respectDoNotTrack:!1,respectGlobalPrivacyControl:!0,privacyMode:"standard",cookieDomain:"auto",cookieExpires:365,secureCookie:"auto",sameSite:"Lax",cookiePrefix:"__dl_",enablePerformanceTracking:!0,enableFingerprinting:!0,maxRetries:5,retryDelay:1e3,maxOfflineQueueSize:100,trackSPA:!0,trackPageViews:!0,fallbackEndpoints:[],plugins:[]},t),"shopify"===this.config.platform&&void 0===this.config.shopifyCartAttributes&&(this.config.shopifyCartAttributes=!0),this.cookies=new s({domain:this.config.cookieDomain,maxAge:this.config.cookieExpires,sameSite:this.config.sameSite,secure:this.config.secureCookie}),r.migrateFromLegacyPrefix(),this.optedOut="true"===this.cookies.get("__dl_opt_out"),this.consent=r.get("dl_consent",null),"checkoutchamp"===this.config.platform&&this.restoreFromURL(),this.identity=new I({persistNewId:this.shouldTrack()}),this.session=new C(this.config.sessionTimeout),this.attribution=new E({attributionWindow:this.config.attributionWindow,trackedParams:this.config.trackedParams,marketingAllowed:()=>this.consentAllowsMarketing()}),this.queue=new P(this.config),this.fingerprint=new O({privacyMode:this.config.privacyMode,enableFingerprinting:this.config.enableFingerprinting});const e=this.session.getSessionId();if(this.identity.setSessionId(e),this.queue.setEnabled(this.shouldTrack()),this.queue.setConsentCheck(()=>this.shouldTrack()),this.initializeAsync(),this.setupUnloadHandler(),this.setupShopifyConsentListener(),this.config.plugins)for(const t of this.config.plugins)try{t.initialize(this),this.log(`Plugin initialized: ${t.name}`)}catch(e){console.warn(`[Datalyr] Plugin '${t.name}' failed to initialize:`,e),this.trackError(e,{plugin:t.name})}this.initialized=!0,this.log("SDK initialized")}initializeAsync(){return t(this,void 0,void 0,function*(){return this.initializationPromise||(this.initializationPromise=(()=>t(this,void 0,void 0,function*(){var t,i;try{if(this.shouldTrack())try{this.attribution.getAttributionData()}catch(t){this.log("Eager attribution capture failed:",t)}try{const t=this.identity.getAnonymousId();yield e.initialize(this.config.workspaceId,t),this.userProperties=yield r.getEncrypted("dl_user_traits",{}),this.log("Encryption initialized, user properties loaded")}catch(t){console.warn("[Datalyr] Encryption unavailable (non-secure context?); continuing WITHOUT PII-at-rest encryption:",t),this.userProperties=r.get("dl_user_traits",{})}this.config.trackSPA&&this.setupSPATracking();const s="strict"===this.config.privacyMode;!1!==this.config.enableContainer&&this.shouldTrack()&&!s&&this.consentAllowsMarketing()&&(this.container=new L({workspaceId:this.config.workspaceId,endpoint:this.config.endpoint,debug:this.config.debug,getIdentity:()=>{var t,e;return{externalId:null===(t=this.identity)||void 0===t?void 0:t.getDistinctId(),email:null===(e=this.userProperties)||void 0===e?void 0:e.email}}}),yield this.container.init().catch(t=>{this.log("Container initialization failed:",t)}),"checkoutchamp"===this.config.platform&&this.fireCheckoutChampPurchasePixel()),function(t,e,i){if(!e)return;const s=t;for(const t of z){const n=e[t];null!=n&&((null==i?void 0:i.has(t))||(s[t]=n))}}(this.config,null===(t=this.container)||void 0===t?void 0:t.getRemoteConfig(),this.explicitConfigKeys),"strict"===this.config.privacyMode&&(this.config.autoIdentify=!1);("checkoutchamp"===this.config.platform||Array.isArray(this.config.checkoutChampDomains)&&this.config.checkoutChampDomains.length>0)&&void 0===this.config.autoIdentify&&(this.config.autoIdentify=!0),!0===this.config.autoIdentify&&this.shouldTrack()&&!1!==this.shopifyMarketingConsent()&&(this.autoIdentify=new F({enabled:!0,captureFromForms:this.config.autoIdentifyForms,captureFromAPI:this.config.autoIdentifyAPI,captureFromShopify:this.config.autoIdentifyShopify,trustedDomains:this.config.autoIdentifyTrustedDomains,debug:this.config.debug}),this.autoIdentify.initialize((t,e)=>{this.log(`Auto-identified user: ${t} from ${e}`),this.track("$auto_identify",{email:t,source:e,timestamp:Date.now()}),this.identify(t,{email:t})})),!0===this.config.shopifyCartAttributes&&this.shouldTrack()&&!1!==this.shopifyMarketingConsent()&&this.syncShopifyCartAttributes().catch(t=>{this.log("Shopify cart attribute sync failed:",t)}),Array.isArray(this.config.checkoutChampDomains)&&this.config.checkoutChampDomains.length>0&&this.shouldTrack()&&this.syncOutboundLinkParams(this.config.checkoutChampDomains),!1!==this.config.stripePaymentLinks&&this.shouldTrack()&&this.syncStripePaymentLinks(null!==(i=this.config.stripeLinkDomains)&&void 0!==i?i:[]),this.config.trackPageViews&&this.page(),this.log("Async initialization complete")}catch(t){console.error("[Datalyr] Async initialization failed:",t),this.userProperties=r.get("dl_user_traits",{})}}))()),this.initializationPromise})}ready(){return t(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("[Datalyr] SDK not initialized. Call init() first.");return this.initializationPromise||Promise.resolve()})}track(t,e={}){if(this.initialized){if(this.shouldTrack())try{this.session.updateActivity(t);const i=l(),s=this.createEventPayload(t,e,i);if(this.queue.enqueue(s),this.container&&this.container.trackToPixels(t,e,i),this.config.plugins)for(const i of this.config.plugins)if(i.track)try{i.track(t,e)}catch(e){this.trackError(e,{plugin:i.name,event:t})}this.log("Event tracked:",t)}catch(e){this.trackError(e,{event:t})}}else console.warn("[Datalyr] SDK not initialized. Call init() first.")}trackAppDownloadClick(e){return t(this,void 0,void 0,function*(){if(this.initialized){if(this.shouldTrack())if(this.track("$app_download_click",{target_platform:e.targetPlatform,app_store_url:e.appStoreUrl}),yield this.queue.forceFlush(),"android"===e.targetPlatform&&e.appStoreUrl.includes("play.google.com")){const t=this.attribution.getLastTouch(),i=new URLSearchParams;(null==t?void 0:t.clickId)&&i.set("dl_click_id",t.clickId),(null==t?void 0:t.clickIdType)&&i.set("dl_click_id_type",t.clickIdType),(null==t?void 0:t.source)&&i.set("utm_source",t.source),(null==t?void 0:t.medium)&&i.set("utm_medium",t.medium),(null==t?void 0:t.campaign)&&i.set("utm_campaign",t.campaign),(null==t?void 0:t.content)&&i.set("utm_content",t.content),(null==t?void 0:t.term)&&i.set("utm_term",t.term);try{const t=new URL(e.appStoreUrl);t.searchParams.set("referrer",i.toString()),window.location.href=t.toString()}catch(t){window.location.href=e.appStoreUrl}}else window.location.href=e.appStoreUrl}else console.warn("[Datalyr] SDK not initialized. Call init() first.")})}identify(t,e={}){if(this.initialized){if(this.shouldTrack())if(t)try{const i=this.identity.getUserId();i&&i!==t&&this.reset();const s=this.identity.identify(t,e);if(this.userProperties=Object.assign(Object.assign({},this.userProperties),e),r.setEncrypted("dl_user_traits",this.userProperties).catch(t=>{console.error("[Datalyr] Failed to encrypt user traits - NOT storing unencrypted PII:",t),console.error("[Datalyr] User traits will only persist in memory until page reload")}),this.track("$identify",Object.assign(Object.assign({},s),{traits:e})),this.config.plugins)for(const i of this.config.plugins)if(i.identify)try{i.identify(t,e)}catch(t){this.trackError(t,{plugin:i.name})}this.log("User identified:",t)}catch(e){this.trackError(e,{userId:t})}else console.warn("[Datalyr] identify() called without userId")}else console.warn("[Datalyr] SDK not initialized. Call init() first.")}page(t={}){if(!this.initialized)return void console.warn("[Datalyr] SDK not initialized. Call init() first.");if(!this.shouldTrack())return;const e=this.session.getSessionId(),i=this.attribution.getJourney(),s=i.length?i[i.length-1]:null;s&&s.sessionId===e||this.attribution.addTouchpoint(e,this.attribution.captureAttribution());const n=Object.assign({title:document.title,url:v(window.location.href),path:window.location.pathname,search:v(window.location.search),referrer:v(document.referrer)},t),o=function(){const t=document.referrer;if(!t)return{};try{const e=new URL(t);return{referrer:v(t),referrer_host:e.hostname,referrer_path:e.pathname,referrer_search:v(e.search),referrer_source:S(e.hostname)}}catch(e){return{referrer:v(t)}}}();if(Object.assign(n,o),this.config.enablePerformanceTracking){const t=this.getPerformanceMetrics();t&&(n.performance=t)}if(this.track("pageview",n),this.config.plugins)for(const t of this.config.plugins)if(t.page)try{t.page(n)}catch(e){this.trackError(e,{plugin:t.name})}}screen(t,e={}){this.initialized?this.shouldTrack()&&this.track("pageview",Object.assign({screen:t},e)):console.warn("[Datalyr] SDK not initialized. Call init() first.")}group(t,e={}){this.initialized?this.shouldTrack()&&this.track("$group",{group_id:t,traits:e}):console.warn("[Datalyr] SDK not initialized. Call init() first.")}alias(t,e){if(!this.initialized)return void console.warn("[Datalyr] SDK not initialized. Call init() first.");if(!t)return void console.warn("[Datalyr] alias() requires a non-empty userId");if(!this.shouldTrack())return;if(e&&e!==this.identity.getAnonymousId())return void console.warn("[Datalyr] alias() only accepts the current anonymous ID as previousId");const i=this.identity.getUserId();i&&i!==t&&this.reset();const s=this.identity.alias(t,e);this.track("$alias",s)}reset(){this.initialized?(this.identity.reset(),this.userProperties={},this.superProperties={},r.remove("dl_user_traits"),r.remove("dl_auto_identified_email"),r.remove("dl_journey"),r.remove("dl_first_touch"),r.remove("dl_last_touch"),this.session.createNewSession(),this.log("User reset")):console.warn("[Datalyr] SDK not initialized. Call init() first.")}getAnonymousId(){return this.identity.getAnonymousId()}getVisitorId(){return this.identity.getAnonymousId()}getStripeMetadata(){const t=this.identity.getAnonymousId();return{client_reference_id:t,metadata:{visitor_id:t}}}getWhopCheckoutMetadata(){return{visitor_id:this.identity.getAnonymousId()}}getUserId(){return this.identity.getUserId()}getDistinctId(){return this.identity.getDistinctId()}getSessionId(){return this.session.getSessionId()}startNewSession(){const t=this.session.createNewSession();return this.identity.setSessionId(t),t}getSessionData(){return this.session.getSessionData()}getAttribution(){return this.attribution.captureAttribution()}getJourney(){return this.attribution.getJourney()}setAttribution(t){const e=this.attribution.captureAttribution(),i=Object.assign(Object.assign({},e),t);this.attribution.storeLastTouch(i),this.attribution.storeFirstTouch(i),this.session.storeAttribution(i)}disposeMarketingLinkDecorators(){var t,e;try{null===(t=this.stripeLinksDisposer)||void 0===t||t.call(this)}catch(t){}this.stripeLinksDisposer=void 0;try{null===(e=this.outboundDisposer)||void 0===e||e.call(this)}catch(t){}this.outboundDisposer=void 0}optOut(){var t;this.initialized?(this.optedOut=!0,this.cookies.set("__dl_opt_out","true",this.config.cookieExpires),this.queue.setEnabled(!1),this.queue.clear(),this.queue.clearOffline(),null===(t=this.autoIdentify)||void 0===t||t.destroy(),this.autoIdentify=void 0,this.container&&(this.container.cleanupAllIframes(),this.container=void 0),this.disposeMarketingLinkDecorators(),this.userProperties={},r.remove("dl_user_traits"),r.remove("dl_auto_identified_email"),r.remove("dl_journey"),this.log("User opted out")):console.warn("[Datalyr] SDK not initialized. Call init() first.")}optIn(){this.initialized?(this.optedOut=!1,this.cookies.set("__dl_opt_out","false",this.config.cookieExpires),this.queue.setEnabled(this.shouldTrack()),this.shouldTrack()&&this.identity.enablePersistence(),this.log("User opted in")):console.warn("[Datalyr] SDK not initialized. Call init() first.")}isOptedOut(){return this.optedOut}setConsent(t){var e;if(this.consent=t,r.set("dl_consent",t),!this.initialized)return;const i=this.shouldTrack();this.queue.setEnabled(i),i?this.identity.enablePersistence():(this.queue.clear(),this.queue.clearOffline(),null===(e=this.autoIdentify)||void 0===e||e.destroy(),this.autoIdentify=void 0,this.userProperties={},r.remove("dl_user_traits"),r.remove("dl_auto_identified_email"),r.remove("dl_journey")),!this.consentAllowsMarketing()&&this.container&&(this.container.cleanupAllIframes(),this.container=void 0),this.consentAllowsMarketing()||this.disposeMarketingLinkDecorators(),this.log("Consent updated:",t)}flush(){return t(this,void 0,void 0,function*(){yield this.queue.flush()})}setSuperProperties(t){this.superProperties=Object.assign(Object.assign({},this.superProperties),t),this.log("Super properties set:",t)}unsetSuperProperty(t){delete this.superProperties[t],this.log("Super property unset:",t)}getSuperProperties(){return Object.assign({},this.superProperties)}syncShopifyCartAttributes(){return t(this,void 0,void 0,function*(){if("undefined"==typeof window||"undefined"==typeof document)return;if(!!!(window.Shopify||document.querySelector('meta[name="shopify-checkout-api-token"]')||window.location.hostname.includes(".myshopify.com")))return;const t=this.attribution.getAttributionData(),e="fbclid"===t.clickIdType?t.clickId:null,i={},s=this.identity.getAnonymousId(),n=this.cookies.get("_fbc")||t._fbc,o=this.cookies.get("_fbp")||t._fbp,r=this.cookies.get("_dl_fbclid_at");if(s&&(i._datalyr_visitor_id=s),n&&(i._datalyr_fbc=String(n)),o&&(i._datalyr_fbp=String(o)),e&&(i._datalyr_fbclid=String(e)),r&&(i._datalyr_fbclid_at=String(r)),0!==Object.keys(i).length)try{yield fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({attributes:i})}),this.log("Shopify cart attributes stamped:",Object.keys(i))}catch(t){this.log("Shopify /cart/update.js failed:",t)}})}restoreFromURL(){var t;if("undefined"!=typeof window&&"undefined"!=typeof document)try{const e=new URLSearchParams(window.location.search);let i=!1;for(const t of["_dl_vid","_dl_fbc","_dl_fbp","_dl_fbclid","_dl_fbclid_at","_dl_gclid","_dl_gclid_at"])e.has(t)&&(e.delete(t),i=!0);if(i&&"function"==typeof(null===(t=window.history)||void 0===t?void 0:t.replaceState)){const t=e.toString(),i=window.location.pathname+(t?"?"+t:"")+window.location.hash;window.history.replaceState(window.history.state,"",i)}}catch(t){this.log("restoreFromURL failed:",t)}}fireCheckoutChampPurchasePixel(){var t;if("undefined"!=typeof window)try{if(!this.container)return;const e=null===(t=window.sessionStorage)||void 0===t?void 0:t.getItem("orderData");if(!e)return;const i=JSON.parse(e)||{},s=i.orderId;if(!s)return;if(!this.container.hasMetaPixel())return void this.log("CC Purchase Pixel: Meta pixel not ready; will retry on next funnel page");const n=`__dl_cc_purchase_${s}`;if(window.sessionStorage.getItem(n))return;window.sessionStorage.setItem(n,"1");const o=`checkoutchamp_purchase_${s}`,r=Number(i.totalAmount),a={order_id:String(s),content_type:"product"};Number.isFinite(r)&&(a.value=r);const c=i.currencyCode||i.currency;c&&(a.currency=String(c)),i.productId&&(a.content_ids=[String(i.productId)]),this.container.trackToPixels("purchase",a,o),this.log("Checkout Champ Purchase Pixel co-fired (CAPI dedup):",{eventId:o,value:a.value,currency:a.currency})}catch(t){this.log("fireCheckoutChampPurchasePixel failed:",t)}}syncOutboundLinkParams(t){this.log("Checkout Champ outbound identity bridge disabled (signed token required)",t)}syncStripePaymentLinks(t){if("undefined"==typeof window||"undefined"==typeof document)return;const e=new Set(["buy.stripe.com"]);for(const i of t){const t=String(i).trim().toLowerCase();t&&e.add(t)}const i=t=>{try{const i=new URL(t,window.location.href).hostname.toLowerCase();return e.has(i)}catch(t){return!1}},s=/^[A-Za-z0-9_-]{1,200}$/,n=()=>{const t=this.identity.getAnonymousId();return t&&s.test(t)?t:null},o=()=>{var t;if("strict"===this.config.privacyMode)return null;const e=null===(t=this.userProperties)||void 0===t?void 0:t.email;return"string"==typeof e&&e?e:null},r=t=>{if(t.href&&i(t.href))try{const e=new URL(t.href,window.location.href);let i=!1;const s=n();s&&!e.searchParams.get("client_reference_id")&&(e.searchParams.set("client_reference_id",s),i=!0);const r=o();!r||e.searchParams.get("prefilled_email")||e.searchParams.get("locked_prefilled_email")||(e.searchParams.set("prefilled_email",r),i=!0),i&&(t.href=e.toString())}catch(t){}},a=()=>{document.querySelectorAll("a[href]").forEach(t=>r(t)),(()=>{const t=n();t&&document.querySelectorAll("stripe-pricing-table, stripe-buy-button").forEach(e=>{e.getAttribute("client-reference-id")||e.setAttribute("client-reference-id",t)})})()},c=t=>{var e,s;const n=null===(e=t.target)||void 0===e?void 0:e.closest("a[href]");if(!n)return;const o=n;if(i(o.href)){r(o);try{null===(s=this.queue)||void 0===s||s.flush()}catch(t){}}};a(),document.addEventListener("click",c,!0);try{let t=null;const e=new MutationObserver(()=>{null==t&&(t=setTimeout(()=>{t=null,a()},150))});e.observe(document.documentElement,{childList:!0,subtree:!0}),this.stripeLinksDisposer=()=>{try{e.disconnect()}catch(t){}null!=t&&(clearTimeout(t),t=null),document.removeEventListener("click",c,!0)},window.addEventListener("pagehide",()=>{var t;return null===(t=this.stripeLinksDisposer)||void 0===t?void 0:t.call(this)},{once:!0})}catch(t){this.log("MutationObserver setup failed (Stripe Payment Link sync):",t)}this.log("Stripe Payment Link auto-decoration active for:",Array.from(e))}createEventPayload(t,e,i){var s;this.identity.setSessionId(this.session.getSessionId());const n=p(e),o=_({},this.superProperties,n),r=(t,e)=>{for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&!Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=e[i])};r(o,this.attribution.getAttributionData());const a=this.session.getMetrics();if(Object.assign(o,a),this.config.enableFingerprinting){const t=this.fingerprint.collect();Object.assign(o,{device_fingerprint:t})}r(o,{url:v(window.location.href),path:window.location.pathname,referrer:v(document.referrer),title:document.title,screen_width:screen.width,screen_height:screen.height,viewport_width:window.innerWidth,viewport_height:window.innerHeight});const c=Object.assign({},null!==(s=this.consent)&&void 0!==s?s:{}),h=this.shopifyAnalyticsConsent(),d=this.shopifyMarketingConsent();"boolean"==typeof h&&(c.analytics=h),"boolean"==typeof d&&(c.marketing=d),Object.keys(c).length>0&&(o.consent=c);const u=this.identity.getIdentityFields(),f=null!=i?i:l(),g=u.distinct_id,m=u.anonymous_id,y=u.visitor_id||m,w=u.session_id;return{workspace_id:this.config.workspaceId,event_id:f,event_name:t,event_data:o,source:"web",timestamp:(new Date).toISOString(),distinct_id:g,anonymous_id:m,visitor_id:y,user_id:u.user_id,canonical_id:u.canonical_id,session_id:w,resolution_method:"browser_sdk",resolution_confidence:1,sdk_version:"1.7.6",sdk_name:"datalyr-web-sdk",schema_version:1}}shouldTrack(){return!this.optedOut&&((!this.consent||!1!==this.consent.analytics)&&(!1!==this.shopifyAnalyticsConsent()&&((!this.config.respectDoNotTrack||"1"!==navigator.doNotTrack&&"1"!==window.doNotTrack&&"yes"!==navigator.doNotTrack)&&(!this.config.respectGlobalPrivacyControl||!0!==navigator.globalPrivacyControl&&!0!==window.globalPrivacyControl))))}consentAllowsMarketing(){return!1!==this.shopifyMarketingConsent()&&(!this.consent||!1!==this.consent.marketing&&!1!==this.consent.sale)}getShopifyCustomerPrivacy(){var t,e;if("undefined"==typeof window)return null;try{return null!==(e=null===(t=window.Shopify)||void 0===t?void 0:t.customerPrivacy)&&void 0!==e?e:null}catch(t){return null}}isShopifyStorefront(){var t;if("shopify"===(null===(t=this.config)||void 0===t?void 0:t.platform))return!0;if("undefined"==typeof window)return!1;try{return Boolean(window.Shopify)||window.location.hostname.toLowerCase().endsWith(".myshopify.com")}catch(t){return!1}}shopifyAnalyticsConsent(){try{const t=this.getShopifyCustomerPrivacy();if(!t)return!this.isShopifyStorefront()&&null;if("function"==typeof t.analyticsProcessingAllowed){const e=t.analyticsProcessingAllowed();return"boolean"==typeof e?e:null}if("function"==typeof t.userCanBeTracked){const e=t.userCanBeTracked();return"boolean"==typeof e?e:null}return!this.isShopifyStorefront()&&null}catch(t){return!this.isShopifyStorefront()&&null}}shopifyMarketingConsent(){try{const t=this.getShopifyCustomerPrivacy();if(!t||"function"!=typeof t.marketingAllowed)return!this.isShopifyStorefront()&&null;const e=t.marketingAllowed();return"boolean"==typeof e?e:!this.isShopifyStorefront()&&null}catch(t){return!this.isShopifyStorefront()&&null}}setupShopifyConsentListener(){if("undefined"!=typeof document)try{this.shopifyConsentHandler=()=>{try{this.onShopifyConsentChanged()}catch(t){this.log("Shopify consent change handling failed:",t)}},document.addEventListener("visitorConsentCollected",this.shopifyConsentHandler);const t=window.Shopify;t&&"function"==typeof t.loadFeatures&&t.loadFeatures([{name:"consent-tracking-api",version:"0.1"}],t=>{if(t)this.log("Shopify loadFeatures(consent-tracking-api) failed:",t);else try{this.onShopifyConsentChanged()}catch(t){this.log("Shopify post-load consent eval failed:",t)}})}catch(t){this.log("Shopify consent listener setup failed:",t)}}onShopifyConsentChanged(){const t=this.shouldTrack();this.queue.setEnabled(t),t&&this.identity.enablePersistence(),t||(this.queue.clear(),this.queue.clearOffline());const e=!1===this.shopifyMarketingConsent();t&&!e||!this.autoIdentify||(this.autoIdentify.destroy(),this.autoIdentify=void 0),!this.consentAllowsMarketing()&&this.container&&(this.container.cleanupAllIframes(),this.container=void 0),this.consentAllowsMarketing()||this.disposeMarketingLinkDecorators(),t&&!e&&!0===this.config.shopifyCartAttributes&&this.syncShopifyCartAttributes().catch(t=>{this.log("Shopify cart attribute sync failed:",t)}),this.log("Shopify consent collected — analytics allowed:",t,"— marketing blocked:",e)}setupSPATracking(){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const t=this;this.lastSpaPath=window.location.pathname+window.location.search+window.location.hash,history.pushState=function(...e){t.originalPushState.apply(history,e),setTimeout(()=>t.handleSpaNavigation(),0)},history.replaceState=function(...e){t.originalReplaceState.apply(history,e),setTimeout(()=>t.handleSpaNavigation(),0)},this.popstateHandler=()=>{setTimeout(()=>t.handleSpaNavigation(),0)},window.addEventListener("popstate",this.popstateHandler),this.hashchangeHandler=()=>{t.handleSpaNavigation()},window.addEventListener("hashchange",this.hashchangeHandler)}handleSpaNavigation(){const t=window.location.pathname+window.location.search+window.location.hash;t!==this.lastSpaPath&&(this.lastSpaPath=t,this.attribution.clearCache(),this.page())}setupUnloadHandler(){this.unloadHandler=()=>{this.queue.forceFlush(!0)},this.visibilityHandler=()=>{"hidden"===document.visibilityState&&this.queue.forceFlush(!1)},window.addEventListener("beforeunload",this.unloadHandler),window.addEventListener("pagehide",this.unloadHandler),window.addEventListener("visibilitychange",this.visibilityHandler)}getPerformanceMetrics(){if(!this.config.enablePerformanceTracking)return null;const t={};try{if(performance&&"function"==typeof performance.getEntriesByType){const e=performance.getEntriesByType("navigation"),i=e&&e[0];i&&(t.pageLoadTime=Math.round(i.loadEventEnd),t.domReadyTime=Math.round(i.domContentLoadedEventEnd),t.firstByteTime=Math.round(i.responseStart),t.dnsTime=Math.round(i.domainLookupEnd-i.domainLookupStart),t.tcpTime=Math.round(i.connectEnd-i.connectStart),t.requestTime=Math.round(i.responseEnd-i.requestStart),t.timeOnPage=Math.round(performance.now()))}}catch(t){this.trackError(t,{context:"performance_metrics"})}return Object.keys(t).length>0?t:null}trackError(t,e){const i={message:t.message||String(t),stack:t.stack,context:e,timestamp:(new Date).toISOString(),url:v(window.location.href)};this.errors.push(i),this.errors.length>this.MAX_ERRORS&&(this.errors=this.errors.slice(-this.MAX_ERRORS)),this.config.debug&&console.error("[Datalyr Error]",i)}getErrors(){return[...this.errors]}getNetworkStatus(){return this.queue.getNetworkStatus()}loadScript(t){this.container&&this.container.triggerCustomScript(t)}getLoadedScripts(){return this.container?this.container.getLoadedScripts():[]}log(...t){var e;(null===(e=this.config)||void 0===e?void 0:e.debug)&&console.log("[Datalyr]",...t)}destroy(){this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),this.hashchangeHandler&&window.removeEventListener("hashchange",this.hashchangeHandler),this.unloadHandler&&(window.removeEventListener("beforeunload",this.unloadHandler),window.removeEventListener("pagehide",this.unloadHandler),this.unloadHandler=void 0),this.visibilityHandler&&(window.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=void 0),this.shopifyConsentHandler&&(document.removeEventListener("visitorConsentCollected",this.shopifyConsentHandler),this.shopifyConsentHandler=void 0),this.outboundDisposer&&(this.outboundDisposer(),this.outboundDisposer=void 0),this.stripeLinksDisposer&&(this.stripeLinksDisposer(),this.stripeLinksDisposer=void 0),this.queue&&this.queue.destroy(),this.session&&this.session.destroy(),this.container&&this.container.cleanupAllIframes(),this.autoIdentify&&this.autoIdentify.destroy(),e.destroy(),this.initializationPromise=null,this.container=void 0,this.autoIdentify=void 0,this.lastSpaPath=null,this.superProperties={},this.userProperties={},this.errors=[],this.initialized=!1,this.log("SDK destroyed")}};"undefined"!=typeof window&&(window.datalyr=M);export{M as datalyr,M as default};
1
+ function t(t,e,i,s){return new(i||(i=Promise))(function(n,o){function r(t){try{c(s.next(t))}catch(t){o(t)}}function a(t){try{c(s.throw(t))}catch(t){o(t)}}function c(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,a)}c((s=s.apply(t,e||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const e=new class{constructor(){this.key=null,this.salt=null}initialize(e,i){return t(this,void 0,void 0,function*(){if(!crypto.subtle){const t=new Error("Web Crypto API not available - encryption cannot be initialized");throw console.error("[Datalyr Encryption]",t.message),t}try{const t=new TextEncoder,s="dl_encryption_salt";let n=localStorage.getItem(s);n?this.salt=this.base64ToArrayBuffer(n):(this.salt=crypto.getRandomValues(new Uint8Array(32)),n=this.arrayBufferToBase64(this.salt),localStorage.setItem(s,n));const o=`datalyr:${e}:${i}`,r=t.encode(o),a=yield crypto.subtle.importKey("raw",r,"PBKDF2",!1,["deriveKey"]);this.key=yield crypto.subtle.deriveKey({name:"PBKDF2",salt:this.salt,iterations:1e5,hash:"SHA-256"},a,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(t){throw console.error("[Datalyr Encryption] Failed to initialize:",t),this.key=null,t}})}encrypt(e){return t(this,void 0,void 0,function*(){if(!this.key||!crypto.subtle)throw new Error("Encryption not initialized - cannot encrypt sensitive data");try{const t="string"==typeof e?e:JSON.stringify(e),i=(new TextEncoder).encode(t),s=crypto.getRandomValues(new Uint8Array(12)),n=yield crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.key,i),o=new Uint8Array(s.length+n.byteLength);return o.set(s,0),o.set(new Uint8Array(n),s.length),this.arrayBufferToBase64(o)}catch(t){throw console.error("[Datalyr Encryption] Encryption failed:",t),t}})}decrypt(e){return t(this,void 0,void 0,function*(){if(!this.key||!crypto.subtle){console.warn("[Datalyr Encryption] Decryption not available - reading potentially unencrypted data");try{return JSON.parse(e)}catch(t){return e}}try{const t=this.base64ToArrayBuffer(e),i=t.slice(0,12),s=t.slice(12),n=yield crypto.subtle.decrypt({name:"AES-GCM",iv:i},this.key,s),o=(new TextDecoder).decode(n);try{return JSON.parse(o)}catch(t){return o}}catch(t){console.warn("[Datalyr Encryption] Decryption failed - attempting to read as unencrypted data (migration mode)");try{return JSON.parse(e)}catch(t){return e}}})}isAvailable(){return null!==this.key&&void 0!==crypto.subtle}arrayBufferToBase64(t){let e="";const i=new Uint8Array(t),s=i.byteLength;for(let t=0;t<s;t++)e+=String.fromCharCode(i[t]);return btoa(e)}base64ToArrayBuffer(t){const e=atob(t),i=e.length,s=new Uint8Array(i);for(let t=0;t<i;t++)s[t]=e.charCodeAt(t);return s}destroy(){this.key=null,this.salt=null}};class i{constructor(t){this.memory=new Map,this.prefix="dl_";try{if(!t)throw new Error("no storage");const e="dl_test__"+Math.random();t.setItem(e,"1"),t.removeItem(e),this.storage=t}catch(t){this.storage=null,"undefined"!=typeof window&&console.warn("[Datalyr] Storage not available, using memory fallback")}}get(t,e=null){const i=this.prefix+t;try{if(this.storage){const t=this.storage.getItem(i);if(null===t)return e;try{return JSON.parse(t)}catch(e){return t}}else{const t=this.memory.get(i);if(void 0===t)return e;try{return JSON.parse(t)}catch(e){return t}}}catch(t){return e}}getString(t,e=null){const i=this.prefix+t;try{const t=this.storage?this.storage.getItem(i):this.memory.has(i)?this.memory.get(i):null;if(null==t)return e;if(t.length>=2&&'"'===t[0]&&'"'===t[t.length-1])try{const e=JSON.parse(t);if("string"==typeof e)return e}catch(t){}return t}catch(t){return e}}set(t,e){const i=this.prefix+t,s="string"==typeof e?e:JSON.stringify(e);try{return this.storage?(this.storage.setItem(i,s),!0):(this.memory.set(i,s),!0)}catch(e){return console.warn("[Datalyr] Failed to store:",t,e),this.memory.set(i,s),!1}}remove(t){const e=this.prefix+t;try{return this.storage?(this.storage.removeItem(e),!0):(this.memory.delete(e),!0)}catch(t){return!1}}keys(){try{if(this.storage){const t=[];for(let e=0;e<this.storage.length;e++){const i=this.storage.key(e);i&&i.startsWith(this.prefix)&&t.push(i.slice(this.prefix.length))}return t}return Array.from(this.memory.keys()).filter(t=>t.startsWith(this.prefix)).map(t=>t.slice(this.prefix.length))}catch(t){return[]}}migrateFromLegacyPrefix(){if(!this.storage)return 0;let t=0;try{const e=[];for(let t=0;t<this.storage.length;t++){const i=this.storage.key(t);i&&i.startsWith("__dl_dl_")&&e.push(i)}e.forEach(e=>{try{const i=this.storage.getItem(e);if(i){const s=e.slice(2);this.storage.getItem(s)||(this.storage.setItem(s,i),t++),this.storage.removeItem(e)}}catch(t){console.warn(`[Datalyr Storage] Failed to migrate legacy key: ${e}`,t)}}),t>0&&console.log(`[Datalyr Storage] Migrated ${t} keys from legacy prefix`)}catch(t){console.warn("[Datalyr Storage] Error during legacy key migration:",t)}return t}getEncrypted(i){return t(this,arguments,void 0,function*(t,i=null){const s=this.prefix+t;try{let t=null;if(t=this.storage?this.storage.getItem(s):this.memory.get(s)||null,!t)return i;return yield e.decrypt(t)}catch(e){return console.warn("[Datalyr Storage] Failed to decrypt:",t,e),i}})}setEncrypted(i,s){return t(this,void 0,void 0,function*(){const t=this.prefix+i,n=yield e.encrypt(s);return this.storage?(this.storage.setItem(t,n),!0):(this.memory.set(t,n),!0)})}}class s{constructor(t={}){this.domain=t.domain||"auto",this.maxAge=t.maxAge||365,this.sameSite=t.sameSite||"Lax",this.secure=t.secure||"auto"}get(t){const e="undefined"!=typeof document?document.cookie:"";if(!e)return null;for(const i of e.split(";")){const e=i.trim(),s=e.indexOf("=");if(-1===s)continue;if(e.slice(0,s)!==t)continue;const n=e.slice(s+1);if(!n)return null;try{return decodeURIComponent(n)}catch(t){return n}}return null}set(t,e,i){try{const s=86400*(i||this.maxAge),n="auto"===this.secure?"https:"===location.protocol:this.secure;let o="";"auto"===this.domain?o=this.getAutoDomain():this.domain&&(o=`;domain=${this.domain}`);const r=[`${t}=${encodeURIComponent(e)}`,`max-age=${s}`,"path=/",`SameSite=${this.sameSite}`,n?"Secure":"",o].filter(Boolean).join(";");return document.cookie=r,!0}catch(e){return console.warn("[Datalyr] Failed to set cookie:",t,e),!1}}remove(t){try{const e=["",location.hostname],i=location.hostname.split(".");return i.length>2&&(e.push(`.${i.slice(-2).join(".")}`),e.push(`.${location.hostname}`)),e.forEach(e=>{const i=e?`;domain=${e}`:"";document.cookie=`${t}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${i}`}),!0}catch(t){return!1}}getAutoDomain(){const t=location.hostname;if("localhost"===t||/^[\d.]+$/.test(t)||/^\[[\d:]+\]$/.test(t))return"";const e=t.split(".");for(let t=e.length-2;t>=0;t--){const i="."+e.slice(t).join("."),s="__dl_test_"+Math.random();if(document.cookie=`${s}=1;domain=${i};path=/`,-1!==document.cookie.indexOf(s))return document.cookie=`${s}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;domain=${i};path=/`,`;domain=${i}`}return""}}const n="undefined"!=typeof window?window.localStorage:void 0,o="undefined"!=typeof window?window.sessionStorage:void 0,r=new i(n);new i(o);const a=new s;function c(e){return t(this,void 0,void 0,function*(){if("undefined"==typeof crypto||!crypto.subtle)return null;if(!e)return null;try{const t=(new TextEncoder).encode(e.toLowerCase().trim()),i=yield crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("")}catch(t){return null}})}function l(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function h(t=window.location.search){const e={};try{if("URLSearchParams"in window){return new URLSearchParams(t).forEach((t,i)=>{e[i]=t}),e}}catch(t){}const i=(t||"").replace(/^\?/,"").split("&");for(const t of i){const[i,s=""]=t.split("=");try{const t=decodeURIComponent((i||"").replace(/\+/g," ")),n=decodeURIComponent((s||"").replace(/\+/g," "));t&&(e[t]=n)}catch(t){}}return e}const d=new Set(["pass","password","passwd","pwd","secret","token","auth","authorization","bearer","signature","cvv","cvc","ssn"]),u=["apikey","accesskey","secretkey","privatekey","publickey","accesstoken","refreshtoken","idtoken","clientsecret","creditcard","cardnumber"];function f(t){if(t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[\s._\-]+/).map(t=>t.toLowerCase()).filter(Boolean).some(t=>d.has(t)))return!0;const e=t.toLowerCase().replace(/[\s._\-]+/g,"");return u.some(t=>e.includes(t))}function p(t,e=5,i=0){if(i>=e)return"[Max depth reached]";if(null==t)return t;if("undefined"!=typeof Element&&t instanceof Element||"undefined"!=typeof Document&&t instanceof Document||"function"==typeof t)return"[Removed]";if(Array.isArray(t))return t.map(t=>p(t,e,i+1));if("object"==typeof t){const s={};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(f(n))continue;s[n]=p(t[n],e,i+1)}return s}return"string"==typeof t?t.length>1e3?t.slice(0,1e3)+"...[truncated]":/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t)?"[Redacted]":t:t}const g=new Set(["token","access_token","refresh_token","id_token","auth","authorization","password","pass","pwd","secret","api_key","apikey","key","session","session_id","sid","email","e","phone","tel","signature","sig","otp","reset","hash"]),m=new Set(["state","client_id","redirect_uri","response_type","grant_type","code_challenge","session_state","scope","iss","access_token","id_token","refresh_token","token"]);function y(t){const e=new URLSearchParams(t);let i=!1;const s=Array.from(new Set(e.keys())).map(t=>t.toLowerCase()).some(t=>m.has(t));for(const t of Array.from(new Set(e.keys()))){const n=t.toLowerCase();("code"===n?s:g.has(n))&&(e.set(t,"__redacted__"),i=!0)}return{out:e.toString(),mutated:i}}function v(t){if(!t||"string"!=typeof t)return t;const e=t.indexOf("#"),i=t.indexOf("?"),s=-1!==i&&(-1===e||i<e)?i:-1;if(-1===s&&-1===e)return t;try{const i=t.slice(0,-1!==s?s:-1!==e?e:t.length),n=-1===s?"":t.slice(s+1,-1===e?t.length:e),o=-1===e?"":t.slice(e+1);let r=!1,a=n;if(n){const t=y(n);t.mutated&&(a=t.out,r=!0)}let c=o;if(o){const t=o.indexOf("?");if(-1!==t){const e=y(o.slice(t+1));e.mutated&&(c=o.slice(0,t+1)+e.out,r=!0)}else if(/[\w-]+=/.test(o)){const t=y(o);t.mutated&&(c=t.out,r=!0)}}return r?i+(-1===s?"":"?"+a)+(-1===e?"":"#"+c):t}catch(e){return t}}function w(t,...e){if(!e.length)return t;const i=e.shift();if(_(t)&&_(i))for(const e in i)_(i[e])?(t[e]||Object.assign(t,{[e]:{}}),w(t[e],i[e])):Object.assign(t,{[e]:i[e]});return w(t,...e)}function _(t){return t&&"object"==typeof t&&!Array.isArray(t)}const k=new Set(["co.uk","org.uk","net.uk","ac.uk","gov.uk","me.uk","com.au","net.au","org.au","edu.au","gov.au","co.nz","net.nz","org.nz","govt.nz","co.jp","ne.jp","or.jp","ac.jp","go.jp","co.in","net.in","org.in","gov.in","ac.in","co.za","net.za","org.za","gov.za","com.br","net.br","org.br","gov.br","edu.br","co.kr","ne.kr","or.kr","go.kr","ac.kr","com.cn","net.cn","org.cn","gov.cn","edu.cn","co.id","co.th","com.sg","com.my","com.ph","com.vn","com.tw","com.hk","com.mx","com.ar","com.co","com.pe","com.cl","co.il","co.at","co.hu","co.pl"]);function b(t){if(!t)return t;const e=t.toLowerCase();if("localhost"===e||/^[0-9]{1,3}(\.[0-9]{1,3}){3}$/.test(e)||/^\[?[0-9a-fA-F:]+\]?$/.test(e))return t;const i=e.split(".");if(i.length<2)return t;const s=i.slice(-2).join(".");return k.has(s)&&i.length>=3?i.slice(-3).join("."):i.slice(-2).join(".")}function S(t){const e={google:["google.com","google."],facebook:["facebook.com","fb.com"],twitter:["twitter.com","t.co","x.com"],linkedin:["linkedin.com","lnkd.in"],instagram:["instagram.com"],youtube:["youtube.com","youtu.be"],tiktok:["tiktok.com"],reddit:["reddit.com"],pinterest:["pinterest.com"],bing:["bing.com"],yahoo:["yahoo.com"],duckduckgo:["duckduckgo.com"],baidu:["baidu.com"]};for(const[i,s]of Object.entries(e))if(s.some(e=>t.includes(e)))return i;return"other"}class I{constructor(t={}){this.userId=null,this.sessionId=null,this.piiGeneration=0,this.persistNewId=!1!==t.persistNewId,this.anonymousId=this.getOrCreateAnonymousId(),this.userId=this.getStoredUserId()}getOrCreateAnonymousId(){let t=a.get("__dl_visitor_id");if(t)return r.set("dl_anonymous_id",t),t;if(t=r.getString("dl_anonymous_id"),t)return this.setRootDomainCookie("__dl_visitor_id",t),t;try{new URLSearchParams(window.location.search).has("_dl_vid")&&this.stripUrlParam("_dl_vid")}catch(t){console.warn("[Datalyr] Failed to parse URL for _dl_vid:",t)}return t=`anon_${l()}`,this.persistAnonymousId(t),t}persistAnonymousId(t){this.persistNewId&&(this.setRootDomainCookie("__dl_visitor_id",t),r.set("dl_anonymous_id",t))}enablePersistence(){this.persistNewId||(this.persistNewId=!0,this.persistAnonymousId(this.anonymousId))}stripUrlParam(t){var e;try{if("undefined"==typeof window||"function"!=typeof(null===(e=window.history)||void 0===e?void 0:e.replaceState))return;const i=new URL(window.location.href);if(!i.searchParams.has(t))return;i.searchParams.delete(t);const s=i.searchParams.toString(),n=i.pathname+(s?"?"+s:"")+i.hash;window.history.replaceState(window.history.state,"",n)}catch(t){}}setRootDomainCookie(t,e){try{const i=function(){const t=window.location.hostname;return"localhost"===t||t.match(/^[0-9]{1,3}\./)||t.match(/^\[?[0-9a-fA-F:]+\]?$/)||t.split(".").length<2?t:"."+b(t)}(),s="https:"===location.protocol?"; Secure":"",n=encodeURIComponent(e);document.cookie=`${t}=${n}; domain=${i}; path=/; max-age=31536000; SameSite=Lax${s}`;a.get(t)!==e&&(document.cookie=`${t}=${n}; path=/; max-age=31536000; SameSite=Lax${s}`)}catch(i){console.error("[Datalyr] Error setting root domain cookie:",i);try{const i="https:"===location.protocol?"; Secure":"",s=encodeURIComponent(e);document.cookie=`${t}=${s}; path=/; max-age=31536000; SameSite=Lax${i}`}catch(t){console.error("[Datalyr] Failed to set cookie even without domain:",t)}}}getStoredUserId(){return r.getString("dl_user_id")}static looksLikePII(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}persistUserId(t){if(!I.looksLikePII(t))return r.set("dl_user_id",t),this.piiGeneration+=1,void r.remove("dl_user_id_pii");r.remove("dl_user_id");const e=++this.piiGeneration;r.setEncrypted("dl_user_id_pii",t).then(()=>{e!==this.piiGeneration&&r.remove("dl_user_id_pii")}).catch(()=>{e===this.piiGeneration&&r.remove("dl_user_id_pii")})}hydrateEncryptedUserId(){return t(this,void 0,void 0,function*(){const t=r.getString("dl_user_id");if(t&&I.looksLikePII(t))return this.userId||(this.userId=t),void this.persistUserId(t);if(this.userId&&I.looksLikePII(this.userId)){return void((yield r.getEncrypted("dl_user_id_pii",null))||this.persistUserId(this.userId))}if(!this.userId)try{const t=yield r.getEncrypted("dl_user_id_pii",null);"string"==typeof t&&t&&!this.userId&&(this.userId=t)}catch(t){}})}getAnonymousId(){return this.anonymousId}getUserId(){return this.userId}getDistinctId(){return this.userId||this.anonymousId}getCanonicalId(){return this.getDistinctId()}setSessionId(t){this.sessionId=t}getSessionId(){return this.sessionId}identify(t,e={}){if(!t)return console.warn("[Datalyr] identify() called without userId"),{};const i=this.userId;return this.userId=t,this.persistUserId(t),{anonymous_id:this.anonymousId,user_id:t,previous_id:i,traits:e,identified_at:(new Date).toISOString(),resolution_method:"identify_call"}}alias(t,e){const i={userId:t,previousId:e||this.anonymousId,aliased_at:(new Date).toISOString()};return e&&e!==this.anonymousId||(this.userId=t,this.persistUserId(t)),i}reset(){this.userId=null,this.piiGeneration+=1,r.remove("dl_user_id"),r.remove("dl_user_id_pii"),r.remove("dl_user_traits"),this.anonymousId=`anon_${l()}`,r.set("dl_anonymous_id",this.anonymousId),this.setRootDomainCookie("__dl_visitor_id",this.anonymousId)}getIdentityFields(){return{distinct_id:this.getDistinctId(),anonymous_id:this.anonymousId,user_id:this.userId,visitor_id:this.anonymousId,visitorId:this.anonymousId,canonical_id:this.getCanonicalId(),session_id:this.sessionId,sessionId:this.sessionId,resolution_method:"browser_sdk",resolution_confidence:1}}}class C{constructor(t=36e5){this.sessionId=null,this.sessionData=null,this.lastActivity=Date.now(),this.SESSION_KEY="dl_session_data",this.activityCheckInterval=null,this.activityListeners=[],this.sessionCreationLock=!1,this.sessionTimeout=t,this.initSession(),this.setupActivityMonitor()}initSession(){const t=r.get(this.SESSION_KEY),e=Date.now();t&&this.isSessionValid(t,e)?(this.sessionData=t,this.sessionId=t.id,this.lastActivity=e):this.createNewSession()}isSessionValid(t,e){return e-t.lastActivity<this.sessionTimeout&&t.isActive}createNewSession(){if(this.sessionCreationLock)return console.log("[Datalyr Session] Session creation already in progress, returning existing ID"),this.sessionId||"";this.sessionCreationLock=!0;try{const t=Date.now();return this.sessionId=`sess_${l()}`,this.sessionData={id:this.sessionId,startTime:t,lastActivity:t,pageViews:0,events:0,duration:0,isActive:!0},this.saveSession(),this.incrementSessionCount(),this.sessionId}finally{this.sessionCreationLock=!1}}rotateSessionId(){const t=Date.now(),e=this.sessionId;return this.sessionId=`sess_${l()}`,this.sessionData?(this.sessionData.id=this.sessionId,this.sessionData.lastActivity=t,this.saveSession(),e&&r.remove(`dl_session_${e}_attribution`),console.log(`[Datalyr Session] Rotated session ID from ${e} to ${this.sessionId}`)):this.createNewSession(),this.sessionId}getSessionId(){return this.sessionId&&this.isSessionActive()||this.createNewSession(),this.sessionId}getSessionData(){return this.sessionData}updateActivity(t){const e=Date.now();this.sessionData&&this.isSessionValid(this.sessionData,e)?(this.lastActivity=e,this.sessionData.lastActivity=e,this.sessionData.duration=e-this.sessionData.startTime,"pageview"!==t&&"page_view"!==t||this.sessionData.pageViews++,this.sessionData.events++,this.saveSession()):this.createNewSession()}isSessionActive(){if(!this.sessionData)return!1;const t=Date.now();return this.isSessionValid(this.sessionData,t)}endSession(){this.sessionData&&(this.sessionData.isActive=!1,this.saveSession()),this.sessionId=null,this.sessionData=null,this.destroy()}saveSession(){this.sessionData&&r.set(this.SESSION_KEY,this.sessionData)}getTimeout(){return this.sessionTimeout}setTimeout(t){this.sessionTimeout=t}storeAttribution(t){r.set("dl_current_session_attribution",Object.assign(Object.assign({},t),{sessionId:this.sessionId,timestamp:Date.now()}))}getAttribution(){if(!this.sessionId)return null;if(!this.isSessionActive())return null;const t=r.get("dl_current_session_attribution");return t&&t.sessionId===this.sessionId?t:null}getMetrics(){return this.sessionData?{session_id:this.sessionId,session_duration:this.sessionData.duration,session_page_views:this.sessionData.pageViews,session_events:this.sessionData.events,session_start:this.sessionData.startTime,time_since_session_start:Date.now()-this.sessionData.startTime}:{}}setupActivityMonitor(){const t=()=>{const t=Date.now();this.sessionData&&t-this.lastActivity>1e3&&this.updateActivity()};["mousedown","keydown","scroll","touchstart"].forEach(e=>{window.addEventListener(e,t,{passive:!0,capture:!0}),this.activityListeners.push({event:e,handler:t})}),this.activityCheckInterval=setInterval(()=>{this.sessionData&&!this.isSessionActive()&&this.createNewSession()},6e4)}destroy(){this.activityListeners.forEach(({event:t,handler:e})=>{window.removeEventListener(t,e)}),this.activityListeners=[],this.activityCheckInterval&&(clearInterval(this.activityCheckInterval),this.activityCheckInterval=null)}getSessionNumber(){return r.get("dl_session_count",0)+1}incrementSessionCount(){const t=r.get("dl_session_count",0);r.set("dl_session_count",t+1)}}class E{constructor(t={}){this.queryParamsCache=null,this.UTM_PARAMS=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],this.CLICK_IDS=["fbclid","gclid","gbraid","wbraid","ttclid","oppref","msclkid","twclid","li_fat_id","sclid","dclid","epik","rdt_cid","obclid","irclid","ko_click_id"],this.CLICK_ID_ALIASES={ScCid:"sclid",sccid:"sclid",irclickid:"irclid"},this.DEFAULT_TRACKED_PARAMS=["lyr","ref","source","campaign","medium","gad_source"],this.MARKETING_COOKIES=["_fbp","_fbc","_gcl_aw","_gcl_dc","_gcl_gb","_gcl_ha","_gac","_ttp","_ttc","_scid"],this.attributionWindow=t.attributionWindow||7776e6,this.trackedParams=[...this.DEFAULT_TRACKED_PARAMS,...t.trackedParams||[]],this.marketingAllowedFn=t.marketingAllowed}isMarketingAllowed(){return!this.marketingAllowedFn||!1!==this.marketingAllowedFn()}clearCache(){this.queryParamsCache=null}captureAttribution(){const t=this.queryParamsCache||h();this.queryParamsCache||(this.queryParamsCache=t);const e={timestamp:Date.now()};for(const i of this.UTM_PARAMS){const s=t[i];if(s){e[i]=s;e[i.replace("utm_","")]=s}}for(const i of this.CLICK_IDS){const s=t[i];s&&(e.clickId||(e.clickId=s,e.clickIdType=i),e[i]=s)}for(const[i,s]of Object.entries(this.CLICK_ID_ALIASES)){const n=t[i];n&&!e[s]&&(e.clickId||(e.clickId=n,e.clickIdType=s),e[s]=n)}for(const i of this.trackedParams){const s=t[i];s&&(e[i]=s)}return document.referrer&&(e.referrer=v(document.referrer),e.referrerHost=this.extractHostname(document.referrer)),e.landingPage=v(window.location.href),e.landingPath=window.location.pathname,e.source||(e.source=this.determineSource(e)),e.medium||(e.medium=this.determineMedium(e)),e}storeFirstTouch(t){const e=r.get("dl_first_touch");let i=!1;e?e.expires_at&&Date.now()>=e.expires_at&&(i=!0):i=!0,i&&r.set("dl_first_touch",Object.assign(Object.assign({},t),{captured_at:Date.now(),expires_at:Date.now()+this.attributionWindow}))}getFirstTouch(){const t=r.get("dl_first_touch");return t&&t.expires_at&&Date.now()>=t.expires_at?(r.remove("dl_first_touch"),null):t}storeLastTouch(t){r.set("dl_last_touch",Object.assign(Object.assign({},t),{captured_at:Date.now(),expires_at:Date.now()+this.attributionWindow}))}getLastTouch(){const t=r.get("dl_last_touch");return t&&t.expires_at&&Date.now()>=t.expires_at?(r.remove("dl_last_touch"),null):t}addTouchpoint(t,e){const i=this.getJourney(),s={timestamp:Date.now(),sessionId:t,source:e.source||void 0,medium:e.medium||void 0,campaign:e.campaign||void 0};i.push(s),i.length>30&&i.shift(),r.set("dl_journey",i)}getJourney(){return r.get("dl_journey",[])}captureAdCookies(){var t,e;const i={},s=this.isMarketingAllowed();if(i._fbp=a.get("_fbp"),i._fbc=a.get("_fbc"),i._gcl_aw=a.get("_gcl_aw"),i._gcl_dc=a.get("_gcl_dc"),i._gcl_gb=a.get("_gcl_gb"),i._gcl_ha=a.get("_gcl_ha"),i._gac=a.get("_gac"),i._ga=a.get("_ga"),i._gid=a.get("_gid"),i._ttp=a.get("_ttp"),i._ttc=a.get("_ttc"),i._scid=a.get("_scid"),s&&!i._fbp&&(this.hasClickId("fbclid")||i._fbc)){const t=Date.now(),e=Math.floor(1e10*Math.random()).toString();i._fbp=`fb.1.${t}.${e}`,a.set("_fbp",i._fbp,90)}const n=this.getCurrentFbclid();if(s&&n){const t=i._fbc,e=this.extractFbclidFromFbc(t);if(t){if(e&&e!==n){const t=Date.now();i._fbc=`fb.1.${t}.${n}`,a.set("_fbc",i._fbc,90),a.set("_dl_fbclid_at",String(t),90)}}else{const t=a.get("_dl_fbclid_at"),e=t?Number(t):NaN,s=Number.isFinite(e)&&e>0?e:Date.now();t||a.set("_dl_fbclid_at",String(s),90),i._fbc=`fb.1.${s}.${n}`,a.set("_fbc",i._fbc,90)}}const o=this.hasClickId("gclid")&&null!==(e=null===(t=this.queryParamsCache)||void 0===t?void 0:t.gclid)&&void 0!==e?e:null;return s&&o&&!a.get("_dl_gclid_at")&&a.set("_dl_gclid_at",String(Date.now()),90),Object.fromEntries(Object.entries(i).filter(([t,e])=>null!==e))}hasClickId(t){return!!(this.queryParamsCache||h())[t]}getCurrentFbclid(){return(this.queryParamsCache||h()).fbclid||null}extractFbclidFromFbc(t){if(!t)return null;const e=t.split(".");return e.length<4||"fb"!==e[0]?null:e.slice(3).join(".")||null}getAttributionData(){const t=this.getFirstTouch(),e=this.getLastTouch(),i=this.getJourney();let s=this.captureAttribution();const n=!!(s.clickId||s.campaign||s.lyr||s.source&&"direct"!==s.source);if(!n){const i=e||t;i&&(s=Object.assign(Object.assign({},i),{referrer:s.referrer,referrerHost:s.referrerHost,landingPage:s.landingPage,landingPath:s.landingPath}))}const o=this.captureAdCookies();!t&&n&&this.storeFirstTouch(s),n&&this.storeLastTouch(s);const r=Object.assign(Object.assign(Object.assign({},s),o),{first_touch_source:null==t?void 0:t.source,first_touch_medium:null==t?void 0:t.medium,first_touch_campaign:null==t?void 0:t.campaign,first_touch_timestamp:null==t?void 0:t.timestamp,firstTouchSource:null==t?void 0:t.source,firstTouchMedium:null==t?void 0:t.medium,firstTouchCampaign:null==t?void 0:t.campaign,last_touch_source:null==e?void 0:e.source,last_touch_medium:null==e?void 0:e.medium,last_touch_campaign:null==e?void 0:e.campaign,last_touch_timestamp:null==e?void 0:e.timestamp,lastTouchSource:null==e?void 0:e.source,lastTouchMedium:null==e?void 0:e.medium,lastTouchCampaign:null==e?void 0:e.campaign,touchpoint_count:i.length,touchpointCount:i.length,days_since_first_touch:(null==t?void 0:t.timestamp)?Math.floor((Date.now()-t.timestamp)/864e5):0,daysSinceFirstTouch:(null==t?void 0:t.timestamp)?Math.floor((Date.now()-t.timestamp)/864e5):0});if(!this.isMarketingAllowed()){const t=[...this.CLICK_IDS,...Object.values(this.CLICK_ID_ALIASES),"clickId","clickIdType",...this.MARKETING_COOKIES];for(const e of t)delete r[e]}return r}determineSource(t){if(t.clickIdType){return{fbclid:"facebook",gclid:"google",gbraid:"google",wbraid:"google",ttclid:"tiktok",msclkid:"bing",twclid:"twitter",li_fat_id:"linkedin",sclid:"snapchat",dclid:"doubleclick",epik:"pinterest",rdt_cid:"reddit",obclid:"outbrain",irclid:"impact",ko_click_id:"klaviyo"}[t.clickIdType]||"paid"}if(t.referrerHost){const e=t.referrerHost.toLowerCase(),i=("undefined"!=typeof window?window.location.hostname:"").toLowerCase();return i&&(e===i||this.isSameRootDomain(e,i))?"direct":e.includes("facebook.com")||e.includes("fb.com")?"facebook":e.includes("twitter.com")||e.includes("t.co")||e.includes("x.com")?"twitter":e.includes("linkedin.com")||e.includes("lnkd.in")?"linkedin":e.includes("instagram.com")?"instagram":e.includes("youtube.com")||e.includes("youtu.be")?"youtube":e.includes("tiktok.com")?"tiktok":e.includes("reddit.com")?"reddit":e.includes("pinterest.com")?"pinterest":e.includes("google.")?"google":e.includes("bing.com")?"bing":e.includes("yahoo.com")?"yahoo":e.includes("duckduckgo.com")?"duckduckgo":e.includes("baidu.com")?"baidu":"referral"}return"direct"}determineMedium(t){if(t.clickId)return"cpc";const e=t.source;if(!e||"direct"===e)return"none";if(["facebook","twitter","linkedin","instagram","youtube","tiktok","reddit","pinterest"].includes(e))return"social";return["google","bing","yahoo","duckduckgo","baidu"].includes(e)?"organic":"referral"}isSameRootDomain(t,e){return b(t)===b(e)}extractHostname(t){try{return new URL(t).hostname}catch(t){return""}}isAttributionExpired(t){return!t.timestamp||Date.now()-t.timestamp>this.attributionWindow}clearExpiredAttribution(){const t=this.getFirstTouch(),e=this.getLastTouch();t&&this.isAttributionExpired(t)&&r.remove("dl_first_touch"),e&&this.isAttributionExpired(e)&&r.remove("dl_last_touch")}}const D=["purchase","signup","subscribe","lead","conversion"],A=["add_to_cart","begin_checkout","view_item","search"],x=3e5;class T extends Error{}class P extends Error{constructor(t,e){super(e||`HTTP ${t}`),this.status=t}}class O{constructor(t){this.queue=[],this.offlineQueue=[],this.batchTimer=null,this.periodicFlushInterval=null,this.flushPromise=null,this.recentEventIds=new Set,this.MAX_RECENT_EVENT_IDS=1e3,this.OFFLINE_QUEUE_KEY="dl_offline_queue",this.flushLock=!1,this.offlineQueueLock=!1,this.offlineProcessing=!1,this.inFlight=[],this.enabled=!0,this.rateLimitedUntil=0,this.droppedEventCount=0,this.lastDropStatus=null;const e=(t,e,i,s)=>{const n=Number(t);return Number.isFinite(n)?Math.min(Math.max(Math.floor(n),i),s):e};this.config={batchSize:e(t.batchSize,10,1,1e3),flushInterval:e(t.flushInterval,5e3,250,36e5),maxRetries:e(t.maxRetries,5,0,20),retryDelay:e(t.retryDelay,1e3,0,6e4),endpoint:t.endpoint||"https://ingest.datalyr.com",fallbackEndpoints:Array.isArray(t.fallbackEndpoints)?t.fallbackEndpoints:[],workspaceId:t.workspaceId,debug:t.debug||!1,criticalEvents:t.criticalEvents||D,highPriorityEvents:t.highPriorityEvents||A,maxOfflineQueueSize:e(t.maxOfflineQueueSize,100,1,1e5)},this.networkStatus={isOnline:!1!==navigator.onLine,lastOfflineAt:null,lastOnlineAt:null},this.loadOfflineQueue(),this.setupNetworkListeners(),this.startPeriodicFlush(),this.networkStatus.isOnline&&this.offlineQueue.length>0&&setTimeout(()=>this.processOfflineQueue(),1e3)}enqueue(t){if(!this.enabled)return;const e=t.event_name;if(this.isDuplicateEvent(t))this.log("Duplicate event suppressed:",e);else{if(this.config.criticalEvents.includes(e))return this.log("Critical event, sending immediately:",e),this.persistCriticalEvent(t),void this.sendBatch([t]).then(()=>{this.removeFromOfflineQueue(t.event_id)}).catch(i=>{if(i instanceof P)return this.log("Critical event permanently rejected, dropping:",e,i),void this.removeFromOfflineQueue(t.event_id);this.log("Critical event send failed, retained in offline queue:",e,i)});this.queue.push(t),this.log("Event queued:",e),this.shouldFlush(e)&&this.flush()}}isDuplicateEvent(t){const e=this.createEventHash(t);if(this.recentEventIds.has(e))return!0;if(this.recentEventIds.add(e),this.recentEventIds.size>this.MAX_RECENT_EVENT_IDS){const t=this.recentEventIds.size-this.MAX_RECENT_EVENT_IDS,e=this.recentEventIds.values();for(let i=0;i<t;i++){const t=e.next();t.done||this.recentEventIds.delete(t.value)}}return!1}createEventHash(t){const e=[t.event_name,t.timestamp,JSON.stringify(t.event_data||{})].join("|");let i=0;for(let t=0;t<e.length;t++){i=(i<<5)-i+e.charCodeAt(t),i&=i}return i.toString(36)}shouldFlush(t){return this.queue.length>=this.config.batchSize||(t&&this.config.highPriorityEvents.includes(t)?(this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(()=>this.flush(),1e3),!1):(this.batchTimer||(this.batchTimer=setTimeout(()=>this.flush(),this.config.flushInterval)),!1))}flush(){return t(this,void 0,void 0,function*(){if(this.enabled&&!(Date.now()<this.rateLimitedUntil)){if(this.flushPromise||this.flushLock)return this.flushPromise||Promise.resolve();this.flushLock=!0;try{this.flushPromise=this._flush(),yield this.flushPromise}finally{this.flushPromise=null,this.flushLock=!1}}})}_flush(){return t(this,void 0,void 0,function*(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),0===this.queue.length)return;if(!this.networkStatus.isOnline)return this.log("Network offline, queuing events"),void this.moveToOfflineQueue();const t=Math.min(this.config.batchSize,this.queue.length),e=this.queue.slice(0,t);this.inFlight=e;try{yield this.sendBatch(e),this.queue.splice(0,t),this.log(`Successfully sent and removed ${t} events from queue`)}catch(i){this.log("Failed to send batch:",i),this.queue.splice(0,t),i instanceof P?(this.droppedEventCount+=e.length,this.lastDropStatus=i.status,console.warn(`[Datalyr Queue] Dropped ${e.length} events — permanent error ${i.status}. ${this.droppedEventCount} dropped this session.`)):this.moveToOfflineQueue(e)}finally{this.inFlight=[]}})}sendBatch(e){return t(this,arguments,void 0,function*(t,e=0,i=0){const s={events:t,batchId:l(),timestamp:(new Date).toISOString()},n=[this.config.endpoint,...this.config.fallbackEndpoints],o=n[i]||this.config.endpoint,r=JSON.stringify(s),a=new Blob([r]).size<=6e4;let c=!1;try{c=!/(^|\.)datalyr\.com$/i.test(new URL(o).hostname)}catch(t){}try{const e=yield fetch(o,Object.assign({method:"POST",headers:{"Content-Type":"application/json","X-Batch-Size":t.length.toString()},body:r,keepalive:a},c?{credentials:"include"}:{}));if(!e.ok){if(429===e.status){const t=parseInt(e.headers.get("Retry-After")||"60");throw this.rateLimitedUntil=Date.now()+1e3*Math.max(t,1),this.log(`Rate limited; backing off ${t}s`),new T("Rate limited (429)")}if(403===e.status)throw this.rateLimitedUntil=Date.now()+x,this.log("Origin rejected (403); backing off 300s and parking events"),new T("Origin rejected (403)");if(e.status>=400&&e.status<500&&408!==e.status)throw new P(e.status,`HTTP ${e.status}: ${e.statusText}`);throw new Error(`HTTP ${e.status}: ${e.statusText}`)}this.log(`Batch sent successfully to ${o}: ${t.length} events`)}catch(s){if(s instanceof T||s instanceof P)throw s;if(i<n.length-1)return this.log(`Failed on ${o}, trying fallback ${i+1}`),this.sendBatch(t,0,i+1);if(e<this.config.maxRetries){const s=function(t,e=1e3){const i=.1*Math.random();return Math.min(e*Math.pow(2,t)*(1+i),3e4)}(e,this.config.retryDelay);return this.log(`Retrying batch in ${s}ms (attempt ${e+1}/${this.config.maxRetries})`),yield new Promise(t=>setTimeout(t,s)),this.sendBatch(t,e+1,i)}throw s}})}setupNetworkListeners(){window.addEventListener("online",()=>{this.networkStatus.isOnline=!0,this.networkStatus.lastOnlineAt=Date.now(),this.log("Network connection restored"),setTimeout(()=>this.processOfflineQueue(),1e3)}),window.addEventListener("offline",()=>{this.networkStatus.isOnline=!1,this.networkStatus.lastOfflineAt=Date.now(),this.log("Network connection lost")})}startPeriodicFlush(){this.periodicFlushInterval=setInterval(()=>{this.queue.length>0&&this.flush(),this.networkStatus.isOnline&&this.offlineQueue.length>0&&this.processOfflineQueue()},this.config.flushInterval)}stopPeriodicFlush(){this.periodicFlushInterval&&(clearInterval(this.periodicFlushInterval),this.periodicFlushInterval=null)}moveToOfflineQueue(t){if(this.enabled){if(this.offlineQueueLock)return console.warn("[Datalyr Queue] Offline queue busy; buffering events without persisting"),void(t&&this.offlineQueue.push(...t));this.offlineQueueLock=!0;try{if(t?this.offlineQueue.push(...t):(this.offlineQueue.push(...this.queue),this.queue=[]),this.offlineQueue.length>this.config.maxOfflineQueueSize){const t=this.offlineQueue.length-this.config.maxOfflineQueueSize;this.offlineQueue.splice(0,t),this.droppedEventCount+=t,console.warn(`[Datalyr Queue] Offline queue full — dropped ${t} oldest event(s).`)}this.saveOfflineQueue()}finally{this.offlineQueueLock=!1}}}persistCriticalEvent(t){this.enabled&&(this.offlineQueue.some(e=>e.event_id===t.event_id)||(this.offlineQueue.push(t),this.offlineQueue.length>this.config.maxOfflineQueueSize&&this.offlineQueue.splice(0,this.offlineQueue.length-this.config.maxOfflineQueueSize),this.saveOfflineQueue()))}removeFromOfflineQueue(t){const e=this.offlineQueue.length;this.offlineQueue=this.offlineQueue.filter(e=>e.event_id!==t),this.offlineQueue.length!==e&&(0===this.offlineQueue.length?r.remove(this.OFFLINE_QUEUE_KEY):this.saveOfflineQueue())}loadOfflineQueue(){const t=r.get(this.OFFLINE_QUEUE_KEY,[]);Array.isArray(t)&&(this.offlineQueue=t,this.log(`Loaded ${this.offlineQueue.length} offline events`))}saveOfflineQueue(){if(!this.enabled)return;const t=this.offlineQueue.slice(-this.config.maxOfflineQueueSize);r.set(this.OFFLINE_QUEUE_KEY,t)}processOfflineQueue(){return t(this,void 0,void 0,function*(){if(this.enabled){if(this.consentCheck&&!1===this.consentCheck())return this.enabled=!1,void this.clearOffline();if(!(Date.now()<this.rateLimitedUntil)&&!this.offlineProcessing&&0!==this.offlineQueue.length&&this.networkStatus.isOnline){this.offlineProcessing=!0;try{for(this.log(`Processing ${this.offlineQueue.length} offline events`);this.offlineQueue.length>0&&this.enabled;){const t=this.offlineQueue.splice(0,this.config.batchSize);try{yield this.sendBatch(t),this.saveOfflineQueue()}catch(e){if(e instanceof P){this.droppedEventCount+=t.length,this.lastDropStatus=e.status,console.warn(`[Datalyr Queue] Dropped ${t.length} offline events — permanent error ${e.status}. ${this.droppedEventCount} dropped this session.`),this.saveOfflineQueue();continue}this.log("Failed to send offline batch:",e),this.offlineQueue.unshift(...t),this.saveOfflineQueue();break}}0===this.offlineQueue.length&&r.remove(this.OFFLINE_QUEUE_KEY)}finally{this.offlineProcessing=!1}}}})}getQueueSize(){return this.queue.length}getOfflineQueueSize(){return this.offlineQueue.length}getStats(){return{queued:this.queue.length,offline:this.offlineQueue.length,droppedEvents:this.droppedEventCount,lastDropStatus:this.lastDropStatus,backoffUntil:this.rateLimitedUntil}}getNetworkStatus(){return Object.assign({},this.networkStatus)}buildBatch(t){return{events:t,batchId:l(),timestamp:(new Date).toISOString()}}forceFlush(){return t(this,arguments,void 0,function*(t=!1){if(!this.enabled)return;if(!t){if(Date.now()<this.rateLimitedUntil)return;return yield this.flush(),void(yield this.processOfflineQueue())}const e=this.queue.slice(this.inFlight.length),i=[...e,...this.offlineQueue];if(this.queue=this.queue.slice(0,this.inFlight.length),this.offlineQueue=[],0===i.length)return;if(this.enabled){const t=i.slice(-this.config.maxOfflineQueueSize);i.length>t.length&&this.log(`Offline cap dropped ${i.length-t.length} oldest events at unload`),r.set(this.OFFLINE_QUEUE_KEY,t)}if(0===e.length)return;if(Date.now()<this.rateLimitedUntil)return;if(!navigator.sendBeacon)return;const s=[];let n=[],o=2;for(const t of e){const e=new Blob([JSON.stringify(t)]).size+1;n.length>0&&(n.length>=this.config.batchSize||o+e>6e4)&&(s.push(n),n=[],o=2),n.push(t),o+=e}n.length>0&&s.push(n);let a=0;for(const t of s){const e=new Blob([JSON.stringify(this.buildBatch(t))],{type:"application/json"});if(!navigator.sendBeacon(this.config.endpoint,e))break;a+=t.length}this.log(`forceFlush(terminal): beaconed ${a}/${e.length} live events; backlog (${i.length-e.length}) persisted for next-load drain`)})}clear(){this.queue=[],this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null)}setEnabled(t){this.enabled=t}setConsentCheck(t){this.consentCheck=t}clearOffline(){this.offlineQueue=[],r.remove(this.OFFLINE_QUEUE_KEY)}log(...t){this.config.debug&&console.log("[Datalyr Queue]",...t)}destroy(){this.stopPeriodicFlush(),this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.queue.length>0&&this.moveToOfflineQueue()}}class L{constructor(t={}){this.privacyMode=t.privacyMode||"standard",this.enableFingerprinting=!1!==t.enableFingerprinting}collect(){return"strict"!==this.privacyMode&&this.enableFingerprinting?this.collectStandard():this.collectMinimal()}collectMinimal(){const t={timezone:this.getTimezone(),language:navigator.language||null,screen_bucket:this.getScreenBucket(),dnt:"1"===navigator.doNotTrack||!0===window.globalPrivacyControl||null,userAgent:navigator.userAgent||null};if("userAgentData"in navigator){const e=navigator.userAgentData;t.userAgentData={brands:e.brands||[],mobile:e.mobile||!1,platform:e.platform||null}}return t}collectStandard(){const t={};try{if(t.timezone=this.getTimezone(),t.language=navigator.language||null,t.screen_bucket=this.getScreenBucket(),t.dnt="1"===navigator.doNotTrack||!0===window.globalPrivacyControl||null,t.userAgent=navigator.userAgent||null,"userAgentData"in navigator){const e=navigator.userAgentData;t.userAgentData={brands:e.brands||[],mobile:e.mobile||!1,platform:e.platform||null}}}catch(t){console.warn("[Datalyr] Error collecting fingerprint:",t)}return t}getTimezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch(t){return null}}getScreenBucket(){try{if(!window.screen)return null;const t=100*Math.round(screen.width/100);return`${t}x${100*Math.round(screen.height/100)}`}catch(t){return null}}generateHash(e){return t(this,void 0,void 0,function*(){try{const t=Object.keys(e).sort().reduce((t,i)=>(t[i]=e[i],t),{}),i=JSON.stringify(t);if(window.crypto&&window.crypto.subtle){const t=(new TextEncoder).encode(i),e=yield crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}let s=0;for(let t=0;t<i.length;t++){s=(s<<5)-s+i.charCodeAt(t),s&=s}return Math.abs(s).toString(16)}catch(t){return""}})}}class F{constructor(t){this.scripts=[],this.loadedScripts=new Set,this.sessionLoadedScripts=new Set,this.pixels=null,this.initialized=!1,this.sandboxedIframes=[],this.iframeCleanupTimeouts=new Map,this.messageHandler=null,this.workspaceId=t.workspaceId,this.endpoint=t.endpoint||"https://ingest.datalyr.com",this.debug=t.debug||!1,this.getIdentity=t.getIdentity;const e=r.get("dl_session_scripts",[]);this.sessionLoadedScripts=new Set(e),this.messageHandler=t=>{if(t.data&&"datalyr_script_complete"===t.data.type){const e=t.data.scriptId;this.log("Received script completion signal:",e);const i=this.sandboxedIframes.find(t=>t.dataset.datalyrScript===e);i&&this.cleanupIframe(i)}},window.addEventListener("message",this.messageHandler)}init(){return t(this,void 0,void 0,function*(){if(!this.initialized)try{const t="undefined"!=typeof AbortController?new AbortController:null,e=t?setTimeout(()=>t.abort(),3e3):null;let i;try{i=yield fetch(`${this.endpoint}/container-scripts`,{method:"POST",headers:{"Content-Type":"application/json","X-Container-Version":"1.0"},body:JSON.stringify({workspaceId:this.workspaceId}),signal:t?t.signal:void 0})}finally{e&&clearTimeout(e)}if(!i.ok)throw new Error(`Failed to fetch container scripts: ${i.status}`);const s=yield i.json();this.scripts=s.scripts||[],this.pixels=s.pixels||null,this.remoteConfig=s.config&&"object"==typeof s.config?s.config:void 0,this.pixels&&(yield this.initializePixels()),this.loadScriptsByTrigger("page_load"),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{this.loadScriptsByTrigger("dom_ready")}):this.loadScriptsByTrigger("dom_ready"),window.addEventListener("load",()=>{this.loadScriptsByTrigger("window_load")}),this.initialized=!0,this.log("Container manager initialized with",this.scripts.length,"scripts")}catch(t){this.log("Error initializing container:",t)}})}getRemoteConfig(){return this.remoteConfig}loadScriptsByTrigger(t){this.scripts.filter(e=>e.enabled&&e.trigger===t&&this.shouldLoadScript(e)).forEach(t=>this.loadScript(t))}shouldLoadScript(t){return("once_per_page"!==t.frequency||!this.loadedScripts.has(t.id))&&(("once_per_session"!==t.frequency||!this.sessionLoadedScripts.has(t.id))&&(!(t.conditions&&t.conditions.length>0)||this.evaluateConditions(t.conditions)))}evaluateConditions(t){return t.every(t=>{try{const{type:e,operator:i,value:s}=t;switch(e){case"url_path":return this.evaluateStringCondition(window.location.pathname,i,s);case"url_host":return this.evaluateStringCondition(window.location.hostname,i,s);case"url_parameter":const e=new URLSearchParams(window.location.search);return this.evaluateStringCondition(e.get(t.parameter)||"",i,s);case"referrer":return this.evaluateStringCondition(document.referrer,i,s);case"device_type":const n=/Mobile|Android|iPhone|iPad/i.test(navigator.userAgent);return this.evaluateStringCondition(n?"mobile":"desktop",i,s);default:return!0}}catch(t){return!1}})}evaluateStringCondition(t,e,i){switch(e){case"equals":return t===i;case"not_equals":return t!==i;case"contains":return t.includes(i);case"not_contains":return!t.includes(i);case"starts_with":return t.startsWith(i);case"ends_with":return t.endsWith(i);case"matches_regex":try{return new RegExp(i).test(t)}catch(t){return!1}default:return!1}}loadScript(t){try{switch(t.type){case"inline":this.loadInlineScript(t);break;case"external":this.loadExternalScript(t);break;case"pixel":this.loadPixel(t)}this.loadedScripts.add(t.id),"once_per_session"===t.frequency&&(this.sessionLoadedScripts.add(t.id),r.set("dl_session_scripts",Array.from(this.sessionLoadedScripts))),this.log("Loaded script:",t.name)}catch(e){this.log("Error loading script:",t.name,e)}}loadInlineScript(t){const e=document.createElement("iframe");e.style.display="none",e.setAttribute("sandbox","allow-scripts"),e.dataset.datalyrScript=t.id,this.sandboxedIframes.push(e);const i=`\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset="UTF-8">\n </head>\n <body>\n <script>\n // User-provided script runs here in isolation\n try {\n ${t.content}\n } catch (error) {\n console.error('[Datalyr Container] Script execution error:', error);\n }\n\n // FIXED (ISSUE-02): Signal completion for cleanup\n // Scripts have 5 seconds to execute before iframe is removed\n setTimeout(function() {\n try {\n parent.postMessage({ type: 'datalyr_script_complete', scriptId: '${t.id}' }, '*');\n } catch (e) {\n // Ignore postMessage errors from sandbox\n }\n }, 5000);\n <\/script>\n </body>\n </html>\n `;document.body.appendChild(e),e.contentDocument&&(e.contentDocument.open(),e.contentDocument.write(i),e.contentDocument.close());const s=window.setTimeout(()=>{this.cleanupIframe(e)},3e4);this.iframeCleanupTimeouts.set(e,s),this.log("Loaded inline script in sandbox:",t.id)}cleanupIframe(t){try{const e=this.iframeCleanupTimeouts.get(t);e&&(clearTimeout(e),this.iframeCleanupTimeouts.delete(t));const i=this.sandboxedIframes.indexOf(t);i>-1&&this.sandboxedIframes.splice(i,1),t.parentNode&&(t.parentNode.removeChild(t),this.log("Cleaned up sandboxed iframe:",t.dataset.datalyrScript))}catch(t){this.log("Error cleaning up iframe:",t)}}cleanupAllIframes(){const t=[...this.sandboxedIframes];t.forEach(t=>this.cleanupIframe(t)),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.iframeCleanupTimeouts.forEach(t=>clearTimeout(t)),this.iframeCleanupTimeouts.clear(),this.log(`Cleaned up ${t.length} sandboxed iframes`)}loadExternalScript(t){var e;if(!this.isValidScriptUrl(t.content))return void this.log("Blocked invalid script URL:",t.content);if(!(null===(e=t.settings)||void 0===e?void 0:e.integrity))return void console.error(`[Datalyr Container] SECURITY: External script "${t.id}" blocked - missing SRI hash.\nAll external scripts MUST include an integrity hash to prevent CDN compromise attacks.\nGenerate SRI hash at: https://www.srihash.org/\nExample: { integrity: "sha384-..." }`);const i=document.createElement("script");i.src=t.content,i.dataset.datalyrScript=t.id,t.settings?(i.integrity=t.settings.integrity,i.crossOrigin=t.settings.crossorigin||"anonymous",!1!==t.settings.async&&(i.async=!0),t.settings.defer&&(i.defer=!0)):i.async=!0,document.head.appendChild(i)}loadPixel(t){const e=new Image;e.src=t.content,e.style.display="none",e.dataset.datalyrPixel=t.id,document.body.appendChild(e)}initializePixels(){return t(this,void 0,void 0,function*(){var t,e,i,s;this.pixels&&((null===(t=this.pixels.meta)||void 0===t?void 0:t.enabled)&&this.pixels.meta.pixel_id&&(yield this.initializeMetaPixel(this.pixels.meta)),(null===(e=this.pixels.google)||void 0===e?void 0:e.enabled)&&this.pixels.google.tag_id&&this.initializeGoogleTag(this.pixels.google),(null===(i=this.pixels.tiktok)||void 0===i?void 0:i.enabled)&&this.pixels.tiktok.pixel_id&&this.initializeTikTokPixel(this.pixels.tiktok),(null===(s=this.pixels.whop)||void 0===s?void 0:s.enabled)&&this.pixels.whop.company_id&&this.initializeWhopPixel(this.pixels.whop))})}initializeWhopPixel(t){var e,i;try{const s=window;if(!s.whop){const t=s.whop={q:[],t:Date.now(),s:[],o:"https://t.whop.tw",track:function(...e){t.q.push([Date.now(),...e])},setScope:function(...e){t.s=e.filter(t=>"string"==typeof t),t.q.push([Date.now(),"setScope",...t.s])},scope:function(...e){return{track:function(...i){t.q.push([Date.now(),...i,{__scope:e}])}}}},i=document.createElement("script");i.async=!0,i.src="https://t.whop.tw/s.js";const n=document.getElementsByTagName("script")[0];null===(e=null==n?void 0:n.parentNode)||void 0===e||e.insertBefore(i,n),n||document.head.appendChild(i)}if("function"!=typeof(null===(i=s.whop)||void 0===i?void 0:i.setScope))throw new Error("Existing window.whop does not expose setScope");s.whop.setScope(t.company_id),this.log("Whop Pixel initialized:",t.company_id)}catch(t){this.log("Error initializing Whop Pixel:",t)}}initializeMetaPixel(e){return t(this,void 0,void 0,function*(){var t,i,s,n,o,r,a;try{i=window,s=document,n="script",i.fbq||(o=i.fbq=function(){o.callMethod?o.callMethod.apply(o,arguments):o.queue.push(arguments)},i._fbq||(i._fbq=o),o.push=o,o.loaded=!0,o.version="2.0",o.queue=[],(r=s.createElement(n)).async=!0,r.src="https://connect.facebook.net/en_US/fbevents.js",(a=s.getElementsByTagName(n)[0]).parentNode.insertBefore(r,a));const l={},h=null===(t=this.getIdentity)||void 0===t?void 0:t.call(this);if(null==h?void 0:h.externalId){const t=yield c(String(h.externalId));t&&(l.external_id=t)}if(null==h?void 0:h.email){const t=yield c(String(h.email).toLowerCase().trim());t&&(l.em=t)}Object.keys(l).length>0?(window.fbq("init",e.pixel_id,l),this.log("Meta Pixel initialized with advanced matching:",e.pixel_id,Object.keys(l))):(window.fbq("init",e.pixel_id),this.log("Meta Pixel initialized (no advanced matching):",e.pixel_id))}catch(t){this.log("Error initializing Meta Pixel:",t)}})}initializeGoogleTag(t){try{const e=document.createElement("script");function i(...t){window.dataLayer.push(t)}e.async=!0,e.src=`https://www.googletagmanager.com/gtag/js?id=${t.tag_id}`,document.head.appendChild(e),window.dataLayer=window.dataLayer||[],window.gtag=i,i("js",new Date),i("config",t.tag_id,{allow_enhanced_conversions:!1!==t.enhanced_conversions}),this.log("Google Tag initialized:",t.tag_id)}catch(s){this.log("Error initializing Google Tag:",s)}}initializeTikTokPixel(t){try{!function(t,e,i){t.TiktokAnalyticsObject=i;var s=t[i]=t[i]||[];s.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],s.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var n=0;n<s.methods.length;n++)s.setAndDefer(s,s.methods[n]);s.instance=function(t){for(var e=s._i[t]||[],i=0;i<s.methods.length;i++)s.setAndDefer(e,s.methods[i]);return e},s.load=function(t,e){var n;s._i=s._i||{},s._i[t]=[],s._o=s._o||{},s._o[t]=e||{};var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src="https://analytics.tiktok.com/i18n/pixel/events.js?sdkid="+t+"&lib="+i;var r=document.getElementsByTagName("script")[0];null===(n=r.parentNode)||void 0===n||n.insertBefore(o,r)}}(window,document,"ttq"),window.ttq.load(t.pixel_id),window.ttq.page(),this.log("TikTok Pixel initialized:",t.pixel_id)}catch(t){this.log("Error initializing TikTok Pixel:",t)}}hasMetaPixel(){var t,e;return!(!(null===(e=null===(t=this.pixels)||void 0===t?void 0:t.meta)||void 0===e?void 0:e.enabled)||!window.fbq)}trackToPixels(t,e={},i){var s,n,o,r,a,c,l,h,d,u,f,p;if(t.startsWith("$"))return;const g=this.sanitizeEventName(t),m=this.sanitizeProperties(e);if((null===(n=null===(s=this.pixels)||void 0===s?void 0:s.meta)||void 0===n?void 0:n.enabled)&&window.fbq)try{const e={page_view:"PageView",pageview:"PageView",view_content:"ViewContent",product_viewed:"ViewContent",view_item:"ViewContent",add_to_cart:"AddToCart",product_added:"AddToCart",add_to_wishlist:"AddToWishlist",initiate_checkout:"InitiateCheckout",begin_checkout:"InitiateCheckout",checkout_started:"InitiateCheckout",add_payment_info:"AddPaymentInfo",purchase:"Purchase",order_completed:"Purchase",order_paid:"Purchase",lead:"Lead",complete_registration:"CompleteRegistration",sign_up:"CompleteRegistration",signup:"CompleteRegistration",search:"Search",subscribe:"Subscribe",subscription_created:"Subscribe",start_trial:"StartTrial",trial_started:"StartTrial",contact:"Contact",schedule:"Schedule"},s=null===(r=null===(o=this.pixels)||void 0===o?void 0:o.meta)||void 0===r?void 0:r.event_mappings,n=(null==s?void 0:s[t])||e[String(t).toLowerCase()]||g;i?window.fbq("track",n,m,{eventID:i}):window.fbq("track",n,m)}catch(t){this.log("Error tracking Meta Pixel event:",t)}if((null===(c=null===(a=this.pixels)||void 0===a?void 0:a.google)||void 0===c?void 0:c.enabled)&&window.gtag)try{window.gtag("event",g,m)}catch(t){this.log("Error tracking Google Tag event:",t)}if((null===(h=null===(l=this.pixels)||void 0===l?void 0:l.tiktok)||void 0===h?void 0:h.enabled)&&window.ttq)try{const e={view_content:"ViewContent",product_viewed:"ViewContent",view_item:"ViewContent",search:"Search",add_to_wishlist:"AddToWishlist",add_to_cart:"AddToCart",product_added:"AddToCart",initiate_checkout:"InitiateCheckout",begin_checkout:"InitiateCheckout",checkout_started:"InitiateCheckout",add_payment_info:"AddPaymentInfo",purchase:"CompletePayment",order_completed:"CompletePayment",order_paid:"CompletePayment",place_an_order:"PlaceAnOrder",contact:"Contact",download:"Download",lead:"SubmitForm",submit_form:"SubmitForm",complete_registration:"CompleteRegistration",sign_up:"CompleteRegistration",signup:"CompleteRegistration",subscribe:"Subscribe",subscription_created:"Subscribe"},i=null===(u=null===(d=this.pixels)||void 0===d?void 0:d.tiktok)||void 0===u?void 0:u.event_mappings,s=(null==i?void 0:i[t])||e[String(t).toLowerCase()]||g;window.ttq.track(s,m)}catch(t){this.log("Error tracking TikTok Pixel event:",t)}if((null===(p=null===(f=this.pixels)||void 0===f?void 0:f.whop)||void 0===p?void 0:p.enabled)&&window.whop&&("pageview"===t||"page_view"===t))try{window.whop.track("page")}catch(t){this.log("Error tracking Whop Pixel page:",t)}}triggerCustomScript(t){const e=this.scripts.find(e=>e.id===t&&"custom"===e.trigger);e&&this.shouldLoadScript(e)&&this.loadScript(e)}getLoadedScripts(){return Array.from(this.loadedScripts)}isValidScriptUrl(t){try{const e=new URL(t);return!("https:"!==e.protocol&&!e.hostname.includes("localhost"))&&!["data:","javascript:","file:"].includes(e.protocol)}catch(t){return!1}}sanitizeEventName(t){return"string"!=typeof t?"unknown_event":t.replace(/[^a-zA-Z0-9_$ ]/g,"").substring(0,100)}sanitizeProperties(t){if(null==t)return{};if("object"!=typeof t)return this.sanitizeValue(t);if(Array.isArray(t))return t.map(t=>this.sanitizeValue(t));const e={};for(const[i,s]of Object.entries(t)){const t=i.replace(/[^a-zA-Z0-9_]/g,"").substring(0,100);t&&(e[t]=this.sanitizeValue(s))}return e}sanitizeValue(t){return null==t?t:"string"==typeof t?t.replace(/<script[^>]*>.*?<\/script>/gi,"").replace(/<[^>]+>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").substring(0,1e3):"number"==typeof t||"boolean"==typeof t?t:"object"==typeof t?this.sanitizeProperties(t):String(t).substring(0,1e3)}log(...t){this.debug&&console.log("[Datalyr Container]",...t)}}class z{constructor(t={}){this.formListeners=[],this.lastIdentifyTime=0,this.RATE_LIMIT_MS=5e3,this.destroyed=!1,this.config={enabled:!1!==t.enabled,captureFromForms:!1!==t.captureFromForms,captureFromAPI:!0===t.captureFromAPI,captureFromShopify:!1!==t.captureFromShopify,trustedDomains:t.trustedDomains||[],debug:t.debug||!1}}initialize(e){return t(this,void 0,void 0,function*(){if(!this.config.enabled)return void this.log("Auto-identify disabled");this.identifyCallback=e;const t=yield r.getEncrypted("dl_auto_identified_email");if(t){const e=r.get("dl_auto_identified_email");if("string"==typeof e&&e.includes("@"))try{yield r.setEncrypted("dl_auto_identified_email",t),this.log("Migrated legacy plaintext auto-identified email to encrypted storage")}catch(t){this.log("Failed to migrate legacy auto-identified email:",t)}return void this.log("User already auto-identified")}this.config.captureFromForms&&this.setupFormMonitoring(),this.config.captureFromAPI&&(this.setupFetchInterception(),this.setupXHRInterception()),this.config.captureFromShopify&&this.setupShopifyMonitoring(),this.log("Auto-identify initialized")})}setupFormMonitoring(){this.scanForEmailForms(),this.formObserver=new MutationObserver(()=>{this.scanForEmailForms()}),this.formObserver.observe(document.body,{childList:!0,subtree:!0}),this.log("Form monitoring active")}findVisitorEmailInput(t){const e=Array.from(t.querySelectorAll('input[type="email"], input[name*="email" i], input[id*="email" i], input[autocomplete="email"]')).filter(t=>!this.isThirdPartyEmailField(t));if(0===e.length)return null;if(1===e.length)return e[0];const i=e.filter(t=>"email"===(t.getAttribute("autocomplete")||"").toLowerCase());return 1===i.length?i[0]:(this.log("Multiple email inputs in form; skipping auto-identify (ambiguous)"),null)}isThirdPartyEmailField(t){const e=[t.name,t.id,t.getAttribute("autocomplete"),t.getAttribute("aria-label"),t.placeholder].filter(Boolean).join(" ");return z.THIRD_PARTY_EMAIL_FIELD.test(e)}scanForEmailForms(){if(this.destroyed)return;document.querySelectorAll("form").forEach(t=>{if(this.formListeners.some(e=>e.element===t))return;if(this.findVisitorEmailInput(t)){const e=e=>this.handleFormSubmit(e,t);t.addEventListener("submit",e),this.formListeners.push({element:t,handler:e}),this.log("Monitoring form:",t)}})}handleFormSubmit(t,e){try{const t=this.findVisitorEmailInput(e);if(!t)return;const i=t.value.trim();this.isValidEmail(i)&&(this.log("Email captured from form:",i),this.triggerIdentify(i,"form"))}catch(t){this.log("Error handling form submit:",t)}}setupFetchInterception(){if("function"!=typeof window.fetch)return;this.originalFetch=window.fetch;const e=this;window.fetch=function(i,s){return t(this,void 0,void 0,function*(){const n="string"==typeof i?i:i instanceof URL?i.href:i.url;if(!e.isTrustedDomain(n))return e.originalFetch.call(window,i,s);try{(null==s?void 0:s.body)&&e.extractEmailFromData(s.body,"api-request");const n=e.originalFetch.call(window,i,s);return n.then(i=>t(this,void 0,void 0,function*(){var t;if(i.ok&&(null===(t=i.headers.get("content-type"))||void 0===t?void 0:t.includes("application/json")))try{const t=i.clone(),s=yield t.json();e.extractEmailFromData(s,"api-response")}catch(t){}})).catch(()=>{}),n}catch(t){return e.log("Error intercepting fetch:",t),e.originalFetch.call(window,i,s)}})},this.log("Fetch interception active")}setupXHRInterception(){if("undefined"==typeof XMLHttpRequest)return;const t=this;this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send,XMLHttpRequest.prototype.open=function(e,i,...s){return this._datalyrUrl="string"==typeof i?i:i.href,t.originalXHROpen.apply(this,[e,i,...s])},XMLHttpRequest.prototype.send=function(e){const i=this._datalyrUrl;return i&&t.isTrustedDomain(i)&&(e&&t.extractEmailFromData(e,"api-request"),this.addEventListener("load",function(){if(this.status>=200&&this.status<300)try{const e=this.getResponseHeader("content-type");if(null==e?void 0:e.includes("application/json")){const e=JSON.parse(this.responseText);t.extractEmailFromData(e,"api-response")}}catch(t){}})),t.originalXHRSend.call(this,e)},this.log("XHR interception active")}setupShopifyMonitoring(){if(!this.isShopify())return;this.log("Shopify detected, setting up monitoring"),this.checkShopifyCustomer();let t=0;this.shopifyCheckInterval=setInterval(()=>{t++,this.checkShopifyCustomer(),t>=12&&this.shopifyCheckInterval&&(clearInterval(this.shopifyCheckInterval),this.shopifyCheckInterval=void 0,this.log("Shopify monitoring stopped after max checks (no login detected)"))},1e4),this.log("Shopify monitoring active")}isShopify(){return!!(window.Shopify||document.querySelector('meta[name="shopify-checkout-api-token"]')||window.location.hostname.includes(".myshopify.com"))}checkShopifyCustomer(){return t(this,void 0,void 0,function*(){var t;try{const e=yield fetch("/account.json",{credentials:"same-origin"});if(e.ok){const i=yield e.json();(null===(t=null==i?void 0:i.customer)||void 0===t?void 0:t.email)&&(this.log("Email captured from Shopify:",i.customer.email),this.triggerIdentify(i.customer.email,"shopify"),this.shopifyCheckInterval&&(clearInterval(this.shopifyCheckInterval),this.shopifyCheckInterval=void 0))}}catch(t){this.log("Shopify customer check failed:",t)}})}extractEmailFromData(t,e){try{let i=[];if("string"==typeof t)try{const e=JSON.parse(t);i=this.findEmailsInObject(e)}catch(e){const s=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,n=t.match(s);n&&(i=n)}else t instanceof FormData?t.forEach(t=>{"string"==typeof t&&this.isValidEmail(t)&&i.push(t)}):"object"==typeof t&&null!==t&&(i=this.findEmailsInObject(t));if(i.length>0){const t=i[0];this.log(`Email found in ${e}:`,t),this.triggerIdentify(t,"api")}}catch(t){this.log("Error extracting email from data:",t)}}findEmailsInObject(t,e=0){if(e>5)return[];const i=[];for(const s in t){if(!t.hasOwnProperty(s))continue;const n=t[s];/email/i.test(s)&&"string"==typeof n&&this.isValidEmail(n)?i.push(n):"object"==typeof n&&null!==n&&i.push(...this.findEmailsInObject(n,e+1))}return i}isTrustedDomain(t){try{const e=new URL(t,window.location.origin);return e.origin===window.location.origin||0!==this.config.trustedDomains.length&&this.config.trustedDomains.some(t=>e.hostname===t||e.hostname.endsWith(`.${t}`))}catch(t){return!1}}isValidEmail(t){if(!t||"string"!=typeof t)return!1;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t))return!1;return![/test@/i,/example@/i,/demo@/i,/fake@/i,/@test\./i,/@example\./i].some(e=>e.test(t))}triggerIdentify(e,i){return t(this,void 0,void 0,function*(){if(this.destroyed)return;const t=Date.now();if(t-this.lastIdentifyTime<this.RATE_LIMIT_MS)return void this.log("Rate limited, skipping identify");this.lastIdentifyTime=t;if((yield r.getEncrypted("dl_auto_identified_email"))!==e){if(!this.destroyed){try{yield r.setEncrypted("dl_auto_identified_email",e)}catch(t){this.log("Failed to persist auto-identified email:",t)}this.identifyCallback&&(this.log(`Auto-identifying user: ${e} (source: ${i})`),this.identifyCallback(e,i))}}else this.log("Already identified with this email")})}destroy(){this.destroyed=!0,this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=void 0),this.originalXHROpen&&(XMLHttpRequest.prototype.open=this.originalXHROpen,this.originalXHROpen=void 0),this.originalXHRSend&&(XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHRSend=void 0),this.formObserver&&(this.formObserver.disconnect(),this.formObserver=void 0),this.formListeners.forEach(({element:t,handler:e})=>{t.removeEventListener("submit",e)}),this.formListeners=[],this.shopifyCheckInterval&&(clearInterval(this.shopifyCheckInterval),this.shopifyCheckInterval=void 0),this.log("Auto-identify destroyed")}log(...t){this.config.debug&&console.log("[Datalyr Auto-Identify]",...t)}}z.THIRD_PARTY_EMAIL_FIELD=/(recipient|friend|gift|refer|invite|colleague|coworker|share|to[-_]?email|email[-_]?to|second(ary)?[-_]?email)/i;const M=/cs_(?:live|test)_[A-Za-z0-9]{8,}/,R=new Set(["checkout.stripe.com"]),$=/(json|text|javascript)/i;function q(t){if(!t)return null;const e=M.exec(t);return e?e[0]:null}function j(t,e){try{const i=new URL(t,null!=e?e:"undefined"!=typeof window?window.location.href:void 0).hostname.toLowerCase();return R.has(i)}catch(t){return!1}}class U{constructor(t={}){var e,i;this.seen=new Set,this.disposers=[],this.started=!1,this.maxSessions=null!==(e=t.maxSessions)&&void 0!==e?e:5,this.maxScanBytes=null!==(i=t.maxScanBytes)&&void 0!==i?i:65536}start(t){this.started||"undefined"==typeof window||(this.started=!0,this.sink=t,this.hookFetch(),this.hookXhr(),this.hookClicks(),this.hookWindowOpen())}stop(){for(const t of this.disposers.reverse())try{t()}catch(t){}this.disposers=[],this.started=!1,this.sink=void 0}emit(t){var e;if(t&&!this.seen.has(t)&&!(this.seen.size>=this.maxSessions)){this.seen.add(t);try{null===(e=this.sink)||void 0===e||e.call(this,t)}catch(t){}}}scanResponse(t){var e,i,s,n,o,r;try{const a=null!==(s=null===(i=null===(e=t.headers)||void 0===e?void 0:e.get)||void 0===i?void 0:i.call(e,"content-type"))&&void 0!==s?s:"";if(a&&!$.test(a))return;const c=Number(null!==(r=null===(o=null===(n=t.headers)||void 0===n?void 0:n.get)||void 0===o?void 0:o.call(n,"content-length"))&&void 0!==r?r:NaN);if(Number.isFinite(c)&&c>this.maxScanBytes)return;const l="function"==typeof t.clone?t.clone():null;if(!l)return;l.text().then(t=>this.emit(q(t.slice(0,this.maxScanBytes)))).catch(()=>{})}catch(t){}}hookFetch(){if("function"!=typeof window.fetch)return;const t=window.fetch,e=this,i=function(...i){const s=t.apply(null!=this?this:window,i);try{s.then(t=>e.scanResponse(t)).catch(()=>{})}catch(t){}return s};window.fetch=i,this.disposers.push(()=>{window.fetch===i&&(window.fetch=t)})}hookXhr(){if("undefined"==typeof XMLHttpRequest)return;const t=XMLHttpRequest.prototype,e=t.send;if("function"!=typeof e)return;const i=this,s=function(...t){try{this.addEventListener("load",()=>{try{if(""!==this.responseType&&"text"!==this.responseType)return;const t=this.responseText;if(!t||t.length>i.maxScanBytes)return;i.emit(q(t))}catch(t){}})}catch(t){}return e.apply(this,t)};t.send=s,this.disposers.push(()=>{t.send===s&&(t.send=e)})}hookClicks(){if("undefined"==typeof document)return;const t=t=>{var e,i;try{const s=null===(i=null===(e=t.target)||void 0===e?void 0:e.closest)||void 0===i?void 0:i.call(e,"a[href]");if(!s||!s.href||!j(s.href))return;this.emit(q(s.href))}catch(t){}};document.addEventListener("click",t,!0),this.disposers.push(()=>document.removeEventListener("click",t,!0))}hookWindowOpen(){if("function"!=typeof window.open)return;const t=window.open,e=this,i=function(...i){var s;try{const t=i[0],n="string"==typeof t?t:null===(s=null==t?void 0:t.toString)||void 0===s?void 0:s.call(t);n&&j(n)&&e.emit(q(n))}catch(t){}return t.apply(null!=this?this:window,i)};window.open=i,this.disposers.push(()=>{window.open===i&&(window.open=t)})}}const N=["autoIdentify","autoIdentifyForms","autoIdentifyAPI","autoIdentifyShopify","shopifyCartAttributes","stripeCheckoutSessions","checkoutChampDomains","respectGlobalPrivacyControl","respectDoNotTrack","privacyMode"];const Q="dl_identify_fingerprint";class H{constructor(){this.explicitConfigKeys=new Set,this.superProperties={},this.userProperties={},this.optedOut=!1,this.consent=null,this.initialized=!1,this.errors=[],this.MAX_ERRORS=50,this.lastSpaPath=null,this.initialPageViewReady=!1,this.initialPageViewSent=!1,this.initializationPromise=null}getWorkspaceId(){var t,e;return null!==(e=null===(t=this.config)||void 0===t?void 0:t.workspaceId)&&void 0!==e?e:null}init(t){if(this.initialized)return void console.warn("[Datalyr] SDK already initialized");if(!t.workspaceId)throw new Error("[Datalyr] workspaceId is required");this.explicitConfigKeys=new Set(Object.keys(t)),this.config=Object.assign({endpoint:"https://ingest.datalyr.com",debug:!1,batchSize:10,flushInterval:5e3,flushAt:10,criticalEvents:void 0,highPriorityEvents:void 0,sessionTimeout:36e5,trackSessions:!0,attributionWindow:7776e6,trackedParams:[],respectDoNotTrack:!1,respectGlobalPrivacyControl:!0,privacyMode:"standard",cookieDomain:"auto",cookieExpires:365,secureCookie:"auto",sameSite:"Lax",cookiePrefix:"__dl_",enablePerformanceTracking:!0,enableFingerprinting:!0,maxRetries:5,retryDelay:1e3,maxOfflineQueueSize:100,trackSPA:!0,trackPageViews:!0,fallbackEndpoints:[],plugins:[]},t),"shopify"===this.config.platform&&void 0===this.config.shopifyCartAttributes&&(this.config.shopifyCartAttributes=!0),this.cookies=new s({domain:this.config.cookieDomain,maxAge:this.config.cookieExpires,sameSite:this.config.sameSite,secure:this.config.secureCookie}),r.migrateFromLegacyPrefix(),this.optedOut="true"===this.cookies.get("__dl_opt_out"),this.consent=r.get("dl_consent",null),"checkoutchamp"===this.config.platform&&this.restoreFromURL(),this.identity=new I({persistNewId:this.shouldTrack()}),this.session=new C(this.config.sessionTimeout),this.attribution=new E({attributionWindow:this.config.attributionWindow,trackedParams:this.config.trackedParams,marketingAllowed:()=>this.consentAllowsMarketing()}),this.queue=new O(this.config),this.fingerprint=new L({privacyMode:this.config.privacyMode,enableFingerprinting:this.config.enableFingerprinting});const e=this.session.getSessionId();if(this.identity.setSessionId(e),this.queue.setEnabled(this.shouldTrack()),this.queue.setConsentCheck(()=>this.shouldTrack()),this.initializeAsync(),this.setupUnloadHandler(),this.setupShopifyConsentListener(),this.config.plugins)for(const t of this.config.plugins)try{t.initialize(this),this.log(`Plugin initialized: ${t.name}`)}catch(e){console.warn(`[Datalyr] Plugin '${t.name}' failed to initialize:`,e),this.trackError(e,{plugin:t.name})}this.initialized=!0,this.log("SDK initialized")}initializeAsync(){return t(this,void 0,void 0,function*(){return this.initializationPromise||(this.initializationPromise=(()=>t(this,void 0,void 0,function*(){var t,i;try{if(this.shouldTrack())try{this.attribution.getAttributionData()}catch(t){this.log("Eager attribution capture failed:",t)}try{const t=this.identity.getAnonymousId();yield e.initialize(this.config.workspaceId,t),this.userProperties=yield r.getEncrypted("dl_user_traits",{}),yield this.identity.hydrateEncryptedUserId(),this.log("Encryption initialized, user properties loaded")}catch(t){console.warn("[Datalyr] Encryption unavailable (non-secure context?); continuing WITHOUT PII-at-rest encryption:",t),this.userProperties=r.get("dl_user_traits",{})}this.config.trackSPA&&this.setupSPATracking();const s="strict"===this.config.privacyMode;!1!==this.config.enableContainer&&this.shouldTrack()&&!s&&this.consentAllowsMarketing()&&(this.container=new F({workspaceId:this.config.workspaceId,endpoint:this.config.endpoint,debug:this.config.debug,getIdentity:()=>{var t,e;return{externalId:null===(t=this.identity)||void 0===t?void 0:t.getDistinctId(),email:null===(e=this.userProperties)||void 0===e?void 0:e.email}}}),yield this.container.init().catch(t=>{this.log("Container initialization failed:",t)}),"checkoutchamp"===this.config.platform&&this.fireCheckoutChampPurchasePixel()),function(t,e,i){if(!e)return;const s=t;for(const t of N){const n=e[t];null!=n&&((null==i?void 0:i.has(t))||(s[t]=n))}}(this.config,null===(t=this.container)||void 0===t?void 0:t.getRemoteConfig(),this.explicitConfigKeys),"strict"===this.config.privacyMode&&(this.config.autoIdentify=!1);("checkoutchamp"===this.config.platform||Array.isArray(this.config.checkoutChampDomains)&&this.config.checkoutChampDomains.length>0)&&void 0===this.config.autoIdentify&&(this.config.autoIdentify=!0),!0===this.config.autoIdentify&&this.shouldTrack()&&!1!==this.shopifyMarketingConsent()&&(this.autoIdentify=new z({enabled:!0,captureFromForms:this.config.autoIdentifyForms,captureFromAPI:this.config.autoIdentifyAPI,captureFromShopify:this.config.autoIdentifyShopify,trustedDomains:this.config.autoIdentifyTrustedDomains,debug:this.config.debug}),this.autoIdentify.initialize((t,e)=>{this.log(`Auto-identified user: ${t} from ${e}`),this.identify(t,{email:t,auto_identify_source:e})})),!0===this.config.shopifyCartAttributes&&this.shouldTrack()&&!1!==this.shopifyMarketingConsent()&&this.syncShopifyCartAttributes().catch(t=>{this.log("Shopify cart attribute sync failed:",t)}),Array.isArray(this.config.checkoutChampDomains)&&this.config.checkoutChampDomains.length>0&&this.shouldTrack()&&this.syncOutboundLinkParams(this.config.checkoutChampDomains),!1!==this.config.stripePaymentLinks&&this.shouldTrack()&&this.syncStripePaymentLinks(null!==(i=this.config.stripeLinkDomains)&&void 0!==i?i:[]),!1!==this.config.stripeCheckoutSessions&&this.shouldTrack()&&this.startStripeSessionCapture(),this.initialPageViewReady=!0,this.trackInitialPageViewOnce(),this.log("Async initialization complete")}catch(t){console.error("[Datalyr] Async initialization failed:",t),this.userProperties=r.get("dl_user_traits",{})}}))()),this.initializationPromise})}ready(){return t(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("[Datalyr] SDK not initialized. Call init() first.");return this.initializationPromise||Promise.resolve()})}track(t,e={}){if(this.initialized){if(this.shouldTrack())try{this.session.updateActivity(t);const i=l(),s=this.createEventPayload(t,e,i);if(this.queue.enqueue(s),this.container&&this.container.trackToPixels(t,e,i),this.config.plugins)for(const i of this.config.plugins)if(i.track)try{i.track(t,e)}catch(e){this.trackError(e,{plugin:i.name,event:t})}this.log("Event tracked:",t)}catch(e){this.trackError(e,{event:t})}}else console.warn("[Datalyr] SDK not initialized. Call init() first.")}trackAppDownloadClick(e){return t(this,void 0,void 0,function*(){if(this.initialized){if(this.shouldTrack())if(this.track("$app_download_click",{target_platform:e.targetPlatform,app_store_url:e.appStoreUrl}),yield this.queue.forceFlush(),"android"===e.targetPlatform&&e.appStoreUrl.includes("play.google.com")){const t=this.attribution.getLastTouch(),i=new URLSearchParams;(null==t?void 0:t.clickId)&&i.set("dl_click_id",t.clickId),(null==t?void 0:t.clickIdType)&&i.set("dl_click_id_type",t.clickIdType),(null==t?void 0:t.source)&&i.set("utm_source",t.source),(null==t?void 0:t.medium)&&i.set("utm_medium",t.medium),(null==t?void 0:t.campaign)&&i.set("utm_campaign",t.campaign),(null==t?void 0:t.content)&&i.set("utm_content",t.content),(null==t?void 0:t.term)&&i.set("utm_term",t.term);try{const t=new URL(e.appStoreUrl);t.searchParams.set("referrer",i.toString()),window.location.href=t.toString()}catch(t){window.location.href=e.appStoreUrl}}else window.location.href=e.appStoreUrl}else console.warn("[Datalyr] SDK not initialized. Call init() first.")})}identityFingerprint(t,e={}){const i=Object.keys(e||{}).sort().map(t=>{let i;try{i=JSON.stringify(e[t])}catch(t){i="[unserializable]"}return`${t}=${i}`}).join("&"),s=`${this.identity.getAnonymousId()}|${t}|${i}`;let n=2166136261;for(let t=0;t<s.length;t++)n^=s.charCodeAt(t),n=Math.imul(n,16777619);return(n>>>0).toString(16)}identify(t,e={}){if(this.initialized){if(this.shouldTrack())if(t)try{const i=this.identity.getUserId();i&&i!==t&&this.reset();const s=this.identity.identify(t,e);this.userProperties=Object.assign(Object.assign({},this.userProperties),e),r.setEncrypted("dl_user_traits",this.userProperties).catch(t=>{console.error("[Datalyr] Failed to encrypt user traits - NOT storing unencrypted PII:",t),console.error("[Datalyr] User traits will only persist in memory until page reload")});const n=this.identityFingerprint(t,e);if(r.getString(Q,null)===n?this.log("Skipping redundant identify (unchanged identity):",t):(r.set(Q,n),this.track("$identify",Object.assign(Object.assign({},s),{traits:e}))),this.config.plugins)for(const i of this.config.plugins)if(i.identify)try{i.identify(t,e)}catch(t){this.trackError(t,{plugin:i.name})}this.log("User identified:",t)}catch(e){this.trackError(e,{userId:t})}else console.warn("[Datalyr] identify() called without userId")}else console.warn("[Datalyr] SDK not initialized. Call init() first.")}getQueueStats(){return this.queue?this.queue.getStats():null}page(t={}){if(!this.initialized)return void console.warn("[Datalyr] SDK not initialized. Call init() first.");if(!this.shouldTrack())return;const e=this.session.getSessionId(),i=this.attribution.getJourney(),s=i.length?i[i.length-1]:null;s&&s.sessionId===e||this.attribution.addTouchpoint(e,this.attribution.captureAttribution());const n=Object.assign({title:document.title,url:v(window.location.href),path:window.location.pathname,search:v(window.location.search),referrer:v(document.referrer)},t),o=function(){const t=document.referrer;if(!t)return{};try{const e=new URL(t);return{referrer:v(t),referrer_host:e.hostname,referrer_path:e.pathname,referrer_search:v(e.search),referrer_source:S(e.hostname)}}catch(e){return{referrer:v(t)}}}();if(Object.assign(n,o),this.config.enablePerformanceTracking){const t=this.getPerformanceMetrics();t&&(n.performance=t)}if(this.track("pageview",n),this.config.plugins)for(const t of this.config.plugins)if(t.page)try{t.page(n)}catch(e){this.trackError(e,{plugin:t.name})}}screen(t,e={}){this.initialized?this.shouldTrack()&&this.track("pageview",Object.assign({screen:t},e)):console.warn("[Datalyr] SDK not initialized. Call init() first.")}group(t,e={}){this.initialized?this.shouldTrack()&&this.track("$group",{group_id:t,traits:e}):console.warn("[Datalyr] SDK not initialized. Call init() first.")}alias(t,e){if(!this.initialized)return void console.warn("[Datalyr] SDK not initialized. Call init() first.");if(!t)return void console.warn("[Datalyr] alias() requires a non-empty userId");if(!this.shouldTrack())return;if(e&&e!==this.identity.getAnonymousId())return void console.warn("[Datalyr] alias() only accepts the current anonymous ID as previousId");const i=this.identity.getUserId();i&&i!==t&&this.reset();const s=this.identity.alias(t,e);this.track("$alias",s)}reset(){this.initialized?(this.identity.reset(),this.userProperties={},this.superProperties={},r.remove("dl_user_traits"),r.remove(Q),r.remove("dl_auto_identified_email"),r.remove("dl_journey"),r.remove("dl_first_touch"),r.remove("dl_last_touch"),this.session.createNewSession(),this.log("User reset")):console.warn("[Datalyr] SDK not initialized. Call init() first.")}getAnonymousId(){return this.identity.getAnonymousId()}getVisitorId(){return this.identity.getAnonymousId()}getStripeMetadata(){const t=this.identity.getAnonymousId();return{client_reference_id:t,metadata:{visitor_id:t}}}getWhopCheckoutMetadata(){return{visitor_id:this.identity.getAnonymousId()}}getUserId(){return this.identity.getUserId()}getDistinctId(){return this.identity.getDistinctId()}getSessionId(){return this.session.getSessionId()}startNewSession(){const t=this.session.createNewSession();return this.identity.setSessionId(t),t}getSessionData(){return this.session.getSessionData()}getAttribution(){return this.attribution.captureAttribution()}getJourney(){return this.attribution.getJourney()}setAttribution(t){const e=this.attribution.captureAttribution(),i=Object.assign(Object.assign({},e),t);this.attribution.storeLastTouch(i),this.attribution.storeFirstTouch(i),this.session.storeAttribution(i)}disposeMarketingLinkDecorators(){var t,e,i;try{null===(t=this.stripeLinksDisposer)||void 0===t||t.call(this)}catch(t){}this.stripeLinksDisposer=void 0;try{null===(e=this.stripeSessionWatcher)||void 0===e||e.stop()}catch(t){}this.stripeSessionWatcher=void 0;try{null===(i=this.outboundDisposer)||void 0===i||i.call(this)}catch(t){}this.outboundDisposer=void 0}optOut(){var t;this.initialized?(this.optedOut=!0,this.cookies.set("__dl_opt_out","true",this.config.cookieExpires),this.queue.setEnabled(!1),this.queue.clear(),this.queue.clearOffline(),null===(t=this.autoIdentify)||void 0===t||t.destroy(),this.autoIdentify=void 0,this.container&&(this.container.cleanupAllIframes(),this.container=void 0),this.disposeMarketingLinkDecorators(),this.userProperties={},r.remove("dl_user_traits"),r.remove("dl_user_id"),r.remove("dl_user_id_pii"),r.remove(Q),r.remove("dl_auto_identified_email"),r.remove("dl_journey"),r.remove("dl_first_touch"),r.remove("dl_last_touch"),this.log("User opted out")):console.warn("[Datalyr] SDK not initialized. Call init() first.")}optIn(){this.initialized?(this.optedOut=!1,this.cookies.set("__dl_opt_out","false",this.config.cookieExpires),this.queue.setEnabled(this.shouldTrack()),this.shouldTrack()&&this.identity.enablePersistence(),this.log("User opted in")):console.warn("[Datalyr] SDK not initialized. Call init() first.")}isOptedOut(){return this.optedOut}setConsent(t){var e;if(this.consent=t,r.set("dl_consent",t),!this.initialized)return;const i=this.shouldTrack();this.queue.setEnabled(i),i?this.identity.enablePersistence():(this.queue.clear(),this.queue.clearOffline(),null===(e=this.autoIdentify)||void 0===e||e.destroy(),this.autoIdentify=void 0,this.userProperties={},r.remove("dl_user_traits"),r.remove("dl_user_id"),r.remove("dl_user_id_pii"),r.remove(Q),r.remove("dl_auto_identified_email"),r.remove("dl_journey"),r.remove("dl_first_touch"),r.remove("dl_last_touch")),!this.consentAllowsMarketing()&&this.container&&(this.container.cleanupAllIframes(),this.container=void 0),this.consentAllowsMarketing()||this.disposeMarketingLinkDecorators(),this.log("Consent updated:",t)}flush(){return t(this,void 0,void 0,function*(){yield this.queue.flush()})}setSuperProperties(t){this.superProperties=Object.assign(Object.assign({},this.superProperties),t),this.log("Super properties set:",t)}unsetSuperProperty(t){delete this.superProperties[t],this.log("Super property unset:",t)}getSuperProperties(){return Object.assign({},this.superProperties)}syncShopifyCartAttributes(){return t(this,void 0,void 0,function*(){if("undefined"==typeof window||"undefined"==typeof document)return;if(!!!(window.Shopify||document.querySelector('meta[name="shopify-checkout-api-token"]')||window.location.hostname.includes(".myshopify.com")))return;const t=this.attribution.getAttributionData(),e="fbclid"===t.clickIdType?t.clickId:null,i={},s=this.identity.getAnonymousId(),n=this.cookies.get("_fbc")||t._fbc,o=this.cookies.get("_fbp")||t._fbp,r=this.cookies.get("_dl_fbclid_at");if(s&&(i._datalyr_visitor_id=s),n&&(i._datalyr_fbc=String(n)),o&&(i._datalyr_fbp=String(o)),e&&(i._datalyr_fbclid=String(e)),r&&(i._datalyr_fbclid_at=String(r)),0!==Object.keys(i).length)try{yield fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({attributes:i})}),this.log("Shopify cart attributes stamped:",Object.keys(i))}catch(t){this.log("Shopify /cart/update.js failed:",t)}})}restoreFromURL(){var t;if("undefined"!=typeof window&&"undefined"!=typeof document)try{const e=new URLSearchParams(window.location.search);let i=!1;for(const t of["_dl_vid","_dl_fbc","_dl_fbp","_dl_fbclid","_dl_fbclid_at","_dl_gclid","_dl_gclid_at"])e.has(t)&&(e.delete(t),i=!0);if(i&&"function"==typeof(null===(t=window.history)||void 0===t?void 0:t.replaceState)){const t=e.toString(),i=window.location.pathname+(t?"?"+t:"")+window.location.hash;window.history.replaceState(window.history.state,"",i)}}catch(t){this.log("restoreFromURL failed:",t)}}fireCheckoutChampPurchasePixel(){var t;if("undefined"!=typeof window)try{if(!this.container)return;const e=null===(t=window.sessionStorage)||void 0===t?void 0:t.getItem("orderData");if(!e)return;const i=JSON.parse(e)||{},s=i.orderId;if(!s)return;if(!this.container.hasMetaPixel())return void this.log("CC Purchase Pixel: Meta pixel not ready; will retry on next funnel page");const n=`__dl_cc_purchase_${s}`;if(window.sessionStorage.getItem(n))return;window.sessionStorage.setItem(n,"1");const o=`checkoutchamp_purchase_${s}`,r=Number(i.totalAmount),a={order_id:String(s),content_type:"product"};Number.isFinite(r)&&(a.value=r);const c=i.currencyCode||i.currency;c&&(a.currency=String(c)),i.productId&&(a.content_ids=[String(i.productId)]),this.container.trackToPixels("purchase",a,o),this.log("Checkout Champ Purchase Pixel co-fired (CAPI dedup):",{eventId:o,value:a.value,currency:a.currency})}catch(t){this.log("fireCheckoutChampPurchasePixel failed:",t)}}syncOutboundLinkParams(t){this.log("Checkout Champ outbound identity bridge disabled (signed token required)",t)}startStripeSessionCapture(){if(this.stripeSessionWatcher)return;const t=new U;this.stripeSessionWatcher=t,t.start(t=>{var e;if(this.shouldTrack()){this.track("$stripe_checkout_session",{stripe_session_id:t});try{null===(e=this.queue)||void 0===e||e.flush()}catch(t){}}})}syncStripePaymentLinks(t){if("undefined"==typeof window||"undefined"==typeof document)return;const e=new Set(["buy.stripe.com"]);for(const i of t){const t=String(i).trim().toLowerCase();t&&e.add(t)}const i=t=>{try{const i=new URL(t,window.location.href).hostname.toLowerCase();return e.has(i)}catch(t){return!1}},s=/^[A-Za-z0-9_-]{1,200}$/,n=()=>{const t=this.identity.getAnonymousId();return t&&s.test(t)?t:null},o=()=>{var t;if("strict"===this.config.privacyMode)return null;const e=null===(t=this.userProperties)||void 0===t?void 0:t.email;return"string"==typeof e&&e?e:null},r=t=>{if(t.href&&i(t.href))try{const e=new URL(t.href,window.location.href);let i=!1;const s=n();s&&!e.searchParams.get("client_reference_id")&&(e.searchParams.set("client_reference_id",s),i=!0);const r=o();!r||e.searchParams.get("prefilled_email")||e.searchParams.get("locked_prefilled_email")||(e.searchParams.set("prefilled_email",r),i=!0),i&&(t.href=e.toString())}catch(t){}},a=()=>{document.querySelectorAll("a[href]").forEach(t=>r(t)),(()=>{const t=n();t&&document.querySelectorAll("stripe-pricing-table, stripe-buy-button").forEach(e=>{e.getAttribute("client-reference-id")||e.setAttribute("client-reference-id",t)})})()},c=t=>{var e,s;const n=null===(e=t.target)||void 0===e?void 0:e.closest("a[href]");if(!n)return;const o=n;if(i(o.href)){r(o);try{null===(s=this.queue)||void 0===s||s.flush()}catch(t){}}};a(),document.addEventListener("click",c,!0);try{let t=null;const e=new MutationObserver(()=>{null==t&&(t=setTimeout(()=>{t=null,a()},150))});e.observe(document.documentElement,{childList:!0,subtree:!0}),this.stripeLinksDisposer=()=>{try{e.disconnect()}catch(t){}null!=t&&(clearTimeout(t),t=null),document.removeEventListener("click",c,!0)},window.addEventListener("pagehide",()=>{var t;return null===(t=this.stripeLinksDisposer)||void 0===t?void 0:t.call(this)},{once:!0})}catch(t){this.log("MutationObserver setup failed (Stripe Payment Link sync):",t)}this.log("Stripe Payment Link auto-decoration active for:",Array.from(e))}createEventPayload(t,e,i){var s;this.identity.setSessionId(this.session.getSessionId());const n=p(e),o=w({},this.superProperties,n),r=(t,e)=>{for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&!Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=e[i])};r(o,this.attribution.getAttributionData());const a=this.session.getMetrics();if(Object.assign(o,a),this.config.enableFingerprinting){const t=this.fingerprint.collect();Object.assign(o,{device_fingerprint:t})}r(o,{url:v(window.location.href),path:window.location.pathname,referrer:v(document.referrer),title:document.title,screen_width:screen.width,screen_height:screen.height,viewport_width:window.innerWidth,viewport_height:window.innerHeight});const c=Object.assign({},null!==(s=this.consent)&&void 0!==s?s:{}),h=this.shopifyAnalyticsConsent(),d=this.shopifyMarketingConsent();"boolean"==typeof h&&(c.analytics=h),"boolean"==typeof d&&(c.marketing=d),Object.keys(c).length>0&&(o.consent=c);const u=this.identity.getIdentityFields(),f=null!=i?i:l(),g=u.distinct_id,m=u.anonymous_id,y=u.visitor_id||m,_=u.session_id;return{workspace_id:this.config.workspaceId,event_id:f,event_name:t,event_data:o,source:"web",timestamp:(new Date).toISOString(),distinct_id:g,anonymous_id:m,visitor_id:y,user_id:u.user_id,canonical_id:u.canonical_id,session_id:_,resolution_method:"browser_sdk",resolution_confidence:1,sdk_version:"1.7.9",sdk_name:"datalyr-web-sdk",schema_version:1}}shouldTrack(){return!this.optedOut&&((!this.consent||!1!==this.consent.analytics)&&(!1!==this.shopifyAnalyticsConsent()&&((!this.config.respectDoNotTrack||"1"!==navigator.doNotTrack&&"1"!==window.doNotTrack&&"yes"!==navigator.doNotTrack)&&(!this.config.respectGlobalPrivacyControl||!0!==navigator.globalPrivacyControl&&!0!==window.globalPrivacyControl))))}consentAllowsMarketing(){return!1!==this.shopifyMarketingConsent()&&(!this.consent||!1!==this.consent.marketing&&!1!==this.consent.sale)}getShopifyCustomerPrivacy(){var t,e;if("undefined"==typeof window)return null;try{return null!==(e=null===(t=window.Shopify)||void 0===t?void 0:t.customerPrivacy)&&void 0!==e?e:null}catch(t){return null}}isShopifyStorefront(){var t;if("shopify"===(null===(t=this.config)||void 0===t?void 0:t.platform))return!0;if("undefined"==typeof window)return!1;try{return Boolean(window.Shopify)||window.location.hostname.toLowerCase().endsWith(".myshopify.com")}catch(t){return!1}}shopifyAnalyticsConsent(){try{const t=this.getShopifyCustomerPrivacy();if(!t)return!this.isShopifyStorefront()&&null;if("function"==typeof t.analyticsProcessingAllowed){const e=t.analyticsProcessingAllowed();return"boolean"==typeof e?e:null}if("function"==typeof t.userCanBeTracked){const e=t.userCanBeTracked();return"boolean"==typeof e?e:null}return!this.isShopifyStorefront()&&null}catch(t){return!this.isShopifyStorefront()&&null}}shopifyMarketingConsent(){try{const t=this.getShopifyCustomerPrivacy();if(!t||"function"!=typeof t.marketingAllowed)return!this.isShopifyStorefront()&&null;const e=t.marketingAllowed();return"boolean"==typeof e?e:!this.isShopifyStorefront()&&null}catch(t){return!this.isShopifyStorefront()&&null}}setupShopifyConsentListener(){if("undefined"!=typeof document)try{this.shopifyConsentHandler=()=>{try{this.onShopifyConsentChanged()}catch(t){this.log("Shopify consent change handling failed:",t)}},document.addEventListener("visitorConsentCollected",this.shopifyConsentHandler);const t=window.Shopify;t&&"function"==typeof t.loadFeatures&&t.loadFeatures([{name:"consent-tracking-api",version:"0.1"}],t=>{if(t)this.log("Shopify loadFeatures(consent-tracking-api) failed:",t);else try{this.onShopifyConsentChanged()}catch(t){this.log("Shopify post-load consent eval failed:",t)}})}catch(t){this.log("Shopify consent listener setup failed:",t)}}onShopifyConsentChanged(){const t=this.shouldTrack();this.queue.setEnabled(t),t&&this.identity.enablePersistence(),t&&this.trackInitialPageViewOnce(),t||(this.queue.clear(),this.queue.clearOffline());const e=!1===this.shopifyMarketingConsent();t&&!e||!this.autoIdentify||(this.autoIdentify.destroy(),this.autoIdentify=void 0),!this.consentAllowsMarketing()&&this.container&&(this.container.cleanupAllIframes(),this.container=void 0),this.consentAllowsMarketing()||this.disposeMarketingLinkDecorators(),t&&!e&&!0===this.config.shopifyCartAttributes&&this.syncShopifyCartAttributes().catch(t=>{this.log("Shopify cart attribute sync failed:",t)}),this.log("Shopify consent collected — analytics allowed:",t,"— marketing blocked:",e)}trackInitialPageViewOnce(){this.initialPageViewReady&&!this.initialPageViewSent&&this.config.trackPageViews&&this.initialized&&this.shouldTrack()&&(this.initialPageViewSent=!0,this.page())}setupSPATracking(){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const t=this;this.lastSpaPath=window.location.pathname+window.location.search+window.location.hash,history.pushState=function(...e){t.originalPushState.apply(history,e),setTimeout(()=>t.handleSpaNavigation(),0)},history.replaceState=function(...e){t.originalReplaceState.apply(history,e),setTimeout(()=>t.handleSpaNavigation(),0)},this.popstateHandler=()=>{setTimeout(()=>t.handleSpaNavigation(),0)},window.addEventListener("popstate",this.popstateHandler),this.hashchangeHandler=()=>{t.handleSpaNavigation()},window.addEventListener("hashchange",this.hashchangeHandler)}handleSpaNavigation(){const t=window.location.pathname+window.location.search+window.location.hash;t!==this.lastSpaPath&&(this.lastSpaPath=t,this.attribution.clearCache(),this.page())}setupUnloadHandler(){this.unloadHandler=()=>{this.queue.forceFlush(!0)},this.visibilityHandler=()=>{"hidden"===document.visibilityState&&this.queue.forceFlush(!1)},window.addEventListener("beforeunload",this.unloadHandler),window.addEventListener("pagehide",this.unloadHandler),window.addEventListener("visibilitychange",this.visibilityHandler)}getPerformanceMetrics(){if(!this.config.enablePerformanceTracking)return null;const t={};try{if(performance&&"function"==typeof performance.getEntriesByType){const e=performance.getEntriesByType("navigation"),i=e&&e[0];i&&(t.pageLoadTime=Math.round(i.loadEventEnd),t.domReadyTime=Math.round(i.domContentLoadedEventEnd),t.firstByteTime=Math.round(i.responseStart),t.dnsTime=Math.round(i.domainLookupEnd-i.domainLookupStart),t.tcpTime=Math.round(i.connectEnd-i.connectStart),t.requestTime=Math.round(i.responseEnd-i.requestStart),t.timeOnPage=Math.round(performance.now()))}}catch(t){this.trackError(t,{context:"performance_metrics"})}return Object.keys(t).length>0?t:null}trackError(t,e){const i={message:t.message||String(t),stack:t.stack,context:e,timestamp:(new Date).toISOString(),url:v(window.location.href)};this.errors.push(i),this.errors.length>this.MAX_ERRORS&&(this.errors=this.errors.slice(-this.MAX_ERRORS)),this.config.debug&&console.error("[Datalyr Error]",i)}getErrors(){return[...this.errors]}getNetworkStatus(){return this.queue.getNetworkStatus()}loadScript(t){this.container&&this.container.triggerCustomScript(t)}getLoadedScripts(){return this.container?this.container.getLoadedScripts():[]}log(...t){var e;(null===(e=this.config)||void 0===e?void 0:e.debug)&&console.log("[Datalyr]",...t)}destroy(){this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),this.hashchangeHandler&&window.removeEventListener("hashchange",this.hashchangeHandler),this.unloadHandler&&(window.removeEventListener("beforeunload",this.unloadHandler),window.removeEventListener("pagehide",this.unloadHandler),this.unloadHandler=void 0),this.visibilityHandler&&(window.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=void 0),this.shopifyConsentHandler&&(document.removeEventListener("visitorConsentCollected",this.shopifyConsentHandler),this.shopifyConsentHandler=void 0),this.outboundDisposer&&(this.outboundDisposer(),this.outboundDisposer=void 0),this.stripeLinksDisposer&&(this.stripeLinksDisposer(),this.stripeLinksDisposer=void 0),this.stripeSessionWatcher&&(this.stripeSessionWatcher.stop(),this.stripeSessionWatcher=void 0),this.queue&&this.queue.destroy(),this.session&&this.session.destroy(),this.container&&this.container.cleanupAllIframes(),this.autoIdentify&&this.autoIdentify.destroy(),e.destroy(),this.initializationPromise=null,this.container=void 0,this.autoIdentify=void 0,this.lastSpaPath=null,this.initialPageViewReady=!1,this.initialPageViewSent=!1,this.superProperties={},this.userProperties={},this.errors=[],this.initialized=!1,this.log("SDK destroyed")}}function B(){return new H}const V="undefined"!=typeof window&&window.datalyr||B();"undefined"!=typeof window&&(window.datalyr=V);export{B as createDatalyrInstance,V as datalyr,V as default};
2
2
  //# sourceMappingURL=datalyr.esm.min.js.map