@deriv-com/analytics 1.38.9 → 1.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/browser/analytics.bundle.global.js +12 -12
  2. package/dist/browser/analytics.bundle.global.js.map +1 -1
  3. package/dist/browser/analytics.esm.mjs +1 -1
  4. package/dist/browser/analytics.esm.mjs.map +1 -1
  5. package/dist/{chunk-D2MKQCJB.mjs → chunk-44P2MMGV.mjs} +3 -3
  6. package/dist/{chunk-D2MKQCJB.mjs.map → chunk-44P2MMGV.mjs.map} +1 -1
  7. package/dist/{chunk-YGU4ZMIH.mjs → chunk-FY3NPDUL.mjs} +2 -2
  8. package/dist/chunk-GGU2UVKH.mjs +4 -0
  9. package/dist/chunk-GGU2UVKH.mjs.map +1 -0
  10. package/dist/chunk-J3V5QNIH.js +4 -0
  11. package/dist/chunk-J3V5QNIH.js.map +1 -0
  12. package/dist/{chunk-7CT4XR74.mjs → chunk-LIPHY7JK.mjs} +3 -3
  13. package/dist/{chunk-7CT4XR74.mjs.map → chunk-LIPHY7JK.mjs.map} +1 -1
  14. package/dist/{chunk-FE5YWK6A.js → chunk-SQ6Q4Z5S.js} +3 -3
  15. package/dist/{chunk-FE5YWK6A.js.map → chunk-SQ6Q4Z5S.js.map} +1 -1
  16. package/dist/chunk-UG2YL4OB.mjs +9 -0
  17. package/dist/chunk-UG2YL4OB.mjs.map +1 -0
  18. package/dist/{chunk-ILN7DKKL.js → chunk-Y3QT7NAG.js} +3 -3
  19. package/dist/{chunk-ILN7DKKL.js.map → chunk-Y3QT7NAG.js.map} +1 -1
  20. package/dist/{growthbook-3K6VUME4.mjs → growthbook-IRLKT4KH.mjs} +2 -2
  21. package/dist/index.d.mts +11 -3
  22. package/dist/index.d.ts +11 -3
  23. package/dist/index.js +2 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/index.mjs +2 -2
  26. package/dist/index.mjs.map +1 -1
  27. package/dist/metafile-cjs.json +1 -1
  28. package/dist/metafile-esm.json +1 -1
  29. package/dist/metafile-iife.json +1 -1
  30. package/dist/posthog-2YOT34O2.mjs +6 -0
  31. package/dist/posthog-2YOT34O2.mjs.map +1 -0
  32. package/dist/{posthog-Ds4g1sJf.d.mts → posthog-CRa194Jm.d.mts} +8 -3
  33. package/dist/{posthog-DvDj4azD.d.ts → posthog-CZnsy0at.d.ts} +8 -3
  34. package/dist/providers/growthbook/index.js +2 -2
  35. package/dist/providers/growthbook/index.mjs +1 -1
  36. package/dist/providers/posthog/index.d.mts +1 -1
  37. package/dist/providers/posthog/index.d.ts +1 -1
  38. package/dist/providers/posthog/index.js +2 -2
  39. package/dist/providers/posthog/index.js.map +1 -1
  40. package/dist/providers/posthog/index.mjs +2 -2
  41. package/dist/providers/posthog/index.mjs.map +1 -1
  42. package/dist/providers/rudderstack/index.js +1 -1
  43. package/dist/providers/rudderstack/index.mjs +1 -1
  44. package/dist/utils/analytics-cache/index.js +1 -1
  45. package/dist/utils/analytics-cache/index.mjs +1 -1
  46. package/package.json +1 -1
  47. package/dist/chunk-BVGYK54Z.js +0 -4
  48. package/dist/chunk-BVGYK54Z.js.map +0 -1
  49. package/dist/chunk-ID2GN2PS.mjs +0 -4
  50. package/dist/chunk-ID2GN2PS.mjs.map +0 -1
  51. package/dist/chunk-OB6HH25Z.mjs +0 -9
  52. package/dist/chunk-OB6HH25Z.mjs.map +0 -1
  53. package/dist/posthog-ANAV4RFJ.mjs +0 -6
  54. package/dist/posthog-ANAV4RFJ.mjs.map +0 -1
  55. /package/dist/{chunk-YGU4ZMIH.mjs.map → chunk-FY3NPDUL.mjs.map} +0 -0
  56. /package/dist/{growthbook-3K6VUME4.mjs.map → growthbook-IRLKT4KH.mjs.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  /* @deriv-com/analytics - Browser ESM Bundle (RudderStack + PostHog) - Built with tsup */
2
- import{a as k}from"./chunk-OB6HH25Z.mjs";function C(t){return t!=null&&typeof t=="object"&&t["@@functional/placeholder"]===!0}function Z(t){return function e(n){return arguments.length===0||C(n)?e:t.apply(this,arguments)}}function ne(t){return function e(n,s){switch(arguments.length){case 0:return e;case 1:return C(n)?e:Z(function(r){return t(n,r)});default:return C(n)&&C(s)?e:C(n)?Z(function(r){return t(r,s)}):C(s)?Z(function(r){return t(n,r)}):t(n,s)}}}function jt(t){return function e(n,s,r){switch(arguments.length){case 0:return e;case 1:return C(n)?e:ne(function(i,a){return t(n,i,a)});case 2:return C(n)&&C(s)?e:C(n)?ne(function(i,a){return t(i,s,a)}):C(s)?ne(function(i,a){return t(n,i,a)}):Z(function(i){return t(n,s,i)});default:return C(n)&&C(s)&&C(r)?e:C(n)&&C(s)?ne(function(i,a){return t(i,a,r)}):C(n)&&C(r)?ne(function(i,a){return t(i,s,a)}):C(s)&&C(r)?ne(function(i,a){return t(n,i,a)}):C(n)?Z(function(i){return t(i,s,r)}):C(s)?Z(function(i){return t(n,i,r)}):C(r)?Z(function(i){return t(n,s,i)}):t(n,s,r)}}}function Le(t,e){return Object.prototype.hasOwnProperty.call(e,t)}var xs=Z(function(e){return e===null?"Null":e===void 0?"Undefined":Object.prototype.toString.call(e).slice(8,-1)});function en(t){return Object.prototype.toString.call(t)==="[object Object]"}var Gs=Number.isInteger||function(e){return e<<0===e};function Fs(t,e){var n=t<0?e.length+t:t;return e[n]}function Vs(t){return new RegExp(t.source,t.flags?t.flags:(t.global?"g":"")+(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.sticky?"y":"")+(t.unicode?"u":"")+(t.dotAll?"s":""))}function xn(t,e,n){if(n||(n=new Hs),js(t))return t;var s=function(i){var a=n.get(t);if(a)return a;n.set(t,i);for(var l in t)Object.prototype.hasOwnProperty.call(t,l)&&(i[l]=xn(t[l],!0,n));return i};switch(xs(t)){case"Object":return s(Object.create(Object.getPrototypeOf(t)));case"Array":return s(Array(t.length));case"Date":return new Date(t.valueOf());case"RegExp":return Vs(t);case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"BigInt64Array":case"BigUint64Array":return t.slice();default:return t}}function js(t){var e=typeof t;return t==null||e!="object"&&e!="function"}var Hs=(function(){function t(){this.map={},this.length=0}return t.prototype.set=function(e,n){var s=this.hash(e),r=this.map[s];r||(this.map[s]=r=[]),r.push([e,n]),this.length+=1},t.prototype.hash=function(e){var n=[];for(var s in e)n.push(Object.prototype.toString.call(e[s]));return n.join()},t.prototype.get=function(e){if(this.length<=180){for(var n in this.map)for(var a=this.map[n],s=0;s<a.length;s+=1){var r=a[s];if(r[0]===e)return r[1]}return}var i=this.hash(e),a=this.map[i];if(a)for(var s=0;s<a.length;s+=1){var r=a[s];if(r[0]===e)return r[1]}},t})(),b=Z(function(e){return e!=null&&typeof e.clone=="function"?e.clone():xn(e)});function Ks(t,e){for(var n=e,s=0;s<t.length;s+=1){if(n==null)return;var r=t[s];Gs(r)?n=Fs(r,n):n=n[r]}return n}var Qs=jt(function(e,n,s){var r={},i;n=n||{},s=s||{};for(i in n)Le(i,n)&&(r[i]=Le(i,s)?e(i,n[i],s[i]):n[i]);for(i in s)Le(i,s)&&!Le(i,r)&&(r[i]=s[i]);return r}),zs=jt(function t(e,n,s){return Qs(function(r,i,a){return en(i)&&en(a)?t(e,i,a):e(r,i,a)},n,s)}),Ws=jt(function(e,n,s){return zs(function(r,i,a){return e(i,a)},n,s)}),Xs=ne(Ks),Gn=ne(function(e,n){var s={};for(var r in n)e(n[r],r,n)&&(s[r]=n[r]);return s}),m=t=>typeof t=="function"&&!!(t.constructor&&t.call&&t.apply),_=t=>typeof t=="string",G=t=>t===null,w=t=>typeof t>"u",Q=t=>G(t)||w(t),Ys=t=>typeof t=="bigint",O=t=>!w(t),ve=t=>!Q(t),qs=t=>ve(t)&&t!=="",Ht=t=>{switch(Object.prototype.toString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return t instanceof Error}},Js=t=>typeof t=="boolean",ht=(t,e)=>{let n=e.split(".");return Xs(n,t)},Zs=(t,e)=>!!ht(t,e),er=t=>typeof t=="object",tr=t=>!G(t)&&er(t)&&!Array.isArray(t),N=t=>!G(t)&&Object.prototype.toString.call(t)==="[object Object]",nr=(t,e)=>{if(!Array.isArray(t)||!Array.isArray(e))return b(e);let n=b(t);return e.forEach((s,r)=>{n[r]=Array.isArray(s)||tr(s)?L(n[r],s):s}),n},L=(t,e)=>Ws(nr,t,e),ee=t=>N(t)&&Object.keys(t).length>0,Ae=t=>{let e=Gn(O,t);return Object.keys(e).forEach(n=>{let s=e[n];N(s)&&(e[n]=Ae(s))}),e},Qe=t=>{let e=Gn(ve,t);return Object.keys(e).forEach(n=>{let s=e[n];N(s)&&(e[n]=Qe(s))}),e},Y=t=>{if(ee(t))return Qe(t)},z=(t,e)=>typeof t=="boolean"?t:e,Kt=t=>(Object.getOwnPropertyNames(t).forEach(function(e){t[e]&&typeof t[e]=="object"&&Kt(t[e])}),Object.freeze(t)),sr=t=>t.replace(/^\s+|\s+$/gm,""),tn=t=>t.replace(/^\.+/,""),ze=t=>{let e=t;if(!_(t)&&!Q(t))try{e=JSON.stringify(t)}catch{e=null}return e},rr=t=>{let e=Array.from(t,n=>String.fromCodePoint(n)).join("");return globalThis.btoa(e)},ir=t=>rr(new TextEncoder().encode(t)),We=(t,e,n,s,r)=>{let i={category:t,name:e,properties:n,options:s,callback:void 0};m(r)&&(i.callback=r),m(s)&&(i.category=t,i.name=e,i.properties=n,i.options=void 0,i.callback=s),m(n)&&(i.category=t,i.name=e,i.properties=void 0,i.options=void 0,i.callback=n),m(e)&&(i.category=t,i.name=void 0,i.properties=void 0,i.options=void 0,i.callback=e),m(t)&&(i.category=void 0,i.name=void 0,i.properties=void 0,i.options=void 0,i.callback=t),N(t)?(i.name=void 0,i.category=void 0,i.properties=t,m(e)?i.options=void 0:i.options=e):N(e)&&(i.name=void 0,i.properties=e,m(n)?i.options=void 0:i.options=n),_(t)&&!_(e)&&(i.category=void 0,i.name=t),O(i.category)||(i.category=void 0),O(i.name)||(i.name=void 0),i.properties=i.properties?b(i.properties):{},O(i.options)?i.options=b(i.options):i.options=void 0;let a=_(i.name)?i.name:i.properties.name,l=_(i.category)?i.category:i.properties.category;return i.properties=L(N(i.properties)?i.properties:{},{...a&&{name:a},...l&&{category:l}}),i},Qt=(t,e,n,s)=>{let r={name:t,properties:e,options:n,callback:void 0};return m(s)&&(r.callback=s),m(n)&&(r.properties=e,r.options=void 0,r.callback=n),m(e)&&(r.properties=void 0,r.options=void 0,r.callback=e),r.properties=ve(r.properties)?b(r.properties):{},O(r.options)?r.options=b(r.options):r.options=void 0,r},Fn=(t,e,n,s)=>{let r={userId:t,traits:e,options:n,callback:void 0};return m(s)&&(r.callback=s),m(n)&&(r.userId=t,r.traits=e,r.options=void 0,r.callback=n),m(e)&&(r.userId=t,r.traits=void 0,r.options=void 0,r.callback=e),(N(t)||G(t))&&(r.userId=null,r.traits=t,m(e)?r.options=void 0:r.options=e),r.userId=ze(r.userId),N(r.traits)?r.traits=b(r.traits):r.traits=void 0,O(r.options)?r.options=b(r.options):r.options=void 0,r},Vn=(t,e,n,s)=>{let r={to:t,from:e,options:n,callback:void 0};return m(s)&&(r.callback=s),m(n)&&(r.to=t,r.from=e,r.options=void 0,r.callback=n),m(e)?(r.to=t,r.from=void 0,r.options=void 0,r.callback=e):(N(e)||G(e))&&(r.to=t,r.from=void 0,r.options=e),O(r.to)&&(r.to=ze(r.to)),O(r.from)?r.from=ze(r.from):r.from=void 0,O(r.options)?r.options=b(r.options):r.options=void 0,r},jn=(t,e,n,s)=>{let r={groupId:t,traits:e,options:n,callback:void 0};return m(s)&&(r.callback=s),m(n)&&(r.groupId=t,r.traits=e,r.options=void 0,r.callback=n),m(e)&&(r.groupId=t,r.traits=void 0,r.options=void 0,r.callback=e),(N(t)||G(t))&&(r.groupId=null,r.traits=t,m(e)?r.options=void 0:r.options=e),r.groupId=ze(r.groupId),N(r.traits)?r.traits=b(r.traits):r.traits=void 0,O(r.options)?r.options=b(r.options):r.options=void 0,r},it=(function(t){return t.UNLOADED="Page Unloaded",t})({}),zt="API",pt="CapabilitiesManager",j="ConfigManager",Hn="EventManager",Ie="PluginsManager",ae="UserSessionManager",Re="ErrorHandler",ge="PluginEngine",or="StoreManager",ot=`Ready${zt}`,ar=`Load${zt}`,lr="HttpClient",cr="RudderStackAnalytics",we="AnalyticsCore";function ur(t){return crypto.getRandomValues(new Uint8Array(t))}var nn=4096,Me=[],se=0,at;for(;se<256;se++)Me[se]=(se+256).toString(16).substring(1);function dr(){(!at||se+16>nn)&&(at=ur(nn),se=0);for(var t=0,e,n="";t<16;t++)e=at[se+t],t==6?n+=Me[e&15|64]:t==8?n+=Me[e&63|128]:n+=Me[e],t&1&&t>1&&t<11&&(n+="-");return se+=16,n}var ue=256,Be=[],Ue;for(;ue--;)Be[ue]=(ue+256).toString(16).substring(1);function gr(){var t=0,e,n="";if(!Ue||ue+16>256){for(Ue=Array(t=256);t--;)Ue[t]=256*Math.random()|0;t=ue=0}for(;t<16;t++)e=Ue[ue+t],t==6?n+=Be[e&15|64]:t==8?n+=Be[e&63|128]:n+=Be[e],t&1&&t>1&&t<11&&(n+="-");return ue++,n}var fr=()=>!Q(globalThis.crypto)&&m(globalThis.crypto.getRandomValues),Ze=()=>fr()?dr():gr(),hr=()=>!!window.chrome?.runtime?.id,Kn=()=>_(globalThis.navigator.userAgent)&&/Trident.*rv:11\./.test(globalThis.navigator.userAgent),pr=(t,e=!1)=>{let n=!1,s=!1;function r(){n||(n=!0,t(s),setTimeout(()=>{n=!1},0))}(e||Kn())&&globalThis.addEventListener("beforeunload",()=>{s=!1,r()}),globalThis.addEventListener("blur",()=>{s=!0,r()}),globalThis.addEventListener("focus",()=>{n=!1}),document.addEventListener("pagehide",()=>{s=document.visibilityState==="hidden",r()}),document.addEventListener("visibilitychange",()=>{s=!0,document.visibilityState==="hidden"?r():n=!1})},Qn=t=>t.toISOString(),vr=()=>Qn(new Date),S=":: ",mr=t=>`A script with the id "${t}" is already loaded. Skipping the loading of this script to prevent conflicts`,sn=(t,e,n)=>`Unable to load (${_(n)?n:n.type}) the script with the id "${t}" from URL "${e}"`,Er=(t,e,n)=>`A timeout of ${n} ms occurred while trying to load the script with id "${t}" from URL "${e}"`,yr=(t,e)=>`${t}${S}A circular reference has been detected in the object and the property "${e}" has been dropped from the output.`,Sr="Failed to convert the value to a JSON string.",br="Failed to encode the cookie data.",Ir=(t,e)=>`${t}${S}The "${e}" storage type is `,Tr="JSONStringify",Ar="[BigInt]",zn="[Circular Reference]",Rr=(t,e,n)=>{let s=[];return function(r,i){if(!e?.includes(r)&&!(t&&Q(i))){if(typeof i!="object"||G(i))return i;for(;s.length>0&&s[s.length-1]!==this;)s.pop();return s.includes(i)?(n?.warn(yr(Tr,r)),zn):(s.push(i),i)}}},K=(t,e,n,s)=>{try{return JSON.stringify(t,Rr(e,n,s))}catch(r){return s?.warn(Sr,r),null}},Or=t=>{let e=[];return function(s,r){if(Ys(r))return Ar;for(;e.length>0&&e[e.length-1]!==this;)e.pop();return e.includes(r)?zn:(e.push(r),r)}},Wn=(t,e)=>{let n=Array.isArray(t)?[]:{};for(let s in t)if(Object.hasOwnProperty.call(t,s)){let r=t[s],i=e.call(t,s,r);N(i)||Array.isArray(i)?n[s]=Wn(i,e):n[s]=i}return n},I=(t,e)=>{let n=Or(),s=n.call(t,"",t);return N(t)||Array.isArray(t)?Wn(t,n):s},xe="[SDK DISPATCHED ERROR]",et=t=>{let{stack:e,stacktrace:n,"opera#sourceloc":s}=t,r=e??n??s;if(r&&typeof r=="string")return r},Wt=(t,e)=>{if(!Ht(t))return new Error(`${e}: ${K(t)}`);try{let n=t.constructor,s=new n(`${e}: ${t.message}`),r=et(t);return r&&(s.stack=r),Object.getOwnPropertyNames(t).forEach(i=>{if(i!=="message"&&i!=="stack"&&i!=="name")try{s[i]=t[i]}catch{}}),s}catch{return new Error(`${e}: ${K(t)}`)}},D=t=>{if(Ht(t)){let e=et(t);if(e){let{stack:n,stacktrace:s,"opera#sourceloc":r}=t;switch(e){case n:t.stack=`${n}
2
+ import{a as k}from"./chunk-UG2YL4OB.mjs";function C(t){return t!=null&&typeof t=="object"&&t["@@functional/placeholder"]===!0}function Z(t){return function e(n){return arguments.length===0||C(n)?e:t.apply(this,arguments)}}function ne(t){return function e(n,s){switch(arguments.length){case 0:return e;case 1:return C(n)?e:Z(function(r){return t(n,r)});default:return C(n)&&C(s)?e:C(n)?Z(function(r){return t(r,s)}):C(s)?Z(function(r){return t(n,r)}):t(n,s)}}}function jt(t){return function e(n,s,r){switch(arguments.length){case 0:return e;case 1:return C(n)?e:ne(function(i,a){return t(n,i,a)});case 2:return C(n)&&C(s)?e:C(n)?ne(function(i,a){return t(i,s,a)}):C(s)?ne(function(i,a){return t(n,i,a)}):Z(function(i){return t(n,s,i)});default:return C(n)&&C(s)&&C(r)?e:C(n)&&C(s)?ne(function(i,a){return t(i,a,r)}):C(n)&&C(r)?ne(function(i,a){return t(i,s,a)}):C(s)&&C(r)?ne(function(i,a){return t(n,i,a)}):C(n)?Z(function(i){return t(i,s,r)}):C(s)?Z(function(i){return t(n,i,r)}):C(r)?Z(function(i){return t(n,s,i)}):t(n,s,r)}}}function Le(t,e){return Object.prototype.hasOwnProperty.call(e,t)}var xs=Z(function(e){return e===null?"Null":e===void 0?"Undefined":Object.prototype.toString.call(e).slice(8,-1)});function en(t){return Object.prototype.toString.call(t)==="[object Object]"}var Gs=Number.isInteger||function(e){return e<<0===e};function Fs(t,e){var n=t<0?e.length+t:t;return e[n]}function Vs(t){return new RegExp(t.source,t.flags?t.flags:(t.global?"g":"")+(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.sticky?"y":"")+(t.unicode?"u":"")+(t.dotAll?"s":""))}function xn(t,e,n){if(n||(n=new Hs),js(t))return t;var s=function(i){var a=n.get(t);if(a)return a;n.set(t,i);for(var l in t)Object.prototype.hasOwnProperty.call(t,l)&&(i[l]=xn(t[l],!0,n));return i};switch(xs(t)){case"Object":return s(Object.create(Object.getPrototypeOf(t)));case"Array":return s(Array(t.length));case"Date":return new Date(t.valueOf());case"RegExp":return Vs(t);case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"BigInt64Array":case"BigUint64Array":return t.slice();default:return t}}function js(t){var e=typeof t;return t==null||e!="object"&&e!="function"}var Hs=(function(){function t(){this.map={},this.length=0}return t.prototype.set=function(e,n){var s=this.hash(e),r=this.map[s];r||(this.map[s]=r=[]),r.push([e,n]),this.length+=1},t.prototype.hash=function(e){var n=[];for(var s in e)n.push(Object.prototype.toString.call(e[s]));return n.join()},t.prototype.get=function(e){if(this.length<=180){for(var n in this.map)for(var a=this.map[n],s=0;s<a.length;s+=1){var r=a[s];if(r[0]===e)return r[1]}return}var i=this.hash(e),a=this.map[i];if(a)for(var s=0;s<a.length;s+=1){var r=a[s];if(r[0]===e)return r[1]}},t})(),b=Z(function(e){return e!=null&&typeof e.clone=="function"?e.clone():xn(e)});function Ks(t,e){for(var n=e,s=0;s<t.length;s+=1){if(n==null)return;var r=t[s];Gs(r)?n=Fs(r,n):n=n[r]}return n}var Qs=jt(function(e,n,s){var r={},i;n=n||{},s=s||{};for(i in n)Le(i,n)&&(r[i]=Le(i,s)?e(i,n[i],s[i]):n[i]);for(i in s)Le(i,s)&&!Le(i,r)&&(r[i]=s[i]);return r}),zs=jt(function t(e,n,s){return Qs(function(r,i,a){return en(i)&&en(a)?t(e,i,a):e(r,i,a)},n,s)}),Ws=jt(function(e,n,s){return zs(function(r,i,a){return e(i,a)},n,s)}),Xs=ne(Ks),Gn=ne(function(e,n){var s={};for(var r in n)e(n[r],r,n)&&(s[r]=n[r]);return s}),m=t=>typeof t=="function"&&!!(t.constructor&&t.call&&t.apply),_=t=>typeof t=="string",G=t=>t===null,w=t=>typeof t>"u",Q=t=>G(t)||w(t),Ys=t=>typeof t=="bigint",O=t=>!w(t),ve=t=>!Q(t),qs=t=>ve(t)&&t!=="",Ht=t=>{switch(Object.prototype.toString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return t instanceof Error}},Js=t=>typeof t=="boolean",ht=(t,e)=>{let n=e.split(".");return Xs(n,t)},Zs=(t,e)=>!!ht(t,e),er=t=>typeof t=="object",tr=t=>!G(t)&&er(t)&&!Array.isArray(t),N=t=>!G(t)&&Object.prototype.toString.call(t)==="[object Object]",nr=(t,e)=>{if(!Array.isArray(t)||!Array.isArray(e))return b(e);let n=b(t);return e.forEach((s,r)=>{n[r]=Array.isArray(s)||tr(s)?L(n[r],s):s}),n},L=(t,e)=>Ws(nr,t,e),ee=t=>N(t)&&Object.keys(t).length>0,Ae=t=>{let e=Gn(O,t);return Object.keys(e).forEach(n=>{let s=e[n];N(s)&&(e[n]=Ae(s))}),e},Qe=t=>{let e=Gn(ve,t);return Object.keys(e).forEach(n=>{let s=e[n];N(s)&&(e[n]=Qe(s))}),e},Y=t=>{if(ee(t))return Qe(t)},z=(t,e)=>typeof t=="boolean"?t:e,Kt=t=>(Object.getOwnPropertyNames(t).forEach(function(e){t[e]&&typeof t[e]=="object"&&Kt(t[e])}),Object.freeze(t)),sr=t=>t.replace(/^\s+|\s+$/gm,""),tn=t=>t.replace(/^\.+/,""),ze=t=>{let e=t;if(!_(t)&&!Q(t))try{e=JSON.stringify(t)}catch{e=null}return e},rr=t=>{let e=Array.from(t,n=>String.fromCodePoint(n)).join("");return globalThis.btoa(e)},ir=t=>rr(new TextEncoder().encode(t)),We=(t,e,n,s,r)=>{let i={category:t,name:e,properties:n,options:s,callback:void 0};m(r)&&(i.callback=r),m(s)&&(i.category=t,i.name=e,i.properties=n,i.options=void 0,i.callback=s),m(n)&&(i.category=t,i.name=e,i.properties=void 0,i.options=void 0,i.callback=n),m(e)&&(i.category=t,i.name=void 0,i.properties=void 0,i.options=void 0,i.callback=e),m(t)&&(i.category=void 0,i.name=void 0,i.properties=void 0,i.options=void 0,i.callback=t),N(t)?(i.name=void 0,i.category=void 0,i.properties=t,m(e)?i.options=void 0:i.options=e):N(e)&&(i.name=void 0,i.properties=e,m(n)?i.options=void 0:i.options=n),_(t)&&!_(e)&&(i.category=void 0,i.name=t),O(i.category)||(i.category=void 0),O(i.name)||(i.name=void 0),i.properties=i.properties?b(i.properties):{},O(i.options)?i.options=b(i.options):i.options=void 0;let a=_(i.name)?i.name:i.properties.name,l=_(i.category)?i.category:i.properties.category;return i.properties=L(N(i.properties)?i.properties:{},{...a&&{name:a},...l&&{category:l}}),i},Qt=(t,e,n,s)=>{let r={name:t,properties:e,options:n,callback:void 0};return m(s)&&(r.callback=s),m(n)&&(r.properties=e,r.options=void 0,r.callback=n),m(e)&&(r.properties=void 0,r.options=void 0,r.callback=e),r.properties=ve(r.properties)?b(r.properties):{},O(r.options)?r.options=b(r.options):r.options=void 0,r},Fn=(t,e,n,s)=>{let r={userId:t,traits:e,options:n,callback:void 0};return m(s)&&(r.callback=s),m(n)&&(r.userId=t,r.traits=e,r.options=void 0,r.callback=n),m(e)&&(r.userId=t,r.traits=void 0,r.options=void 0,r.callback=e),(N(t)||G(t))&&(r.userId=null,r.traits=t,m(e)?r.options=void 0:r.options=e),r.userId=ze(r.userId),N(r.traits)?r.traits=b(r.traits):r.traits=void 0,O(r.options)?r.options=b(r.options):r.options=void 0,r},Vn=(t,e,n,s)=>{let r={to:t,from:e,options:n,callback:void 0};return m(s)&&(r.callback=s),m(n)&&(r.to=t,r.from=e,r.options=void 0,r.callback=n),m(e)?(r.to=t,r.from=void 0,r.options=void 0,r.callback=e):(N(e)||G(e))&&(r.to=t,r.from=void 0,r.options=e),O(r.to)&&(r.to=ze(r.to)),O(r.from)?r.from=ze(r.from):r.from=void 0,O(r.options)?r.options=b(r.options):r.options=void 0,r},jn=(t,e,n,s)=>{let r={groupId:t,traits:e,options:n,callback:void 0};return m(s)&&(r.callback=s),m(n)&&(r.groupId=t,r.traits=e,r.options=void 0,r.callback=n),m(e)&&(r.groupId=t,r.traits=void 0,r.options=void 0,r.callback=e),(N(t)||G(t))&&(r.groupId=null,r.traits=t,m(e)?r.options=void 0:r.options=e),r.groupId=ze(r.groupId),N(r.traits)?r.traits=b(r.traits):r.traits=void 0,O(r.options)?r.options=b(r.options):r.options=void 0,r},it=(function(t){return t.UNLOADED="Page Unloaded",t})({}),zt="API",pt="CapabilitiesManager",j="ConfigManager",Hn="EventManager",Ie="PluginsManager",ae="UserSessionManager",Re="ErrorHandler",ge="PluginEngine",or="StoreManager",ot=`Ready${zt}`,ar=`Load${zt}`,lr="HttpClient",cr="RudderStackAnalytics",we="AnalyticsCore";function ur(t){return crypto.getRandomValues(new Uint8Array(t))}var nn=4096,Me=[],se=0,at;for(;se<256;se++)Me[se]=(se+256).toString(16).substring(1);function dr(){(!at||se+16>nn)&&(at=ur(nn),se=0);for(var t=0,e,n="";t<16;t++)e=at[se+t],t==6?n+=Me[e&15|64]:t==8?n+=Me[e&63|128]:n+=Me[e],t&1&&t>1&&t<11&&(n+="-");return se+=16,n}var ue=256,Be=[],Ue;for(;ue--;)Be[ue]=(ue+256).toString(16).substring(1);function gr(){var t=0,e,n="";if(!Ue||ue+16>256){for(Ue=Array(t=256);t--;)Ue[t]=256*Math.random()|0;t=ue=0}for(;t<16;t++)e=Ue[ue+t],t==6?n+=Be[e&15|64]:t==8?n+=Be[e&63|128]:n+=Be[e],t&1&&t>1&&t<11&&(n+="-");return ue++,n}var fr=()=>!Q(globalThis.crypto)&&m(globalThis.crypto.getRandomValues),Ze=()=>fr()?dr():gr(),hr=()=>!!window.chrome?.runtime?.id,Kn=()=>_(globalThis.navigator.userAgent)&&/Trident.*rv:11\./.test(globalThis.navigator.userAgent),pr=(t,e=!1)=>{let n=!1,s=!1;function r(){n||(n=!0,t(s),setTimeout(()=>{n=!1},0))}(e||Kn())&&globalThis.addEventListener("beforeunload",()=>{s=!1,r()}),globalThis.addEventListener("blur",()=>{s=!0,r()}),globalThis.addEventListener("focus",()=>{n=!1}),document.addEventListener("pagehide",()=>{s=document.visibilityState==="hidden",r()}),document.addEventListener("visibilitychange",()=>{s=!0,document.visibilityState==="hidden"?r():n=!1})},Qn=t=>t.toISOString(),vr=()=>Qn(new Date),S=":: ",mr=t=>`A script with the id "${t}" is already loaded. Skipping the loading of this script to prevent conflicts`,sn=(t,e,n)=>`Unable to load (${_(n)?n:n.type}) the script with the id "${t}" from URL "${e}"`,Er=(t,e,n)=>`A timeout of ${n} ms occurred while trying to load the script with id "${t}" from URL "${e}"`,yr=(t,e)=>`${t}${S}A circular reference has been detected in the object and the property "${e}" has been dropped from the output.`,Sr="Failed to convert the value to a JSON string.",br="Failed to encode the cookie data.",Ir=(t,e)=>`${t}${S}The "${e}" storage type is `,Tr="JSONStringify",Ar="[BigInt]",zn="[Circular Reference]",Rr=(t,e,n)=>{let s=[];return function(r,i){if(!e?.includes(r)&&!(t&&Q(i))){if(typeof i!="object"||G(i))return i;for(;s.length>0&&s[s.length-1]!==this;)s.pop();return s.includes(i)?(n?.warn(yr(Tr,r)),zn):(s.push(i),i)}}},K=(t,e,n,s)=>{try{return JSON.stringify(t,Rr(e,n,s))}catch(r){return s?.warn(Sr,r),null}},Or=t=>{let e=[];return function(s,r){if(Ys(r))return Ar;for(;e.length>0&&e[e.length-1]!==this;)e.pop();return e.includes(r)?zn:(e.push(r),r)}},Wn=(t,e)=>{let n=Array.isArray(t)?[]:{};for(let s in t)if(Object.hasOwnProperty.call(t,s)){let r=t[s],i=e.call(t,s,r);N(i)||Array.isArray(i)?n[s]=Wn(i,e):n[s]=i}return n},I=(t,e)=>{let n=Or(),s=n.call(t,"",t);return N(t)||Array.isArray(t)?Wn(t,n):s},xe="[SDK DISPATCHED ERROR]",et=t=>{let{stack:e,stacktrace:n,"opera#sourceloc":s}=t,r=e??n??s;if(r&&typeof r=="string")return r},Wt=(t,e)=>{if(!Ht(t))return new Error(`${e}: ${K(t)}`);try{let n=t.constructor,s=new n(`${e}: ${t.message}`),r=et(t);return r&&(s.stack=r),Object.getOwnPropertyNames(t).forEach(i=>{if(i!=="message"&&i!=="stack"&&i!=="name")try{s[i]=t[i]}catch{}}),s}catch{return new Error(`${e}: ${K(t)}`)}},D=t=>{if(Ht(t)){let e=et(t);if(e){let{stack:n,stacktrace:s,"opera#sourceloc":r}=t;switch(e){case n:t.stack=`${n}
3
3
  ${xe}`;break;case s:t.stacktrace=`${s}
4
4
  ${xe}`;break;case r:default:t["opera#sourceloc"]=`${r}
5
5
  ${xe}`;break}}}globalThis.dispatchEvent(new ErrorEvent("error",{error:t,bubbles:!0,cancelable:!0,composed:!0}))},rn="RudderLabs JavaScript SDK",Pe="3.29.0",_r="com.rudderlabs.javascript",Xn="npm",Nr="modern",on="RudderJS-Initiated",Pr="ad-block page request",kr="/ad-blocked",_e="preloadedEventsBuffer",Cr="Consent Management Interaction",Dr="ajs_trait_",Lr="ajs_prop_",an="ajs_aid",wr="ajs_uid",ln="ajs_event",Ur=10*1e3,$r=31536e3*1e3,cn=720*60*1e3,vt=1800*1e3,un=10*1e3,Mr=10*1e3,Br=250,Yn=(t="app")=>{globalThis.RudderStackGlobals||(globalThis.RudderStackGlobals={}),globalThis.RudderStackGlobals[t]||(globalThis.RudderStackGlobals[t]={})},ke=(t,e,n="app")=>{Yn(n),globalThis.RudderStackGlobals[n][t]=e},qn=(t,e="app")=>(Yn(e),globalThis.RudderStackGlobals[e][t]);function xr(t,e,n=Br){let s;return(...r)=>{globalThis.clearTimeout(s),s=globalThis.setTimeout(()=>{t.apply(e,r)},n)}}var dn=(t,e)=>{let n={};return t.forEach((s,r)=>{if(r.startsWith(e)){let i=r.substring(e.length);n[i]=t.get(r)}}),n},Gr=(t=[])=>{let e={trait:Dr,properties:Lr},n=new URLSearchParams(globalThis.location.search);n.get(ln)&&t.unshift(["track",n.get(ln),dn(n,e.properties)]);let s=n.get(wr),r=dn(n,e.trait);if(s||ee(r)){let i=[...s?[s]:[],r];t.unshift(["identify",...i])}n.get(an)&&t.unshift(["setAnonymousId",n.get(an)])},Fr=t=>{let e="load",n=[],s=0;for(;s<t.length;){if(t[s]&&t[s][0]===e){n=b(t[s]),t.splice(s,1);break}s+=1}return n},Vr=t=>{let e="consent",n=t.filter(r=>r[0]===e),s=t.filter(r=>r[0]!==e);t.splice(0,t.length,...n,...s)},jr=t=>{let e=qn(_e)||[];Gr(e),e.length>0&&(t.enqueuePreloadBufferEvents(e),ke(_e,[]))},Hr=(t,e)=>{let n=t.shift(),s;if(m(e[n])){switch(n){case"page":s=We(...t);break;case"track":s=Qt(...t);break;case"identify":s=Fn(...t);break;case"alias":s=Vn(...t);break;case"group":s=jn(...t);break;default:e[n](...t);break}s&&e[n](s)}},Kr=10*1e3,Qr="RS_JS_SDK",zr=(t,e,n=!0,s=null,r=null,i={})=>{let a=document.createElement("script");return a.type="text/javascript",a.onload=s,a.onerror=r,a.src=t,a.id=e,a.async=n,Object.keys(i).forEach(l=>{a.setAttribute(l,i[l])}),a.setAttribute("data-loader",Qr),a},Wr=t=>{let e=document.getElementsByTagName("head");if(e.length>0){e[0]?.insertBefore(t,e[0]?.firstChild);return}let n=document.getElementsByTagName("script");if(n.length>0&&n[0]?.parentNode){n[0]?.parentNode.insertBefore(t,n[0]);return}let s=document.createElement("head");s.appendChild(t);let r=document.getElementsByTagName("html")[0];r?.insertBefore(s,r.firstChild)},Xr=(t,e,n,s=!0,r)=>new Promise((i,a)=>{document.getElementById(e)&&a(new Error(mr(e)));try{let c;Wr(zr(t,e,s,()=>{globalThis.clearTimeout(c),i(e)},v=>{globalThis.clearTimeout(c),a(new Error(sn(e,t,v)))},r)),c=globalThis.setTimeout(()=>{a(new Error(Er(e,t,n)))},n)}catch(c){a(Wt(c,sn(e,t,"unknown")))}}),Xe=class{constructor(e,n=Kr){this.logger=e,this.timeout=n}loadJSFile(e){let{url:n,id:s,timeout:r,async:i,callback:a,extraAttributes:l}=e,c=!m(a);Xr(n,s,r||this.timeout,i,l).then(d=>{c||a(d)}).catch(d=>{c||a(s,d)})}},Yr=Symbol.for("preact-signals");function tt(){if(re>1)re--;else{for(var t,e=!1;Ne!==void 0;){var n=Ne;for(Ne=void 0,mt++;n!==void 0;){var s=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&es(n))try{n.c()}catch(r){e||(t=r,e=!0)}n=s}}if(mt=0,re--,e)throw t}}function U(t){if(re>0)return t();re++;try{return t()}finally{tt()}}var T=void 0;function Jn(t){var e=T;T=void 0;try{return t()}finally{T=e}}var Ne=void 0,re=0,mt=0,Ye=0;function Zn(t){if(T!==void 0){var e=t.n;if(e===void 0||e.t!==T)return e={i:0,S:t,p:T.s,n:void 0,t:T,e:void 0,x:void 0,r:e},T.s!==void 0&&(T.s.n=e),T.s=e,t.n=e,32&T.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=T.s,e.n=void 0,T.s.n=e,T.s=e),e}}function $(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}$.prototype.brand=Yr;$.prototype.h=function(){return!0};$.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:Jn(function(){var s;(s=e.W)==null||s.call(e)}))};$.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,s=t.x;n!==void 0&&(n.x=s,t.e=void 0),s!==void 0&&(s.e=n,t.x=void 0),t===this.t&&(this.t=s,s===void 0&&Jn(function(){var r;(r=e.Z)==null||r.call(e)}))}};$.prototype.subscribe=function(t){var e=this;return X(function(){var n=e.value,s=T;T=void 0;try{t(n)}finally{T=s}},{name:"sub"})};$.prototype.valueOf=function(){return this.value};$.prototype.toString=function(){return this.value+""};$.prototype.toJSON=function(){return this.value};$.prototype.peek=function(){var t=T;T=void 0;try{return this.value}finally{T=t}};Object.defineProperty($.prototype,"value",{get:function(){var t=Zn(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(mt>100)throw new Error("Cycle detected");this.v=t,this.i++,Ye++,re++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{tt()}}}});function u(t,e){return new $(t,e)}function es(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function ts(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function ns(t){for(var e=t.s,n=void 0;e!==void 0;){var s=e.p;e.i===-1?(e.S.U(e),s!==void 0&&(s.n=e.n),e.n!==void 0&&(e.n.p=s)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=s}t.s=n}function ye(t,e){$.call(this,void 0),this.x=t,this.s=void 0,this.g=Ye-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ye.prototype=new $;ye.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Ye))return!0;if(this.g=Ye,this.f|=1,this.i>0&&!es(this))return this.f&=-2,!0;var t=T;try{ts(this),T=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return T=t,ns(this),this.f&=-2,!0};ye.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}$.prototype.S.call(this,t)};ye.prototype.U=function(t){if(this.t!==void 0&&($.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}};ye.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}};Object.defineProperty(ye.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=Zn(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function ss(t){var e=t.u;if(t.u=void 0,typeof e=="function"){re++;var n=T;T=void 0;try{e()}catch(s){throw t.f&=-2,t.f|=8,Xt(t),s}finally{T=n,tt()}}}function Xt(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,ss(t)}function qr(t){if(T!==this)throw new Error("Out-of-order effect");ns(this),T=t,this.f&=-2,8&this.f&&Xt(this),tt()}function Se(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Se.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}};Se.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,ss(this),ts(this),re++;var t=T;return T=this,qr.bind(this,t)};Se.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ne,Ne=this)};Se.prototype.d=function(){this.f|=8,1&this.f||Xt(this)};Se.prototype.dispose=function(){this.d()};function X(t,e){var n=new Se(t,e);try{n.c()}catch(r){throw n.d(),r}var s=n.d.bind(n);return s[Symbol.dispose]=s,s}var Et=class{constructor(){this.items=[]}enqueue(e){this.items.push(e)}dequeue(){return this.items.length===0?null:this.items.shift()}isEmpty(){return this.items.length===0}size(){return this.items.length}clear(){this.items=[]}},$e={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5},gn="LOG",rs="ERROR",Jr="RS SDK",Zr="font-weight: bold; background: black; color: white;",ei="font-weight: normal;",yt=class{constructor(e=gn,n="",s=console){this.minLogLevel=$e[e],this.scope=n,this.logProvider=s}log(...e){this.outputLog("LOG",e)}info(...e){this.outputLog("INFO",e)}debug(...e){this.outputLog("DEBUG",e)}warn(...e){this.outputLog("WARN",e)}error(...e){this.outputLog("ERROR",e)}outputLog(e,n){this.minLogLevel<=$e[e]&&this.logProvider[e.toLowerCase()]?.(...this.formatLogData(n))}setScope(e){this.scope=e||this.scope}setMinLogLevel(e){this.minLogLevel=$e[e],w(this.minLogLevel)&&(this.minLogLevel=$e[gn])}formatLogData(e){if(Array.isArray(e)&&e.length>0){let n=`%c ${Jr}`;this.scope&&(n=`${n} - ${this.scope}`);let s=_(e[0])?e[0].trim():"";n=`${n} %c ${s}`;let r=[n,Zr,ei];return _(e[0])||r.push(e[0]),r.push(...e.slice(1)),r}return e}},te=new yt,q=(function(t){return t.HANDLEDEXCEPTION="handledException",t.UNHANDLEDEXCEPTION="unhandledException",t.UNHANDLEDREJECTION="unhandledPromiseRejection",t})({}),is=["localStorage","memoryStorage","cookieStorage","sessionStorage","none"],St="cookieStorage",fn="Unable to process/parse source configuration response",ti="The source is disabled. Please enable the source in the dashboard to send events.",ni="Failed to prepare data for the request.",si="Failed to invoke plugin because the extension point name is missing.",ri="Failed to invoke plugin because the extension point name is invalid.",ii=t=>`${t}${S}The "getSourceConfig" load API option must be a function that returns valid source configuration data.`,oi=(t,e,n)=>`${t}${S}The base URL "${n}" for ${e} is not valid.`,ai=(t,e,n)=>`${t}${S}The consent manager "${e}" is not supported. Please choose one of the following supported consent managers: "${Object.keys(n)}".`,li=(t,e)=>`${t}${S}Ignoring a non-error: ${e}.`,hn="Failed to log breadcrumb",ci=t=>`${t}${S}Failed to handle the error.`,ui=t=>`${t}${S}Plugin name is missing.`,di=(t,e)=>`${t}${S}Plugin "${e}" already exists.`,gi=(t,e)=>`${t}${S}Plugin "${e}" not found.`,fi=(t,e)=>`${t}${S}Plugin "${e}" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.`,hi=(t,e,n)=>`${t}${S}Plugin "${e}" could not be loaded because some of its dependencies "${n}" do not exist.`,pi=(t,e,n)=>`${t}${S}Failed to invoke the "${e}" extension point of plugin "${n}".`,pn="Failed to fetch the source config",vi=(t,e)=>`${t}${S}The write key "${e}" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.`,mi=(t,e)=>`${t}${S}The data plane URL "${e}" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.`,os=t=>`${t}${S}The provided callback parameter is not a function.`,Ei=(t,e,n,s,r)=>`${t} with status ${e} (${n}) for URL: ${s}. Response: ${r.trim()}`,yi=(t,e,n)=>`${t} due to timeout or no connection (${e?e.type:""}) at the client side for URL: ${n}`,Si=(t,e)=>`${t} for URL: ${e}`,bi=t=>`Failed to save the value for "${t}" to storage`,Ii=t=>`Failed to retrieve or parse data for "${t}" from storage`,Ti=t=>`The server responded with status ${t} while setting the cookies. As a fallback, the cookies will be set client side.`,Ai=t=>`The server failed to set the ${t} cookie. As a fallback, the cookies will be set client side.`,vn="Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.",Ri=(t,e,n)=>`${t}${S}The storage type "${e}" is not supported. Please choose one of the following supported types: "${is}". The default type "${n}" will be used instead.`,Oi=(t,e,n,s)=>`${t}${S}The storage encryption version "${e}" is not supported. Please choose one of the following supported versions: "${Object.keys(n)}". The default version "${s}" will be used instead.`,_i=(t,e,n)=>`${t}${S}The storage data migration has been disabled because the configured storage encryption version (${e}) is not the latest (${n}). To enable storage data migration, please update the storage encryption version to the latest version.`,Ni=(t,e,n)=>`${t}${S}The provided cookie domain (${e}) does not match the current webpage's domain (${n}). Hence, the cookies will be set client-side.`,Pi=(t,e,n,s)=>`${t}${S}The "${e}" property defined under "${n}" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (${s}).`,ki=t=>`${t}${S}Please make sure that the "context" property in the event API's "options" argument is a valid object literal with key-value pairs.`,Ci=t=>`${t}${S}The Beacon API is not supported by your browser. The events will be sent using XHR instead.`,Di=(t,e,n)=>`${t}${S}The session timeout value "${e}" is not a number. The default timeout of ${n} ms will be used instead.`,Li=(t,e,n)=>`${t}${S}The session cut off duration value "${e}" is not a number. The default cut off duration of ${n} ms will be used instead.`,wi=(t,e,n)=>`${t}${S}The session cut off duration value "${e}" ms is less than the session timeout value "${n}" ms. The cut off functionality will be disabled.`,Ui=t=>`${t}${S}The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.`,$i=(t,e,n)=>`${t}${S}The session timeout value ${e} ms is less than the recommended minimum of ${n} ms. Please consider increasing the timeout value to ensure optimal performance and reliability.`,Mi=(t,e,n)=>`${t}${S}The provided session ID (${e}) is either invalid, not a positive integer, or not at least "${n}" digits long. A new session ID will be auto-generated instead.`,Bi=t=>`${t}${S}The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.`,xi=(t,e,n,s)=>`${t}${S}The storage type "${n}" is not available for entry "${e}". The SDK will initialize the entry with "${s}" storage type instead.`,Gi=t=>`${t}${S}The callback threw an exception`,Fi=(t,e)=>`${t}${S}The provided source config URL "${e}" is invalid. Using the default source config URL instead.`,Vi=(t,e)=>`Failed to load the polyfill script with ID "${t}" from URL ${e}.`,ji=(t,e,n)=>`${t}${S}The pre-consent storage strategy "${e}" is not supported. Please choose one of the following supported strategies: "none, session, anonymousId". The default strategy "${n}" will be used instead.`,Hi=(t,e,n)=>`${t}${S}The pre-consent events delivery type "${e}" is not supported. Please choose one of the following supported types: "immediate, buffer". The default type "${n}" will be used instead.`,Ki=(t,e)=>`${t}${S}${e} plugin is deprecated. Please exclude it from the load API options.`,Qi=(t,e,n,s)=>{let r=n.length===1,i=r?` '${n[0]}' plugin was`:` ['${n.join("', '")}'] plugins were`,a=`${t}${S}${e}, but${i} not configured to load.`;return s?`${a} So, ${r?"the plugin":"those plugins"} will be loaded automatically.`:`${a} Ignore if this was intentional. Otherwise, consider adding ${r?"it":"them"} to the 'plugins' load API option.`},zi=(t,e)=>`${t}${S}The provided polyfill URL "${e}" is invalid. The default polyfill URL will be used instead.`,Wi=t=>`${t}${S}Page Unloaded event can only be tracked when the Beacon transport is active. Please enable "useBeacon" load API option.`,Xi=(t,e)=>`${t}${S}Ignoring unknown plugins: ${e.join(", ")}.`,Yi=(t,e)=>`${t}${S}Failed to load the following unavailable local plugins: ${e.join(", ")}. Some features of the SDK may not work as expected. Make sure you are using the correct SDK bundle variant.`,qi=(t,e)=>`${t}${S}Cannot add custom integration for destination ID "${e}" after the SDK is loaded.`,as={All:!0},nt="js-integrations",ls="plugins",Ji=new RegExp("^(https?:\\/\\/)(((([a-zA-Z\\d]([a-zA-Z\\d-]*[a-zA-Z\\d])*)\\.)+[a-zA-Z]{2,}|localhost|((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?)))(\\:\\d+)?(\\/[-a-zA-Z\\d%_.~+]*)*(\\?[;&a-zA-Z\\d%_.~+=-]*)?(\\#[-a-zA-Z\\d_]*)?$"),Ce="modern",st="https://cdn.rudderlabs.com",Yt="v3",cs=`${st}/${Yt}/${Ce}/${nt}`,us=`${st}/${Yt}/${Ce}/${ls}`,ds="https://api.rudderstack.com",le="v3",Zi="xhr",bt={iubenda:"IubendaConsentManager",oneTrust:"OneTrustConsentManager",ketch:"KetchConsentManager",custom:"CustomConsentManager"},Ge={[le]:"StorageEncryption",legacy:"StorageEncryptionLegacy"},eo={[Zi]:"XhrQueue",beacon:"BeaconQueue"},to="rsaRequest",no="rsaMetrics",so="Custom Device Mode",ro={configUrl:ds,loadIntegration:!0,sessions:{autoTrack:!0,timeout:vt,cutOff:{enabled:!1}},sameSiteCookie:"Lax",polyfillIfRequired:!0,integrations:as,useBeacon:!1,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:!0,lockPluginsVersion:!0,uaChTrackLevel:"none",plugins:[],useGlobalIntegrationsConfigInEvents:!1,bufferDataPlaneEventsUntilReady:!1,dataPlaneEventsBufferTimeout:Mr,storage:{encryption:{version:le},migrate:!0,cookie:{}},sendAdblockPage:!1,sameDomainCookiesOnly:!1,secureCookie:!1,sendAdblockPageOptions:{},useServerSideCookies:!1},io=u(b(ro)),A=Kt({userId:"",userTraits:{},anonymousId:"",groupId:"",groupTraits:{},initialReferrer:"",initialReferringDomain:"",sessionInfo:{},authToken:null}),lt=Kt({entries:{userId:!0,userTraits:!0,groupId:!0,groupTraits:!0,sessionInfo:!0,authToken:!0,anonymousId:!1,initialReferrer:!1,initialReferringDomain:!1}}),oo=10,ao={userId:u(A.userId),userTraits:u(A.userTraits),anonymousId:u(A.anonymousId),groupId:u(A.groupId),groupTraits:u(A.groupTraits),initialReferrer:u(A.initialReferrer),initialReferringDomain:u(A.initialReferringDomain),sessionInfo:u(A.sessionInfo),authToken:u(A.authToken)},lo={isOnline:u(!0),storage:{isLocalStorageAvailable:u(!1),isCookieStorageAvailable:u(!1),isSessionStorageAvailable:u(!1)},isBeaconAvailable:u(!1),isLegacyDOM:u(!1),isUaCHAvailable:u(!1),isCryptoAvailable:u(!1),isIE11:u(!1),isAdBlockerDetectionInProgress:u(!1),isAdBlocked:u(void 0),cspBlockedURLs:u([])},co={isErrorReportingEnabled:u(!1),isMetricsReportingEnabled:u(!1),breadcrumbs:u([])},uo=u(void 0),go={activeDataplaneUrl:u(void 0),integrationsCDNPath:u(cs),pluginsCDNPath:u(us),sourceConfigUrl:u(void 0),status:u(void 0),initialized:u(!1),logLevel:u(rs),loaded:u(!1),readyCallbacks:u([]),writeKey:u(void 0),dataPlaneUrl:u(void 0),safeAnalyticsInstance:u(void 0)},fo={enabled:u(!1),initialized:u(!1),data:u({}),activeConsentManagerPluginName:u(void 0),preConsent:u({enabled:!1}),postConsent:u({}),resolutionStrategy:u("and"),provider:u(void 0),metadata:u(void 0)},ho={retries:u(0),dropped:u(0),sent:u(0),queued:u(0),triggered:u(0),metricsServiceUrl:u(void 0)},po=()=>Nr,vo={app:u({name:rn,namespace:_r,version:Pe,installType:Xn}),traits:u(null),library:u({name:rn,version:Pe,snippetVersion:globalThis.RudderSnippetVersion,variant:po()}),userAgent:u(null),device:u(null),network:u(null),os:u({name:"",version:""}),locale:u(null),screen:u({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),"ua-ch":u(void 0),timezone:u(void 0)},mo={configuredDestinations:u([]),activeDestinations:u([]),loadOnlyIntegrations:u({}),failedDestinations:u([]),loadIntegration:u(!0),initializedDestinations:u([]),clientDestinationsReady:u(!1),integrationsConfig:u({})},Eo={toBeProcessedArray:u([]),readyCallbacksArray:u([])},yo={ready:u(!1),loadedPlugins:u([]),failedPlugins:u([]),pluginsToLoadFromConfig:u([]),activePlugins:u([]),totalPluginsToLoad:u(0)},So={encryptionPluginName:u(void 0),migrate:u(!1),type:u(void 0),cookie:u(void 0),entries:u({}),trulyAnonymousTracking:u(!1)},bo={isEnabledServerSideCookies:u(!1),dataServiceUrl:u(void 0)},Io={eventsQueuePluginName:u(void 0),deliveryEnabled:u(!0)},To={enabled:u(!1),pageLifecycle:{enabled:u(!1),pageViewId:u(void 0),pageLoadedTimestamp:u(void 0)}},Ao={capabilities:lo,consents:fo,context:vo,eventBuffer:Eo,lifecycle:go,loadOptions:io,metrics:ho,nativeDestinations:mo,plugins:yo,reporting:co,session:ao,source:uo,storage:So,serverCookies:bo,dataPlaneEvents:Io,autoTrack:To},o={...b(Ao)};function gs(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Fe={exports:{}},Ve={exports:{}},Ro=Ve.exports,mn;function Oo(){return mn||(mn=1,(function(t,e){(function(n,s){t.exports=s()})(Ro,function(){function n(h){return!isNaN(parseFloat(h))&&isFinite(h)}function s(h){return h.charAt(0).toUpperCase()+h.substring(1)}function r(h){return function(){return this[h]}}var i=["isConstructor","isEval","isNative","isToplevel"],a=["columnNumber","lineNumber"],l=["fileName","functionName","source"],c=["args"],d=["evalOrigin"],g=i.concat(a,l,c,d);function v(h){if(h)for(var E=0;E<g.length;E++)h[g[E]]!==void 0&&this["set"+s(g[E])](h[g[E]])}v.prototype={getArgs:function(){return this.args},setArgs:function(h){if(Object.prototype.toString.call(h)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=h},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(h){if(h instanceof v)this.evalOrigin=h;else if(h instanceof Object)this.evalOrigin=new v(h);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var h=this.getFileName()||"",E=this.getLineNumber()||"",R=this.getColumnNumber()||"",P=this.getFunctionName()||"";return this.getIsEval()?h?"[eval] ("+h+":"+E+":"+R+")":"[eval]:"+E+":"+R:P?P+" ("+h+":"+E+":"+R+")":h+":"+E+":"+R}},v.fromString=function(E){var R=E.indexOf("("),P=E.lastIndexOf(")"),ie=E.substring(0,R),rt=E.substring(R+1,P).split(","),De=E.substring(P+1);if(De.indexOf("@")===0)var be=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(De,""),$s=be[1],Ms=be[2],Bs=be[3];return new v({functionName:ie,args:rt||void 0,fileName:$s,lineNumber:Ms||void 0,columnNumber:Bs||void 0})};for(var y=0;y<i.length;y++)v.prototype["get"+s(i[y])]=r(i[y]),v.prototype["set"+s(i[y])]=(function(h){return function(E){this[h]=!!E}})(i[y]);for(var f=0;f<a.length;f++)v.prototype["get"+s(a[f])]=r(a[f]),v.prototype["set"+s(a[f])]=(function(h){return function(E){if(!n(E))throw new TypeError(h+" must be a Number");this[h]=Number(E)}})(a[f]);for(var p=0;p<l.length;p++)v.prototype["get"+s(l[p])]=r(l[p]),v.prototype["set"+s(l[p])]=(function(h){return function(E){this[h]=String(E)}})(l[p]);return v})})(Ve)),Ve.exports}var _o=Fe.exports,En;function No(){return En||(En=1,(function(t,e){(function(n,s){t.exports=s(Oo())})(_o,function(s){var r=/(^|@)\S+:\d+/,i=/^\s*at .*(\S+:\d+|\(native\))/m,a=/^(eval@)?(\[native code])?$/;return{parse:function(c){if(typeof c.stacktrace<"u"||typeof c["opera#sourceloc"]<"u")return this.parseOpera(c);if(c.stack&&c.stack.match(i))return this.parseV8OrIE(c);if(c.stack)return this.parseFFOrSafari(c);throw new Error("Cannot parse given Error object")},extractLocation:function(c){if(c.indexOf(":")===-1)return[c];var d=/(.+?)(?::(\d+))?(?::(\d+))?$/,g=d.exec(c.replace(/[()]/g,""));return[g[1],g[2]||void 0,g[3]||void 0]},parseV8OrIE:function(c){var d=c.stack.split(`
@@ -11,4 +11,4 @@ ${xe}`;break}}}globalThis.dispatchEvent(new ErrorEvent("error",{error:t,bubbles:
11
11
  `),v=[],y=2,f=g.length;y<f;y+=2){var p=d.exec(g[y]);p&&v.push(new s({fileName:p[2],lineNumber:p[1],source:g[y]}))}return v},parseOpera10:function(c){for(var d=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,g=c.stacktrace.split(`
12
12
  `),v=[],y=0,f=g.length;y<f;y+=2){var p=d.exec(g[y]);p&&v.push(new s({functionName:p[3]||void 0,fileName:p[2],lineNumber:p[1],source:g[y]}))}return v},parseOpera11:function(c){var d=c.stack.split(`
13
13
  `).filter(function(g){return!!g.match(r)&&!g.match(/^Error created at/)},this);return d.map(function(g){var v=g.split("@"),y=this.extractLocation(v.pop()),f=v.shift()||"",p=f.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0,h;f.match(/\(([^)]*)\)/)&&(h=f.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var E=h===void 0||h==="[arguments not available]"?void 0:h.split(",");return new s({functionName:p,args:E,fileName:y[0],lineNumber:y[1],columnNumber:y[2],source:g})},this)}}})})(Fe)),Fe.exports}var Po=No(),ko=gs(Po),fs="global code",Co=t=>O(t)&&/^global code$/i.test(t)?fs:t,Do=t=>{let e={file:t.fileName,method:Co(t.functionName),lineNumber:t.lineNumber,columnNumber:t.columnNumber};return e.lineNumber&&e.lineNumber>-1&&!e.file&&!e.method&&(e.file=fs),e},yn=t=>_(t)?t:"";function Sn(t,e,n,s){return{errorClass:yn(t),message:`${n}${yn(e)}`,type:"browserjs",stacktrace:s.reduce((r,i)=>{let a=Do(i);try{return JSON.stringify(a)==="{}"?r:r.concat(a)}catch{return r}},[])}}var hs=(t,e)=>{let n;return Ht(t)&&_(et(t))?n=t:(e.warn(li(Re,K(t))),n=void 0),n},Lo=(t,e)=>{try{let n=ko.parse(t);return Sn(t.name,t.message,e,n)}catch{return Sn(t.name,t.message,e,[])}},bn=(t,e)=>{try{return JSON.parse(t||"")}catch(n){let s=Wt(n,"Failed to parse response data");e(s)}},je="The request failed",wo=[/Failed to fetch dynamically imported module: .*/],Uo=[/Unable to load \(.*\) the script with the id .*/,/A timeout of \d+ ms occurred while trying to load the script with id .*/],$o=[new RegExp(`${je}.*`),/A script with the id .* is already loaded\./],Mo=[...wo,...Uo],Bo="integrations",xo="sdk",Go=xo,Fo={headers:{Accept:"application/json","Content-Type":"application/json;charset=UTF-8"},method:"GET"},In=(t,e,n)=>{let s=L(Fo,e||{});return n&&(s.headers=L(s.headers,{Authorization:n})),s.url=t,s},Tn=(t,e=Ur,n)=>new Promise((s,r)=>{let i;if(t.sendRawData===!0)i=t.data;else if(i=K(t.data,!1,[],n),G(i)){r({error:new Error(ni),undefined:void 0,options:t});return}let a=new XMLHttpRequest,l=d=>{r({error:new Error(Ei(je,a.status,a.statusText,t.url,a.responseText)),xhr:a,options:t})},c=d=>{r({error:new Error(yi(je,d,t.url)),xhr:a,options:t,...d?.type==="timeout"?{timedOut:!0}:{}})};a.ontimeout=c,a.onerror=c,a.onload=()=>{a.status>=200&&a.status<400?s({response:a.responseText,xhr:a,options:t}):l()},a.open(t.method,t.url,!0),t.withCredentials===!0&&(a.withCredentials=!0),a.timeout=e,Object.keys(t.headers).forEach(d=>{t.headers[d]&&a.setRequestHeader(d,t.headers[d])});try{a.send(i)}catch(d){r({error:Wt(d,Si(je,t.url)),xhr:a,options:t})}}),It=class{constructor(e){this.logger=e,this.onError=this.onError.bind(this)}init(e){this.errorHandler=e}async getData(e){let{url:n,options:s,timeout:r,isRawResponse:i}=e;try{let a=await Tn(In(n,s,this.basicAuthHeader),r,this.logger);return{data:i?a.response:bn(a.response,this.onError),details:a}}catch(a){return{data:void 0,details:a}}}getAsyncData(e){let{callback:n,url:s,options:r,timeout:i,isRawResponse:a}=e,l=!m(n);Tn(In(s,r,this.basicAuthHeader),i,this.logger).then(c=>{l||n(a?c.response:bn(c.response,this.onError),c)}).catch(c=>{l||n(void 0,c)})}onError(e,n){this.errorHandler?.onError({error:e,context:lr,groupingHash:n})}setAuthHeader(e,n=!1){let s=n?e:ir(`${e}:`);this.basicAuthHeader=`Basic ${s}`}resetAuthHeader(){this.basicAuthHeader=void 0}},ps=new It(te),Vo="1",jo=()=>["rsa"],Ho=["www.test-host.com","localhost","127.0.0.1","[::1]"],Ko=["userId","userTraits","groupId","groupTraits","anonymousId","config","integration","eventBuffer","traits","authToken"],Qo="RudderStack JavaScript SDK",zo="git+https://github.com/rudderlabs/rudder-sdk-js.git",Wo="js",vs=t=>{o.capabilities.isAdBlockerDetectionInProgress.value=!0;try{let e=new URL(o.lifecycle.sourceConfigUrl.value),n=`${e.origin}${e.pathname}?view=ad`;t.getAsyncData({url:n,options:{method:"HEAD",headers:{"Content-Type":void 0}},isRawResponse:!0,callback:(s,r)=>{o.capabilities.isAdBlockerDetectionInProgress.value=!1,o.capabilities.isAdBlocked.value=r?.error!==void 0||r?.xhr?.responseURL!==n}})}catch(e){throw o.capabilities.isAdBlockerDetectionInProgress.value=!1,e}},Xo=(t,e)=>{switch(e){case q.UNHANDLEDEXCEPTION:{let{error:n}=t;return n||t}case q.UNHANDLEDREJECTION:return t.reason;case q.HANDLEDEXCEPTION:default:return t}},Yo=t=>({type:"manual",name:t,timestamp:new Date,metaData:{}}),qo=(t=()=>window.location.hostname)=>{let e=t();return!e||e&&Ho.includes(e)?"development":"production"},Jo=t=>{let e=K(t,!1,Ko);return e!==null?JSON.parse(e):{}},Zo=()=>globalThis.location.href.split("?")[0],ea=(t,e,n,s)=>({id:`${t.value?.id??n.writeKey.value}..${e.sessionInfo.value.id??"NA"}..${s.pageLifecycle.pageViewId.value??"NA"}`,name:t.value?.name??"NA"}),ta=(t,e)=>({locale:t.value??"NA",userAgent:e.value??"NA",time:new Date}),na=(t,e,n,s)=>{let{context:r,lifecycle:i,session:a,source:l,reporting:c,autoTrack:d}=n,{app:g,locale:v,userAgent:y,timezone:f,screen:p,library:h}=r;return{payloadVersion:"5",notifier:{name:Qo,version:g.value.version,url:zo},events:[{exceptions:[b(t)],severity:e.severity,unhandled:e.unhandled,severityReason:e.severityReason,app:{version:g.value.version,releaseStage:qo(),type:g.value.installType},device:ta(v,y),request:{url:Zo(),clientIp:"[NOT COLLECTED]"},breadcrumbs:b(c.breadcrumbs.value),context:t.message,groupingHash:s,metaData:{app:{snippetVersion:h.value.snippetVersion},device:{...p.value,timezone:f.value},...Jo(n)},user:ea(l,a,i,d)}]}},sa=(t,e,n)=>{if(w(t.capabilities.isAdBlocked.value)){t.capabilities.isAdBlockerDetectionInProgress.value===!1&&vs(e);let s=X(()=>{O(t.capabilities.isAdBlocked.value)&&(n(t.capabilities.isAdBlocked.value===!1),s())})}else n(t.capabilities.isAdBlocked.value===!1)},ra=(t,e,n)=>{let s=t.message;return new Promise(r=>{if(Mo.some(i=>i.test(s))){let i=/https?:\/\/[^\s"'(),;<>[\]{}]+/.exec(s)?.[0];_(i)?i.startsWith(st)?e.capabilities.cspBlockedURLs.value.includes(i)?r(!1):sa(e,n,r):r(!1):r(!0)}else r(!$o.some(i=>i.test(s)))})},ms=t=>t?t.split("/").at(-2):void 0,Es=t=>{let e=t.stacktrace[0]?.file;if(!(!e||typeof e!="string"))return e},ia=t=>{let e=Es(t);if(!e)return!1;let n=e.substring(e.lastIndexOf("/")+1);return ms(e)===nt||jo().some(r=>n.startsWith(r)&&n.endsWith(".js"))},oa=(t,e)=>{if(e)return e;let n=Es(t);return ms(n)===nt?Bo:Go},aa=(t,e,n)=>{let s={version:Vo,message_id:Ze(),source:{name:Wo,sdk_version:e.context.app.value.version,write_key:e.lifecycle.writeKey.value,install_type:e.context.app.value.installType,category:n},errors:t};return K(s)},la=(t,e,n)=>{let s;if(!O(t))s=e;else if(_(t))s=t;else{let r=hs(t,n);O(r)?s=r.message:s=e}return s},Tt=class{constructor(e,n){k(this,"initialized",!1);this.httpClient=e,this.logger=n}init(){this.initialized||(this.attachErrorListeners(),this.initialized=!0)}attachErrorListeners(){globalThis.addEventListener("error",e=>{this.onError({error:e,context:Re,errorType:q.UNHANDLEDEXCEPTION})}),globalThis.addEventListener("unhandledrejection",e=>{this.onError({error:e,context:Re,errorType:q.UNHANDLEDREJECTION})}),document.addEventListener("securitypolicyviolation",e=>{let n=_(e.blockedURI)?e.blockedURI:"";e.disposition==="enforce"&&n.startsWith(st)&&!o.capabilities.cspBlockedURLs.value.includes(n)&&(o.capabilities.cspBlockedURLs.value=[...o.capabilities.cspBlockedURLs.value,n])})}async onError(e){try{let{error:n,context:s,customMessage:r,groupingHash:i,category:a}=e,l=e.errorType??q.HANDLEDEXCEPTION,c=Xo(n,l),d=hs(c,this.logger);if(w(d))return;let g=r?`${r} - `:"",v=`${s}${S}${g}`,y=Lo(d,v),p=et(d).includes(xe);if(!p&&!ia(y)&&l!==q.HANDLEDEXCEPTION)return;if(o.reporting.isErrorReportingEnabled.value&&await ra(y,o,this.httpClient)){let E={severity:"error",unhandled:l!==q.HANDLEDEXCEPTION,severityReason:{type:l}},R=la(i,y.message,this.logger),P=na(y,E,o,R),ie=oa(y,a);this.httpClient.getAsyncData({url:o.metrics.metricsServiceUrl.value,options:{method:"POST",data:aa(P,o,ie),sendRawData:!0},isRawResponse:!0})}(l===q.HANDLEDEXCEPTION||p)&&this.logger.error(y.message)}catch(n){this.logger.error(ci(Re),n)}}leaveBreadcrumb(e){try{o.reporting.breadcrumbs.value=[...o.reporting.breadcrumbs.value,Yo(e)]}catch(n){this.onError({error:n,context:Re,customMessage:hn,groupingHash:hn})}}},ys=new Tt(ps,te),At=class{constructor(e,n={}){k(this,"plugins",[]);k(this,"byName",{});k(this,"cache",{});k(this,"config",{throws:!0});this.config={throws:!0,...n},this.logger=e}register(e,n){if(!e.name){let r=ui(ge);if(this.config.throws)throw new Error(r);this.logger.error(r,e);return}if(this.byName[e.name]){let r=di(ge,e.name);if(this.config.throws)throw new Error(r);this.logger.error(r);return}this.cache={},this.plugins=this.plugins.slice();let s=this.plugins.length;this.plugins.forEach((r,i)=>{r.deps?.includes(e.name)&&(s=Math.min(s,i))}),this.plugins.splice(s,0,e),this.byName[e.name]=e,m(e.initialize)&&e.initialize(n)}unregister(e){let n=this.byName[e];if(!n){let r=gi(ge,e);if(this.config.throws)throw new Error(r);this.logger.error(r);return}let s=this.plugins.indexOf(n);if(s===-1){let r=fi(ge,e);if(this.config.throws)throw new Error(r);this.logger.error(r);return}this.cache={},delete this.byName[e],this.plugins=this.plugins.slice(),this.plugins.splice(s,1)}getPlugin(e){return this.byName[e]}getPlugins(e){let n=e??".";return this.cache[n]||(this.cache[n]=this.plugins.filter(s=>{if(s.deps?.some(r=>!this.byName[r])){let r=s.deps.filter(i=>!this.byName[i]);return this.logger.error(hi(ge,s.name,r)),!1}return n==="."?!0:Zs(s,n)})),this.cache[n]}processRawPlugins(e){e(this.plugins),this.cache={}}invoke(e,n=!0,...s){let r=e;if(!r)throw new Error(si);let i=r.startsWith("!"),a=this.config.throws??r.endsWith("!");if(r=r.replace(/(^!|!$)/g,""),!r)throw new Error(ri);let l=r.split(".");l.pop();let c=l.join(".");return(n?this.getPlugins(r):[this.getPlugins(r)[0]]).map(g=>{let v=ht(g,r);if(!m(v)||i)return v;try{return v.apply(ht(g,c),s)}catch(y){if(a)throw y;this.logger.error(pi(ge,r,g.name),y)}return null})}invokeSingle(e,...n){return this.invoke(e,!1,...n)[0]}invokeMultiple(e,...n){return this.invoke(e,!0,...n)}},ca=new At(te,{throws:!0}),ua=t=>t.config.connectionMode!=="cloud"||t.config.useNativeSDKToSend===!0||t.config.useNativeSDK===!0,da=t=>t.config.connectionMode==="hybrid"||t.config.useNativeSDKToSend===!0,An=t=>t.filter(ua),ga=(t,e)=>`${t.replaceAll(" ","-")}___${e}`,Ss=["BeaconQueue","CustomConsentManager","DeviceModeDestinations","DeviceModeTransformation","ExternalAnonymousId","GoogleLinker","IubendaConsentManager","KetchConsentManager","NativeDestinationQueue","OneTrustConsentManager","StorageEncryption","StorageEncryptionLegacy","StorageMigrator","XhrQueue"],fa=["Bugsnag","ErrorReporting"],ha={rudderAnalyticsRemotePlugins:{url:()=>Promise.resolve(window.RudderStackGlobals&&window.RudderStackGlobals.app&&window.RudderStackGlobals.app.pluginsCDNPath?`${window.RudderStackGlobals.app.pluginsCDNPath}/rsa-plugins.js`:"https://cdn.rudderlabs.com/v3/modern/plugins//rsa-plugins.js"),format:"esm",from:"vite"}};function bs(t,e){let n=Object.assign(t,e);for(let s of Object.keys(n))typeof n[s]=="object"&&typeof e[s]=="object"&&(n[s]=bs(n[s],e[s]));return n}var pa=t=>bs({},(globalThis.__federation_shared__||{}).default||{});async function va(t){let e=ha[t];if(e.inited)return e.lib;if(["esm","systemjs"].includes(e.format))return new Promise((n,s)=>{(typeof e.url=="function"?e.url:()=>Promise.resolve(e.url))().then(i=>{import(i).then(a=>{if(!e.inited){let l=pa();a.init(l),e.lib=a,e.lib.init(l),e.inited=!0}n(e.lib)}).catch(s)})})}function M(t,e){if(!t?.default&&e){let n=Object.create(null);return n.default=t,n.__esModule=!0,n}return t}function B(t,e){return va(t).then(n=>n.get(e).then(s=>s()))}var ma=t=>{switch(t){case"BeaconQueue":return()=>B("rudderAnalyticsRemotePlugins","./BeaconQueue").then(e=>M(e,!0));case"CustomConsentManager":return()=>B("rudderAnalyticsRemotePlugins","./CustomConsentManager").then(e=>M(e,!0));case"DeviceModeDestinations":return()=>B("rudderAnalyticsRemotePlugins","./DeviceModeDestinations").then(e=>M(e,!0));case"DeviceModeTransformation":return()=>B("rudderAnalyticsRemotePlugins","./DeviceModeTransformation").then(e=>M(e,!0));case"ExternalAnonymousId":return()=>B("rudderAnalyticsRemotePlugins","./ExternalAnonymousId").then(e=>M(e,!0));case"GoogleLinker":return()=>B("rudderAnalyticsRemotePlugins","./GoogleLinker").then(e=>M(e,!0));case"KetchConsentManager":return()=>B("rudderAnalyticsRemotePlugins","./KetchConsentManager").then(e=>M(e,!0));case"IubendaConsentManager":return()=>B("rudderAnalyticsRemotePlugins","./IubendaConsentManager").then(e=>M(e,!0));case"NativeDestinationQueue":return()=>B("rudderAnalyticsRemotePlugins","./NativeDestinationQueue").then(e=>M(e,!0));case"OneTrustConsentManager":return()=>B("rudderAnalyticsRemotePlugins","./OneTrustConsentManager").then(e=>M(e,!0));case"StorageEncryption":return()=>B("rudderAnalyticsRemotePlugins","./StorageEncryption").then(e=>M(e,!0));case"StorageEncryptionLegacy":return()=>B("rudderAnalyticsRemotePlugins","./StorageEncryptionLegacy").then(e=>M(e,!0));case"StorageMigrator":return()=>B("rudderAnalyticsRemotePlugins","./StorageMigrator").then(e=>M(e,!0));case"XhrQueue":return()=>B("rudderAnalyticsRemotePlugins","./XhrQueue").then(e=>M(e,!0));default:return}},Ea=t=>{let e={};return t.forEach(n=>{if(Ss.includes(n)){let s=ma(n);s&&(e[n]=s)}}),e},Is=()=>({}),ya=()=>({}),Sa=t=>Ea?.(t)||{},ct={...Is(),...ya()},ba=t=>({...Sa(t)}),Rt=class{constructor(e,n,s){this.engine=e,this.errorHandler=n,this.logger=s,this.onError=this.onError.bind(this)}init(){o.lifecycle.status.value="pluginsLoading",ke("pluginsCDNPath",o.lifecycle.pluginsCDNPath.value),this.setActivePlugins(),this.registerLocalPlugins(),this.registerRemotePlugins(),this.attachEffects()}attachEffects(){X(()=>{(o.plugins.activePlugins.value.length===0||o.plugins.loadedPlugins.value.length+o.plugins.failedPlugins.value.length===o.plugins.totalPluginsToLoad.value)&&U(()=>{o.plugins.ready.value=!0,o.lifecycle.status.value="pluginsReady"})})}getPluginsToLoadBasedOnConfig(){let e=o.plugins.pluginsToLoadFromConfig.value;if(!e)return[];e=e.filter(r=>fa.includes(r)?(this.logger.warn(Ki(Ie,r)),!1):!0);let n=[{configurationStatus:()=>O(o.dataPlaneEvents.eventsQueuePluginName.value),configurationStatusStr:"Data plane events delivery is enabled",activePluginName:o.dataPlaneEvents.eventsQueuePluginName.value,supportedPlugins:Object.values(eo),shouldAddMissingPlugins:!0},{configurationStatus:()=>An(o.nativeDestinations.configuredDestinations.value).length>0,configurationStatusStr:"Device mode destinations are connected to the source",supportedPlugins:["DeviceModeDestinations","NativeDestinationQueue"]},{configurationStatus:()=>An(o.nativeDestinations.configuredDestinations.value).some(r=>r.shouldApplyDeviceModeTransformation),configurationStatusStr:"Device mode transformations are enabled for at least one destination",supportedPlugins:["DeviceModeTransformation"]},{configurationStatus:()=>O(o.consents.activeConsentManagerPluginName.value),configurationStatusStr:"Consent management is enabled",activePluginName:o.consents.activeConsentManagerPluginName.value,supportedPlugins:Object.values(bt)},{configurationStatus:()=>O(o.storage.encryptionPluginName.value),configurationStatusStr:"Storage encryption is enabled",activePluginName:o.storage.encryptionPluginName.value,supportedPlugins:Object.values(Ge)},{configurationStatus:()=>o.storage.migrate.value,configurationStatusStr:"Storage migration is enabled",supportedPlugins:["StorageMigrator"]}],s=!1;return n.forEach(r=>{r.configurationStatus()?(e=e.filter(r.activePluginName?i=>!(i!==r.activePluginName&&r.supportedPlugins.includes(i)):i=>O(i)),this.addMissingPlugins(r,s,e)):e=e.filter(r.basePlugins!==void 0?i=>!(r.basePlugins.includes(i)||r.supportedPlugins.includes(i)):i=>!r.supportedPlugins.includes(i))}),[...Object.keys(Is()),...e]}addMissingPlugins(e,n,s){let r=e.shouldAddMissingPlugins||n,i;e.activePluginName?i=[...e.basePlugins||[],e.activePluginName]:i=[...e.supportedPlugins];let a=i.filter(l=>!s.includes(l));a.length>0&&(r&&s.push(...a),this.logger.warn(Qi(Ie,e.configurationStatusStr,a,r)))}setActivePlugins(){let e=this.getPluginsToLoadBasedOnConfig(),n=[...Object.keys(ct),...Ss],s=[],r=[];e.forEach(i=>{n.includes(i)?s.push(i):r.push(i)}),r.length>0&&this.logger.warn(Xi(Ie,r)),U(()=>{o.plugins.totalPluginsToLoad.value=e.length,o.plugins.activePlugins.value=s,o.plugins.failedPlugins.value=r})}registerLocalPlugins(){let e=[];Object.entries(ct).forEach(([n,s])=>{o.plugins.activePlugins.value.includes(n)&&(m(s)?this.register([s()]):e.push(n))}),e.length>0&&(o.plugins.failedPlugins.value=[...o.plugins.failedPlugins.value,...e],this.logger.error(Yi(Ie,e)))}registerRemotePlugins(){let e=ba(o.plugins.activePlugins.value);Promise.all(Object.keys(e).map(async n=>{await e[n]().then(s=>this.register([s.default()])).catch(s=>{o.plugins.failedPlugins.value=[...o.plugins.failedPlugins.value,n],this.onError(s,`Failed to load plugin "${n}"`,s)})})).catch(n=>{this.onError(n)})}invokeMultiple(e,...n){try{return this.engine.invokeMultiple(e,...n)}catch(s){return this.onError(s,e),[]}}invokeSingle(e,...n){try{return this.engine.invokeSingle(e,...n)}catch(s){return this.onError(s,e),null}}register(e){e.forEach(n=>{try{this.engine.register(n,o)}catch(s){o.plugins.failedPlugins.value=[...o.plugins.failedPlugins.value,n.name],this.onError(s,`Failed to register plugin "${n.name}"`)}})}unregisterLocalPlugins(){Object.keys(ct).forEach(e=>{try{this.engine.unregister(e)}catch(n){this.onError(n,`Failed to unregister plugin "${e}"`)}})}onError(e,n,s){this.errorHandler.onError({error:e,context:Ie,customMessage:n,groupingHash:s})}},x="cookieStorage",F="localStorage",V="sessionStorage",W="memoryStorage",de="none",Ia="test_rudder_cookie",Ta="test_rudder_ls",Aa="test_rudder_ss",Ra="rl_user_id",Oa="rl_trait",_a="rl_anonymous_id",Na="rl_group_id",Pa="rl_group_trait",ka="rl_page_init_referrer",Ca="rl_page_init_referring_domain",Da="rl_session",La="rl_auth_token",fe={userId:Ra,userTraits:Oa,anonymousId:_a,groupId:Na,groupTraits:Pa,initialReferrer:ka,initialReferringDomain:Ca,sessionInfo:Da,authToken:La},wa="__tld__",Ts="clientDataInCookie",As="clientDataInLocalStorage",Ua="clientDataInMemory",Rs="clientDataInSessionStorage",Os=["userId","userTraits","anonymousId","groupId","groupTraits","initialReferrer","initialReferringDomain","sessionInfo","authToken"],he={[x]:Ts,[F]:As,[W]:Ua,[V]:Rs},Rn=(t,e)=>{try{return encodeURIComponent(t)}catch(n){e?.error(br,n);return}},On=t=>{try{return decodeURIComponent(t)}catch{return}},$a=t=>{let e={},n=t.split(/\s*;\s*/),s;return n[0]&&n.forEach(r=>{s=r.split("=");let i=s[0]?On(s[0]):void 0;i&&(e[i]=s[1]?On(s[1]):void 0)}),e},Ma=(t,e,n,s)=>{let r={...n||{}},i=`${Rn(t,s)}=${Rn(e,s)}`;G(e)&&(r.maxage=-1),r.maxage&&(r.expires=new Date(+new Date+r.maxage)),r.path&&(i+=`; path=${r.path}`),r.domain&&(i+=`; domain=${r.domain}`),r.expires&&(i+=`; expires=${r.expires.toUTCString()}`),r.samesite&&(i+=`; samesite=${r.samesite}`),r.secure&&(i+="; secure"),globalThis.document.cookie=i},Ot=()=>{let t=globalThis.document.cookie;return $a(t)},Ba=t=>Ot()[t],J=function(t,e,n,s){switch(arguments.length){case 4:case 3:case 2:return Ma(t,e,n,s);case 1:return t?Ba(t):Ot();default:return Ot()}},xa=t=>{let e=document.createElement("a");return e.href=t,e.hostname},Ga=t=>{let n=(typeof globalThis.URL!="function"?xa(t):new URL(t).hostname)?.split(".")??[],s=n[n.length-1],r=[];if(n.length===4&&s&&s===parseInt(s,10).toString())return r;if(n.length<=1)return n[0]&&n[0].indexOf("localhost")!==-1?["localhost"]:r;for(let i=n.length-2;i>=0;i-=1)r.push(n.slice(i).join("."));return r},Fa=t=>{let e=Ga(t);for(let n=0;n<e.length;n+=1){let s=e[n],r=wa,i={domain:`${s.indexOf("localhost")!==-1?"":"."}${s}`};try{if(J(r,1,i),J(r))return J(r,null,i),s}catch{try{J(r,null,i)}catch{}}}return""},Va=()=>{let t=`.${Fa(globalThis.location.href)}`;return{maxage:$r,path:"/",domain:!t||t==="."?void 0:t,samesite:"Lax",enabled:!0}},ja=()=>({enabled:!0}),Ha=()=>({enabled:!0}),Ka=()=>({enabled:!0}),_t=class{constructor(e){k(this,"isEnabled",!0);k(this,"length",0);k(this,"data",{});this.options=Ka(),this.logger=e}configure(e){return this.options=L(this.options,e??{}),this.isEnabled=!!this.options.enabled,this.options}setItem(e,n){return this.data[e]=n,this.length=Object.keys(this.data).length,n}getItem(e){return e in this.data?this.data[e]:null}removeItem(e){return e in this.data&&delete this.data[e],this.length=Object.keys(this.data).length,null}clear(){this.data={},this.length=0}key(e){return this.keys()[e]??null}keys(){return Object.keys(this.data)}},qe=new _t(te),He={exports:{}},Qa=He.exports,_n;function za(){return _n||(_n=1,(function(t,e){(function(n,s){t.exports=s()})(Qa,function(){function n(f){return f=JSON.stringify(f),!!/^\{[\s\S]*\}$/.test(f)}function s(f){return f===void 0||typeof f=="function"?f+"":JSON.stringify(f)}function r(f){if(typeof f=="string")try{return JSON.parse(f)}catch{return f}}function i(f){return{}.toString.call(f)==="[object Function]"}function a(f){return Object.prototype.toString.call(f)==="[object Array]"}function l(f){var p="_Is_Incognit",h="yes";try{f||(f=window.localStorage),f.setItem(p,h),f.removeItem(p)}catch{var E={};E._data={},E.setItem=function(P,ie){return E._data[P]=String(ie)},E.getItem=function(P){return E._data.hasOwnProperty(P)?E._data[P]:void 0},E.removeItem=function(P){return delete E._data[P]},E.clear=function(){return E._data={}},f=E}finally{f.getItem(p)===h&&f.removeItem(p)}return f}var c=l();function d(){if(!(this instanceof d))return new d}d.prototype={set:function(p,h){if(p&&!n(p))c.setItem(p,s(h));else if(n(p))for(var E in p)this.set(E,p[E]);return this},get:function(p){if(p===void 0){var h={};return this.forEach(function(De,be){return h[De]=be}),h}if(p.charAt(0)==="?")return this.has(p.substr(1));var E=arguments;if(E.length>1){for(var R={},P=0,ie=E.length;P<ie;P++){var rt=r(c.getItem(E[P]));this.has(E[P])&&(R[E[P]]=rt)}return R}return r(c.getItem(p))},clear:function(){return c.clear(),this},remove:function(p){var h=this.get(p);return c.removeItem(p),h},has:function(p){return{}.hasOwnProperty.call(this.get(),p)},keys:function(){var p=[];return this.forEach(function(h){p.push(h)}),p},forEach:function(p){for(var h=0,E=c.length;h<E;h++){var R=c.key(h);p(R,this.get(R))}return this},search:function(p){for(var h=this.keys(),E={},R=0,P=h.length;R<P;R++)h[R].indexOf(p)>-1&&(E[h[R]]=this.get(h[R]));return E},len:function(){return c.length}};var g=null;function v(f,p){var h=arguments,E=null;if(g||(g=d()),h.length===0)return g.get();if(h.length===1){if(typeof f=="string")return g.get(f);if(n(f))return g.set(f)}if(h.length===2&&typeof f=="string"){if(!p)return g.remove(f);if(p&&typeof p=="string")return g.set(f,p);p&&i(p)&&(E=null,E=p(f,g.get(f)),v.set(f,E))}if(h.length===2&&a(f)&&i(p))for(var R=0,P=f.length;R<P;R++)E=p(f[R],g.get(f[R])),v.set(f[R],E);return v}for(var y in d.prototype)v[y]=d.prototype[y];return v})})(He)),He.exports}var Wa=za(),oe=gs(Wa),_s=t=>{let e=["QuotaExceededError","NS_ERROR_DOM_QUOTA_REACHED"],n=[22,1014];return t instanceof DOMException?e.includes(t.name)||n.includes(t.code):!1},pe=(t=F,e,n)=>{let s,r,i=Ir(pt,t),a="unavailable",l=!0,c;try{switch(t){case W:return!0;case x:s=e,r=Ia;break;case F:s=e??globalThis.localStorage,r=Ta;break;case V:s=e??globalThis.sessionStorage,r=Aa;break;default:return!1}if(s&&(s.setItem(r,"true"),s.getItem(r)))return s.removeItem(r),!0;l=!1}catch(d){l=!1,c=d,_s(d)&&(a="full")}return l||n?.warn(`${i}${a}.`,c),!1},Nt=class{constructor(e){k(this,"isSupportAvailable",!0);k(this,"isEnabled",!0);k(this,"length",0);this.options=ja(),this.logger=e}configure(e){return this.options=L(this.options,e??{}),this.isSupportAvailable=pe(F),this.isEnabled=!!(this.options.enabled&&this.isSupportAvailable),this.options}setItem(e,n){oe.set(e,n),this.length=oe.len()}getItem(e){let n=oe.get(e);return w(n)?null:n}removeItem(e){oe.remove(e),this.length=oe.len()}clear(){oe.clear(),this.length=0}key(e){return this.keys()[e]??null}keys(){return oe.keys()}},qt=new Nt(te),Pt=class{constructor(e){k(this,"isSupportAvailable",!0);k(this,"isEnabled",!0);k(this,"length",0);this.options=Ha(),this.logger=e}configure(e){return this.options=L(this.options,e??{}),this.isSupportAvailable=pe(V),this.isSupportAvailable&&(this.store=globalThis.sessionStorage),this.isEnabled=!!(this.options.enabled&&this.isSupportAvailable),this.options}setItem(e,n){this.store&&(this.store.setItem(e,n),this.length=this.store.length)}getItem(e){if(!this.store)return null;let n=this.store.getItem(e);return w(n)?null:n}removeItem(e){this.store&&(this.store.removeItem(e),this.length=this.store.length)}clear(){this.store?.clear(),this.length=0}key(e){return this.store?.key(e)??null}keys(){let e=[];if(!this.store)return e;for(let n=0;n<this.store.length;n+=1){let s=this.store.key(n);s!==null&&e.push(s)}return e}},Jt=new Pt(te),kt=class{constructor(e){k(this,"isSupportAvailable",!0);k(this,"isEnabled",!0);k(this,"length",0);this.logger=e}configure(e){return this.options||(this.options=Va()),this.options=L(this.options,e??{}),this.options.sameDomainCookiesOnly&&delete this.options.domain,this.isSupportAvailable=pe(x,this),this.isEnabled=!!(this.options.enabled&&this.isSupportAvailable),this.options}setItem(e,n){return J(e,n,this.options,this.logger),this.length=Object.keys(J()).length,!0}getItem(e){let n=J(e);return w(n)?null:n}removeItem(e){let n=this.setItem(e,null);return this.length=Object.keys(J()).length,n}clear(){}key(e){return this.keys()[e]??null}keys(){return Object.keys(J())}},Zt=new kt(te),H=t=>{switch(t){case F:return qt;case V:return Jt;case W:return qe;case x:return Zt;default:return qe}},Xa=t=>{let e=Zt.configure(t);o.storage.cookie.value={maxage:e.maxage,path:e.path,domain:e.domain,samesite:e.samesite,expires:e.expires,secure:e.secure}},Ya=t=>{qt.configure(t)},qa=t=>{qe.configure(t)},Ja=t=>{Jt.configure(t)},Za=(t={},e={},n={},s={})=>{Xa(t),Ya(e),qa(n),Ja(s)},Ct=class{constructor(e,n,s){this.id=e.id,this.name=e.name,this.isEncrypted=e.isEncrypted??!1,this.validKeys=e.validKeys??{},this.engine=n,this.noKeyValidation=Object.keys(this.validKeys).length===0,this.noCompoundKey=e.noCompoundKey,this.originalEngine=this.engine,this.errorHandler=e.errorHandler,this.logger=e.logger,this.pluginsManager=s}createValidKey(e){let{name:n,id:s,validKeys:r,noKeyValidation:i,noCompoundKey:a}=this;if(i)return a?e:[n,s,e].join(".");let l;return Object.values(r).forEach(c=>{c===e&&(l=a?e:[n,s,e].join("."))}),l}swapQueueStoreToInMemoryEngine(){let{name:e,id:n,validKeys:s,noCompoundKey:r}=this,i=H(W);Object.keys(s).forEach(a=>{let l=this.get(s[a]),c=r?a:[e,n,a].join(".");i.setItem(c,l),this.remove(a)}),this.engine=i}set(e,n){let s=this.createValidKey(e);if(s)try{this.engine.setItem(s,this.encrypt(K(n,!1,[],this.logger)))}catch(r){if(_s(r))this.logger.warn(Bi(`Store ${this.id}`)),this.swapQueueStoreToInMemoryEngine(),this.set(e,n);else{let i=bi(e);this.onError(r,i,i)}}}get(e){let n=this.createValidKey(e),s;try{return!n||(s=this.decrypt(this.engine.getItem(n)),Q(s)||s==="")?null:JSON.parse(s)}catch(r){let i=o.storage.encryptionPluginName.value;if(!i||!o.plugins.failedPlugins.value.includes(i)){let l=Ii(e);this.onError(r,l,l)}return null}}remove(e){let n=this.createValidKey(e);n&&this.engine.removeItem(n)}getOriginalEngine(){return this.originalEngine}decrypt(e){return Q(e)?null:this.crypto(e,"decrypt")}encrypt(e){return this.crypto(e,"encrypt")}crypto(e,n){if(!this.isEncrypted||!e||typeof e!="string"||sr(e)==="")return e;let r=`storage.${n}`,i=this.pluginsManager?this.pluginsManager.invokeSingle(r,e):e;return typeof i>"u"?e:i??""}onError(e,n,s){this.errorHandler.onError({error:e,context:`Store ${this.id}`,customMessage:n,groupingHash:s})}},el=(t,e)=>{let n;if(t.consents.preConsent.value.enabled)switch(t.consents.preConsent.value.storage?.strategy){case"none":n=de;break;case"session":e!=="sessionInfo"&&(n=de);break;case"anonymousId":e!=="anonymousId"&&(n=de);break}return n},Dt=class{constructor(e,n,s){k(this,"stores",{});k(this,"isInitialized",!1);this.errorHandler=n,this.logger=s,this.pluginsManager=e}init(){if(this.isInitialized)return;let e=o.loadOptions.value,n={cookieStorageOptions:{samesite:e.sameSiteCookie,secure:e.secureCookie,domain:e.setCookieDomain,sameDomainCookiesOnly:e.sameDomainCookiesOnly},localStorageOptions:{},inMemoryStorageOptions:{},sessionStorageOptions:{}};Za(Ae(L(n.cookieStorageOptions??{},o.storage.cookie?.value??{})),Ae(n.localStorageOptions),Ae(n.inMemoryStorageOptions),Ae(n.sessionStorageOptions)),this.initClientDataStores(),this.isInitialized=!0}initClientDataStores(){this.initializeStorageState(),[W,F,x,V].forEach(n=>{H(n)?.isEnabled&&this.setStore({id:he[n],name:he[n],isEncrypted:!0,noCompoundKey:!0,type:n,errorHandler:this.errorHandler,logger:this.logger})})}initializeStorageState(){let e=o.storage.type.value,n=o.loadOptions.value.storage?.entries,s=o.consents.postConsent.value.storage;(O(s?.type)||O(s?.entries))&&(e=s?.type,n=s?.entries);let r=!0,i={};Os.forEach(a=>{let l=a,c=a,d=n?.[l]?.type,v=el(o,a)??d??e??St,y=this.getResolvedStorageTypeForEntry(v,a);y!==de&&(r=!1),i={...i,[a]:{type:y,key:fe[c]}}}),U(()=>{o.storage.type.value=e,o.storage.entries.value=i,o.storage.trulyAnonymousTracking.value=r})}getResolvedStorageTypeForEntry(e,n){let s=e;switch(e){case F:H(F)?.isEnabled||(s=W);break;case V:H(V)?.isEnabled||(s=W);break;case W:case de:break;case x:default:H(x)?.isEnabled?s=x:H(F)?.isEnabled?s=F:H(V)?.isEnabled?s=V:s=W;break}return s!==e&&this.logger.warn(xi(or,n,e,s)),s}setStore(e){let n=H(e.type);return this.stores[e.id]=new Ct(e,n,this.pluginsManager),this.stores[e.id]}getStore(e){return this.stores[e]}},tl=t=>N(t)&&N(t.source)&&!Q(t.source.id)&&N(t.source.config)&&Array.isArray(t.source.destinations),nl=t=>typeof t=="string"&&is.includes(t),Ns=t=>{let e=new URL(t),{host:n,protocol:s}=e,r=n.split("."),i;return r.length>2?i=`${r[r.length-2]}.${r[r.length-1]}`:i=n,{topDomain:i,protocol:s}},sl=t=>{let{topDomain:e,protocol:n}=Ns(t);return`${n}//${e}`},rl=(t,e)=>{let n=e?window.location.origin:sl(window.location.href),s=t.startsWith("/")?t.substring(1):t;return`${n}/${s}`},il=t=>{let{topDomain:e}=Ns(window.location.href);return e===t},me=t=>t?.endsWith("/")?me(t.substring(0,t.length-1)):t,Lt=t=>{try{return new URL(t).host}catch{return null}},Ps=t=>Lt(t)??"",ol=t=>{let e={};try{let n=new URL(t),s="utm_";n.searchParams.forEach((r,i)=>{if(i.startsWith(s)){let a=i.substring(s.length);a==="campaign"&&(a="name"),e[a]=r}})}catch{}return e},al=t=>{let e=t;try{let n=new URL(t);e=n.origin+n.pathname+n.search}catch{}return e},ll=t=>t.replace(/\/{2,}/g,"/"),Ee=t=>{if(!_(t))return!1;try{return m(globalThis.URL)&&new URL(t),Ji.test(t)}catch{return!1}},ut="none",dt="immediate",cl=t=>t?.statsCollection?.errors?.enabled===!0,ul=t=>t?.statsCollection?.metrics?.enabled===!0,dl=t=>{let e={sendPageEvent:!1,trackConsent:!1,discardPreConsentEvents:!1};if(N(t)){let n=b(t);e.storage=n.storage,ee(n.integrations)&&(e.integrations=n.integrations),e.discardPreConsentEvents=n.discardPreConsentEvents===!0,e.sendPageEvent=n.sendPageEvent===!0,e.trackConsent=n.trackConsent===!0,ee(n.consentManagement)&&(e.consentManagement=L(n.consentManagement,{enabled:o.consents.enabled.value}))}return e},Nn=t=>ee(t)||Array.isArray(t),gl=(t,e)=>{let{provider:n}=t,s=n?bt[n]:void 0;return n&&!s&&(e.error(ai(j,n,bt)),n=void 0),{provider:n,consentManagerPluginName:s}},ks=(t,e)=>{let n,s=[],r=[],i=!1,a,l=t?.enabled===!0;ee(t)&&l&&({provider:a,consentManagerPluginName:n}=gl(t,e),Nn(t.allowedConsentIds)&&(s=t.allowedConsentIds,i=!0),Nn(t.deniedConsentIds)&&(r=t.deniedConsentIds,i=!0));let c={allowedConsentIds:s,deniedConsentIds:r};return l=l&&!!n,{provider:a,consentManagerPluginName:n,initialized:i,enabled:l,consentsData:c}},fl=()=>{let t=document.querySelector("script[data-rsa-write-key]");if(t&&t.dataset.rsaWriteKey===o.lifecycle.writeKey.value)return t.src;let e=document.getElementsByTagName("script"),n=/(?:^|\/)rsa(\.min)?\.js$/;for(let s of e){let r=s.getAttribute("src");if(r&&n.test(r))return r}},hl=t=>{o.reporting.isErrorReportingEnabled.value=cl(t.source.config)&&!hr(),o.reporting.isMetricsReportingEnabled.value=ul(t.source.config)},pl=t=>{let{useServerSideCookies:e,dataServiceEndpoint:n,storage:s,setCookieDomain:r,sameDomainCookiesOnly:i}=o.loadOptions.value,a=s?.cookie,l=!1,c;if(e){l=e;let d=a.domain??r,g=O(d)&&!il(tn(d))||i,v=rl(n??to,g);if(Ee(v)){c=me(v);let y=Lt(window.location.href),f=Lt(v);y!==f&&(a={...a,samesite:"None",secure:!0}),!i&&g&&f!==tn(d)&&(l=!1,t.warn(Ni(j,d,f)))}else l=!1}return{sscEnabled:l,cookieOptions:a,finalDataServiceUrl:c}},vl=t=>{let{storage:e}=o.loadOptions.value,n=e?.type;O(n)&&!nl(n)&&(t.warn(Ri(j,n,St)),n=St);let s=e?.encryption?.version,r=s&&Ge[s];!w(s)&&w(r)?(t.warn(Oi(j,s,Ge,le)),s=le):w(s)&&(s=le);let i=e?.migrate,a=i&&s===le;i===!0&&a!==i&&t.warn(_i(j,s,le));let{sscEnabled:l,finalDataServiceUrl:c,cookieOptions:d}=pl(t);U(()=>{o.storage.type.value=n,o.storage.cookie.value=d,o.serverCookies.isEnabledServerSideCookies.value=l,o.serverCookies.dataServiceUrl.value=c,o.storage.encryptionPluginName.value=Ge[s],o.storage.migrate.value=a})},ml=t=>{let{provider:e,consentManagerPluginName:n,initialized:s,enabled:r,consentsData:i}=ks(o.loadOptions.value.consentManagement,t),a=o.loadOptions.value.preConsent,l=a?.storage?.strategy??ut,c=["none","session","anonymousId"];O(l)&&!c.includes(l)&&(l=ut,t.warn(ji(j,a?.storage?.strategy,ut)));let d=a?.events?.delivery??dt,g=["immediate","buffer"];O(d)&&!g.includes(d)&&(d=dt,t.warn(Hi(j,a?.events?.delivery,dt))),U(()=>{o.consents.activeConsentManagerPluginName.value=n,o.consents.initialized.value=s,o.consents.enabled.value=r,o.consents.data.value=i,o.consents.provider.value=e,o.consents.preConsent.value={enabled:o.loadOptions.value.preConsent?.enabled===!0&&s===!1&&r===!0,storage:{strategy:l},events:{delivery:d}}})},El=t=>{let e=o.consents.resolutionStrategy.value,n;N(t.consentManagementMetadata)&&(o.consents.provider.value&&(e=t.consentManagementMetadata.providers.find(s=>s.provider===o.consents.provider.value)?.resolutionStrategy??o.consents.resolutionStrategy.value),n=t.consentManagementMetadata),o.consents.provider.value==="custom"&&(e=void 0),U(()=>{o.consents.metadata.value=b(n),o.consents.resolutionStrategy.value=e})},yl=t=>{if(o.dataPlaneEvents.deliveryEnabled.value){let e="XhrQueue",n=e;o.loadOptions.value.useBeacon&&(o.capabilities.isBeaconAvailable.value?n="BeaconQueue":(n=e,t.warn(Ci(j)))),U(()=>{o.dataPlaneEvents.eventsQueuePluginName.value=n})}},Sl=(t,e,n,s,r)=>{let i=new URLSearchParams({p:Xn,v:Pe,build:Ce,writeKey:e,lockIntegrationsVersion:n.toString(),lockPluginsVersion:s.toString()}),a=ds,l=i,c="/sourceConfig/",d="";if(Ee(t)){let g=new URL(t);me(g.pathname).endsWith("/sourceConfig")||(g.pathname=`${me(g.pathname)}/sourceConfig/`),g.pathname=ll(g.pathname),i.forEach((v,y)=>{g.searchParams.get(y)===null&&g.searchParams.set(y,v)}),a=g.origin,c=g.pathname,l=g.searchParams,d=g.hash}else r.warn(Fi(j,t));return`${a}${c}?${l}${d}`},bl=t=>t.map(e=>({id:e.id,displayName:e.destinationDefinition.displayName,enabled:e.enabled,config:e.config,shouldApplyDeviceModeTransformation:e.shouldApplyDeviceModeTransformation??!1,propagateEventsUntransformedOnError:e.propagateEventsUntransformedOnError??!1,userFriendlyId:ga(e.destinationDefinition.displayName,e.id),isCustomIntegration:e.destinationDefinition.displayName===so})),Cs=(t,e,n,s,r,i,a)=>{let l;if(i){if(!Ee(i))return a.error(oi(j,t,i)),null;l=me(i)}else if(l=n,o.context.app.value.installType==="cdn"){let c=fl();c&&(l=c.split("/").slice(0,-1).concat(e).join("/"))}return r&&(l=l.replace(new RegExp(`/${Yt}/${Ce}/${e}$`),`/${s}/${Ce}/${e}`)),l},Il=(t,e,n,s)=>Cs("integrations",nt,cs,t,e,n,s),Tl=(t,e,n,s)=>Cs("plugins",ls,us,t,e,n,s),wt=class{constructor(e,n,s){this.errorHandler=n,this.logger=s,this.httpClient=e,this.onError=this.onError.bind(this),this.processConfig=this.processConfig.bind(this)}attachEffects(){X(()=>{this.logger.setMinLogLevel(o.lifecycle.logLevel.value)})}init(){let{logLevel:e,configUrl:n,lockIntegrationsVersion:s,lockPluginsVersion:r,destSDKBaseURL:i,pluginsSDKBaseURL:a,integrations:l}=o.loadOptions.value,c=Il(Pe,s,i,this.logger);if(G(c))return;let d;d=Tl(Pe,r,a,this.logger),d!==null&&(this.attachEffects(),o.lifecycle.activeDataplaneUrl.value=me(o.lifecycle.dataPlaneUrl.value),vl(this.logger),ml(this.logger),yl(this.logger),U(()=>{o.lifecycle.integrationsCDNPath.value=c,o.lifecycle.pluginsCDNPath.value=d,e&&(o.lifecycle.logLevel.value=e),o.lifecycle.sourceConfigUrl.value=Sl(n,o.lifecycle.writeKey.value,s,r,this.logger),o.metrics.metricsServiceUrl.value=`${o.lifecycle.activeDataplaneUrl.value}/${no}`,o.nativeDestinations.loadOnlyIntegrations.value=l}),this.getConfig())}onError(e,n,s){this.errorHandler.onError({error:e,context:j,customMessage:n,groupingHash:s})}processConfig(e,n){if(!O(e)){O(n)?this.onError(n.error,pn):this.onError(new Error(pn));return}let s;try{_(e)?s=JSON.parse(e):s=e}catch(i){this.onError(i,fn);return}if(!tl(s)){this.onError(new Error(fn));return}if(s.source.enabled===!1){this.logger.error(ti);return}hl(s);let r=s.source.destinations.length>0?bl(s.source.destinations):[];U(()=>{o.source.value={config:s.source.config,name:s.source.name,id:s.source.id,workspaceId:s.source.workspaceId},o.nativeDestinations.configuredDestinations.value=r,o.plugins.pluginsToLoadFromConfig.value=o.loadOptions.value.plugins??[],El(s),o.lifecycle.status.value="configured"})}getConfig(){let e=o.loadOptions.value.getSourceConfig;if(e){if(!m(e)){this.logger.error(ii(j));return}let n=e();n instanceof Promise?n.then(s=>this.processConfig(s)).catch(s=>{this.onError(s,"SourceConfig")}):this.processConfig(n)}else this.httpClient.getAsyncData({url:o.lifecycle.sourceConfigUrl.value,options:{headers:{"Content-Type":void 0}},callback:this.processConfig})}},Al=()=>{let t=/([A-Z]+[+-]\d+)/.exec(new Date().toString());return t?.[1]?t[1]:"NA"},Ds=(t=()=>document)=>t()?.referrer||"$direct",Rl=(t=()=>document)=>{let n=t().getElementsByTagName("link"),s="";for(let r=0;n[r];r+=1){let i=n[r];if(i.getAttribute("rel")==="canonical"&&!s){s=i.getAttribute("href")??"";break}}return s},Ol=(t=()=>globalThis.navigator)=>{let e=t();if(w(e))return null;let{userAgent:n}=e,{brave:s}=e;if(s&&Object.getPrototypeOf(s).isBrave){let r=n.match(/(chrome)\/([\w.]+)/i);r&&(n=`${n} Brave/${r[2]}`)}return n},_l=(t=()=>globalThis.navigator)=>{let e=t();return w(e)?null:e.language??e.browserLanguage},Ls=(t=()=>globalThis.location,e=()=>document)=>{let n=t(),s=Rl(e),r=n.pathname,{href:i}=n,a=i,{search:l}=n;if(s)try{let v=new URL(s);v.search===""?a=s+l:a=s,r=v.pathname}catch{}let c=al(a),{title:d}=e(),g=Ds(e);return{path:r,referrer:g,referring_domain:Ps(g),search:l,title:d,url:c,tab_url:i}},Nl=(t,e="none")=>{e==="none"&&t(void 0),e==="default"&&t(navigator.userAgentData),e==="full"&&navigator.userAgentData?.getHighEntropyValues(["architecture","bitness","brands","mobile","model","platform","platformVersion","uaFullVersion","fullVersionList","wow64"]).then(n=>{t(n)}).catch(()=>{t()})},Pl=()=>{let t=globalThis.document.createElement("div");return t.setAttribute("data-a-b","c"),t.dataset?t.dataset.aB==="c":!1},Ut={URL:()=>!m(globalThis.URL)||!m(globalThis.URLSearchParams),Promise:()=>!m(globalThis.Promise),"Number.isNaN":()=>!m(globalThis.Number.isNaN),"Number.isInteger":()=>!m(globalThis.Number.isInteger),"Array.from":()=>!m(globalThis.Array.from),"Array.prototype.find":()=>!m(globalThis.Array.prototype.find),"Array.prototype.includes":()=>!m(globalThis.Array.prototype.includes),"String.prototype.endsWith":()=>!m(globalThis.String.prototype.endsWith),"String.prototype.startsWith":()=>!m(globalThis.String.prototype.startsWith),"String.prototype.includes":()=>!m(globalThis.String.prototype.includes),"String.prototype.replaceAll":()=>!m(globalThis.String.prototype.replaceAll),"String.fromCodePoint":()=>!m(globalThis.String.fromCodePoint),"Object.entries":()=>!m(globalThis.Object.entries),"Object.values":()=>!m(globalThis.Object.values),"Object.assign":()=>!m(globalThis.Object.assign),"Object.fromEntries":()=>!m(globalThis.Object.fromEntries),"Element.prototype.dataset":()=>!Pl(),TextEncoder:()=>!m(globalThis.TextEncoder)||!m(globalThis.TextDecoder),requestAnimationFrame:()=>!m(globalThis.requestAnimationFrame)||!m(globalThis.cancelAnimationFrame),CustomEvent:()=>!m(globalThis.CustomEvent),"navigator.sendBeacon":()=>!m(globalThis.navigator.sendBeacon),ArrayBuffer:()=>!m(globalThis.Uint8Array),Set:()=>!m(globalThis.Set),atob:()=>!m(globalThis.atob)},kl=()=>{let t=Object.keys(Ut),e=!1;for(let n=0;n<t.length;n++){let s=Ut[t[n]];if(m(s)&&s()){e=!0;break}}return e},Cl="https://polyfill-fastly.io/v3/polyfill.min.js",Dl=`${Cl}?version=3.111.0&features=${Object.keys(Ut).join("%2C")}`,Ll=10*1e3,Pn="rudderstackPolyfill",wl=()=>!Q(globalThis.crypto)&&m(globalThis.crypto.getRandomValues),kn=()=>!Q(globalThis.navigator.userAgentData),Ul=()=>!Q(globalThis.navigator.sendBeacon)&&m(globalThis.navigator.sendBeacon),Cn=()=>{let t={density:0,width:0,height:0,innerWidth:0,innerHeight:0};return t={width:globalThis.screen.width,height:globalThis.screen.height,density:globalThis.devicePixelRatio,innerWidth:globalThis.innerWidth,innerHeight:globalThis.innerHeight},t},$t=class{constructor(e,n,s){this.httpClient=e,this.errorHandler=n,this.logger=s,this.externalSrcLoader=new Xe(this.logger),this.onError=this.onError.bind(this),this.onReady=this.onReady.bind(this)}init(){this.prepareBrowserCapabilities(),this.attachWindowListeners()}detectBrowserCapabilities(){U(()=>{o.capabilities.storage.isCookieStorageAvailable.value=pe(x,H(x),this.logger),o.capabilities.storage.isLocalStorageAvailable.value=pe(F,void 0,this.logger),o.capabilities.storage.isSessionStorageAvailable.value=pe(V,void 0,this.logger),o.capabilities.isBeaconAvailable.value=Ul(),o.capabilities.isUaCHAvailable.value=kn(),o.capabilities.isCryptoAvailable.value=wl(),o.capabilities.isIE11.value=Kn(),o.capabilities.isOnline.value=globalThis.navigator.onLine,o.context.userAgent.value=Ol(),o.context.locale.value=_l(),o.context.screen.value=Cn(),o.context.timezone.value=Al(),kn()&&Nl(e=>{o.context["ua-ch"].value=e},o.loadOptions.value.uaChTrackLevel)}),X(()=>{o.loadOptions.value.sendAdblockPage===!0&&o.lifecycle.sourceConfigUrl.value!==void 0&&vs(this.httpClient)})}prepareBrowserCapabilities(){o.capabilities.isLegacyDOM.value=kl();let e=o.loadOptions.value.polyfillURL,n=Dl;if(ve(e)&&(Ee(e)?n=e:this.logger.warn(zi(pt,e))),o.loadOptions.value.polyfillIfRequired&&o.capabilities.isLegacyDOM.value&&Ee(n)){let r=n!==o.loadOptions.value.polyfillURL;if(r){let i=`RS_polyfillCallback_${o.lifecycle.writeKey.value}`,a=()=>{this.onReady(),delete globalThis[i]};globalThis[i]=a,n=`${n}&callback=${i}`}this.externalSrcLoader.loadJSFile({url:n,id:Pn,async:!0,timeout:Ll,callback:i=>{i?r||this.onReady():this.onError(new Error(Vi(Pn,n)))}})}else this.onReady()}attachWindowListeners(){globalThis.addEventListener("offline",()=>{o.capabilities.isOnline.value=!1}),globalThis.addEventListener("online",()=>{o.capabilities.isOnline.value=!0}),globalThis.addEventListener("resize",xr(()=>{o.context.screen.value=Cn()},this))}onReady(){this.detectBrowserCapabilities(),o.lifecycle.status.value="browserCapabilitiesReady"}onError(e,n){this.errorHandler.onError({error:e,context:pt,groupingHash:n})}},$l="web",Ml=["integrations","anonymousId","originalTimestamp"],Dn=["library","consentManagement","userAgent","ua-ch","screen"],gt=["id","anonymous_id","user_id","sent_at","timestamp","received_at","original_timestamp","event","event_text","channel","context_ip","context_request_ip","context_passed_ip","group_id","previous_id"],ws=t=>typeof t=="number"&&!Number.isNaN(t),Bl=(t,e)=>e.toString().length>=t,Je=t=>ws(t)&&t>=0&&Number.isInteger(t),Ln=10,Us=t=>{let{cutOff:e}=t,n=Date.now();return!!(e?.enabled&&e.expiresAt&&n>e.expiresAt)},wn=t=>!t.expiresAt||Date.now()>t.expiresAt||Us(t),xl=()=>Date.now(),Gl=(t,e)=>!t||!Je(t)||!Bl(Ln,t)?(e.warn(Mi(ae,t,Ln)),!1):!0,Fl=t=>{if(t?.enabled)return t.expiresAt??(Je(t.duration)?Date.now()+t.duration:void 0)},Vl=t=>{let{timeout:e,cutOff:n}=t,s=Date.now();return{id:s,expiresAt:s+e,timeout:e,autoTrack:!0,...n&&{cutOff:n}}},jl=(t,e)=>({id:Gl(t,e)?t:xl(),sessionStart:void 0,manualTrack:!0}),Oe=t=>t===x||t===F||t===V||t===W,Mt=()=>Ze(),Hl=t=>{if(Js(t)){let{entries:e,...n}=lt;return{...n,entries:{...e,anonymousId:t}}}return N(t)&&N(t.entries)?L(lt,t):{...lt}},Kl=t=>{let e=Ls(),n={};return Object.keys(e).forEach(s=>{n[s]=t?.[s]||e[s]}),n.initial_referrer=t?.initial_referrer||o.session.initialReferrer.value,n.initial_referring_domain=t?.initial_referring_domain||o.session.initialReferringDomain.value,n},Ql=(t,e)=>{let n=e?.page||{},s=t,r=Ls();return Object.keys(r).forEach(i=>{w(s[i])&&(s[i]=n[i]||r[i])}),w(s.initial_referrer)&&(s.initial_referrer=n.initial_referrer||o.session.initialReferrer.value),w(s.initial_referring_domain)&&(s.initial_referring_domain=n.initial_referring_domain||o.session.initialReferringDomain.value),s},ft=(t,e,n)=>{N(t)&&Object.keys(t).forEach(s=>{(gt.includes(s)||gt.includes(s.toLowerCase()))&&n.warn(Pi(Hn,s,e,gt))})},zl=(t,e)=>{let{properties:n,traits:s,context:r}=t,{traits:i}=r;ft(n,"properties",e),ft(s,"traits",e),ft(i,"context.traits",e)},Wl=(t,e)=>{e.anonymousId&&_(e.anonymousId)&&(t.anonymousId=e.anonymousId),ee(e.integrations)&&(t.integrations=e.integrations),e.originalTimestamp&&_(e.originalTimestamp)&&(t.originalTimestamp=e.originalTimestamp)},Xl=(t,e,n)=>{let s=t;return Object.keys(e).forEach(r=>{if(!Ml.includes(r)&&!Dn.includes(r))if(r!=="context")s=L(s,{[r]:e[r]});else if(!w(e[r])&&N(e[r])){let i={};Object.keys(e[r]).forEach(a=>{Dn.includes(a)||(i[a]=e[r][a])}),s=L(s,{...i})}else n.warn(ki(Hn))}),s},Yl=(t,e,n)=>{N(e)&&(Wl(t,e),t.context=Xl(t.context,e,n))},ql=t=>{let e;return o.loadOptions.value.useGlobalIntegrationsConfigInEvents?e=o.consents.postConsent.value.integrations??o.nativeDestinations.loadOnlyIntegrations.value:t?e=t:e=as,b(e)},Te=(t,e,n,s)=>{let r={channel:$l,context:{traits:b(o.session.userTraits.value),sessionId:o.session.sessionInfo.value.id||void 0,sessionStart:o.session.sessionInfo.value.sessionStart||void 0,...o.consents.enabled.value&&{consentManagement:{deniedConsentIds:b(o.consents.data.value.deniedConsentIds),allowedConsentIds:b(o.consents.data.value.allowedConsentIds),provider:o.consents.provider.value,resolutionStrategy:o.consents.resolutionStrategy.value}},"ua-ch":o.context["ua-ch"].value,app:o.context.app.value,library:o.context.library.value,userAgent:o.context.userAgent.value,os:o.context.os.value,locale:o.context.locale.value,screen:o.context.screen.value,campaign:ol(globalThis.location.href),page:Kl(n),timezone:o.context.timezone.value,...o.autoTrack.enabled.value&&{autoTrack:{...o.autoTrack.pageLifecycle.enabled.value&&{page:{pageViewId:o.autoTrack.pageLifecycle.pageViewId.value}}}}},originalTimestamp:vr(),messageId:Ze(),userId:t.userId||o.session.userId.value};Oe(o.storage.entries.value.anonymousId?.type)?r.anonymousId=o.session.anonymousId.value:r.anonymousId=Mt(),o.storage.trulyAnonymousTracking.value&&(r.context.trulyAnonymousTracking=!0),t.type==="identify"&&(r.context.traits=o.storage.entries.value.userTraits?.type!==de?b(o.session.userTraits.value):t.context.traits),t.type==="group"&&((t.groupId||o.session.groupId.value)&&(r.groupId=t.groupId||o.session.groupId.value),(t.traits||o.session.groupTraits.value)&&(r.traits=o.storage.entries.value.groupTraits?.type!==de?b(o.session.groupTraits.value):t.traits));let i=L(t,r);return i.event===void 0&&(i.event=null),i.properties===void 0&&(i.properties=null),Yl(i,e,s),zl(i,s),i.integrations=ql(i.integrations),i},Bt=class{constructor(e){this.logger=e}generatePageEvent(e,n,s,r){let i=s??{};return i=Ql(i,r),Te({properties:i,name:n,category:e,type:"page"},r,i,this.logger)}generateTrackEvent(e,n,s){return Te({properties:n,event:e,type:"track"},s,void 0,this.logger)}generateIdentifyEvent(e,n,s){return Te({userId:e,type:"identify",context:{traits:n}},s,void 0,this.logger)}generateAliasEvent(e,n,s){let i=Te({previousId:n,type:"alias"},s,void 0,this.logger);return i.userId=e??i.userId,i}generateGroupEvent(e,n,s){let r={type:"group"};return e&&(r.groupId=e),n&&(r.traits=n),Te(r,s,void 0,this.logger)}create(e){let n;switch(e.type){case"page":n=this.generatePageEvent(e.category,e.name,e.properties,e.options);break;case"track":n=this.generateTrackEvent(e.name,e.properties,e.options);break;case"identify":n=this.generateIdentifyEvent(e.userId,e.traits,e.options);break;case"alias":n=this.generateAliasEvent(e.to,e.from,e.options);break;default:n=this.generateGroupEvent(e.groupId,e.traits,e.options);break}return n}},xt=class{constructor(e,n,s,r){this.eventRepository=e,this.userSessionManager=n,this.errorHandler=s,this.logger=r,this.eventFactory=new Bt(this.logger)}init(){this.eventRepository.init()}resume(){this.eventRepository.resume()}addEvent(e){this.userSessionManager.refreshSession();let n=this.eventFactory.create(e);this.eventRepository.enqueue(n,e.callback)}},Gt=class{constructor(e,n,s,r,i){this.storeManager=n,this.pluginsManager=e,this.logger=i,this.errorHandler=r,this.httpClient=s,this.onError=this.onError.bind(this),this.serverSideCookieDebounceFuncs={},this.serverSideCookiesRequestInProgress={}}init(){this.syncStorageDataToState(),this.registerEffects()}syncStorageDataToState(){this.migrateStorageIfNeeded(),this.migrateDataFromPreviousStorage(),this.setUserId(this.getUserId()),this.setUserTraits(this.getUserTraits()),this.setGroupId(this.getGroupId()),this.setGroupTraits(this.getGroupTraits());let{externalAnonymousIdCookieName:e,anonymousIdOptions:n}=o.loadOptions.value,s;ve(e)&&typeof e=="string"&&(s=this.getExternalAnonymousIdByCookieName(e)),this.setAnonymousId(s??this.getAnonymousId(n)),this.setAuthToken(this.getAuthToken()),this.setInitialReferrerInfo(),this.configureSessionTracking()}configureSessionTracking(){let e;if(this.isPersistenceEnabledForStorageEntry("sessionInfo")){let n=this.getConfiguredSessionTrackingInfo(),s=this.getSessionInfo()??A.sessionInfo;e={autoTrack:n.autoTrack&&s.manualTrack!==!0,timeout:n.timeout,manualTrack:s.manualTrack,expiresAt:s.expiresAt,id:s.id,sessionStart:s.sessionStart},!e.autoTrack&&e.manualTrack!==!0?e=A.sessionInfo:n.cutOff?.enabled===!0&&(e.cutOff={enabled:!0,duration:n.cutOff.duration,expiresAt:s.cutOff?.expiresAt})}else e=A.sessionInfo;o.session.sessionInfo.value=e,o.session.sessionInfo.value.autoTrack&&this.startOrRenewAutoTracking(o.session.sessionInfo.value)}setInitialReferrerInfo(){let e=this.getInitialReferrer(),n=this.getInitialReferringDomain();if(e&&n)this.setInitialReferrer(e),this.setInitialReferringDomain(n);else{let s=e||Ds();this.setInitialReferrer(s),this.setInitialReferringDomain(Ps(s))}}isPersistenceEnabledForStorageEntry(e){return Oe(o.storage.entries.value[e]?.type)}migrateDataFromPreviousStorage(){let e=o.storage.entries.value,n=[x,F,V];Object.keys(e).forEach(s=>{let r=s,i=e[r]?.type,a=this.storeManager?.getStore(he[i]);a&&n.forEach(l=>{let c=this.storeManager?.getStore(he[l]);if(c&&l!==i){let d=c.get(fe[r]);qs(d)&&a.set(fe[r],d),c.remove(fe[r])}})})}migrateStorageIfNeeded(e,n){if(!o.storage.migrate.value)return;let s=e??[];s.length===0&&[Ts,As,Rs].forEach(a=>{let l=this.storeManager?.getStore(a);l&&s.push(l)}),(n??Object.keys(fe)).forEach(i=>{let a=fe[i];s.forEach(l=>{let c=this.pluginsManager?.invokeSingle("storage.migrate",a,l.engine,this.errorHandler,this.logger);Q(c)||l.set(a,c)})})}getConfiguredSessionTrackingInfo(){let e=o.loadOptions.value.sessions.autoTrack!==!1;if(!e)return{autoTrack:e};let n,s=o.loadOptions.value.sessions?.timeout;Je(s)?n=s:(this.logger.warn(Di(ae,s,vt)),n=vt),n===0&&(this.logger.warn(Ui(ae)),e=!1),n>0&&n<un&&this.logger.warn($i(ae,n,un));let r=this.getCutOffInfo(n);return{timeout:n,autoTrack:e,cutOff:r}}getCutOffInfo(e){let n=o.loadOptions.value.sessions.cutOff,s,r=!1;return n.enabled===!0&&(s=n.duration,r=!0,Je(s)?s<e&&(this.logger.warn(wi(ae,s,e)),r=!1):(this.logger.warn(Li(ae,s,cn)),s=cn)),{enabled:r,duration:s}}onError(e,n,s){this.errorHandler.onError({error:e,context:ae,customMessage:n,groupingHash:s})}getEncryptedCookieData(e,n){let s=[];return e.forEach(r=>{let i=n?.encrypt(K(r.value,!1,[],this.logger));ve(i)&&s.push({name:r.name,value:i})}),s}makeRequestToSetCookie(e,n){this.httpClient?.getAsyncData({url:o.serverCookies.dataServiceUrl.value,options:{method:"POST",data:K({reqType:"setCookies",workspaceId:o.source.value?.workspaceId,data:{options:{maxAge:o.storage.cookie.value?.maxage,path:o.storage.cookie.value?.path,domain:o.storage.cookie.value?.domain,sameSite:o.storage.cookie.value?.samesite,secure:o.storage.cookie.value?.secure,expires:o.storage.cookie.value?.expires},cookies:e}}),sendRawData:!0,withCredentials:!0},isRawResponse:!0,callback:n})}setServerSideCookies(e,n,s){let r=Object.keys(e),i=()=>r.map(d=>({name:e[d].name,value:o.session[d].value})),a={};r.forEach(d=>{a[e[d].name]=s?.get(e[d].name)});let l=()=>{r.forEach(d=>{this.serverSideCookiesRequestInProgress[d]=!1})},c=()=>{i().forEach(d=>{n&&n(d.name,d.value)})};try{let d={};r.forEach(v=>{d[e[v].name]=o.session[v].value});let g=this.getEncryptedCookieData(i(),s);g.length>0?this.makeRequestToSetCookie(g,(v,y)=>{l(),y?.xhr?.status===200?i().forEach(f=>{let p=a[f.name],h=s?.get(f.name);K(d[f.name],!1,[])!==K(h,!1,[])&&(G(p)&&G(h)&&this.logger.error(Ai(f.name)),n&&n(f.name,f.value))}):(this.logger.error(Ti(y?.xhr?.status)),c())}):(c(),l())}catch(d){this.onError(d,vn,vn),c(),l()}}syncValueToStorage(e){let n=o.storage.entries.value,s=n[e]?.type;if(Oe(s)){let r=this.storeManager.getStore(he[s]),i=n[e]?.key,a=o.session[e].value;a&&(_(a)||ee(a))?o.serverCookies.isEnabledServerSideCookies.value&&s===x?(this.serverSideCookiesRequestInProgress[e]=!0,this.serverSideCookieDebounceFuncs[e]&&globalThis.clearTimeout(this.serverSideCookieDebounceFuncs[e]),this.serverSideCookieDebounceFuncs[e]=globalThis.setTimeout(()=>{let l={[e]:{name:i}};this.setServerSideCookies(l,(c,d)=>{r?.set(c,d)},r)},oo)):r?.set(i,a):r?.remove(i)}}registerEffects(){Os.forEach(e=>{X(()=>{this.syncValueToStorage(e)})})}setAnonymousId(e,n){let s=e;(!_(e)||!s)&&(s=void 0),this.isPersistenceEnabledForStorageEntry("anonymousId")?(!s&&n&&(s=this.pluginsManager?.invokeSingle("userSession.anonymousIdGoogleLinker",n)),s=s||Mt()):s=A.anonymousId,o.session.anonymousId.value=s}getAnonymousId(e){let n=o.storage.entries.value.anonymousId?.type;if(Oe(n)){let s=o.session.anonymousId.value;(!s||s===A.anonymousId)&&(s=this.getEntryValue("anonymousId")),!s&&e&&(s=this.pluginsManager?.invokeSingle("storage.getAnonymousId",H,e)),o.session.anonymousId.value=s||Mt()}return o.session.anonymousId.value}getEntryValue(e){let n=o.storage.entries.value,s=n[e]?.type;if(Oe(s)){let r=this.storeManager?.getStore(he[s]);this.migrateStorageIfNeeded([r],[e]);let i=n[e]?.key;return r?.get(i)??null}return null}getExternalAnonymousIdByCookieName(e){let n=H(x);return n?.isEnabled?n.getItem(e)??null:null}getUserSessionValue(e){return this.serverSideCookiesRequestInProgress[e]?o.session[e].value:this.getEntryValue(e)}getUserId(){return this.getUserSessionValue("userId")}getUserTraits(){return this.getUserSessionValue("userTraits")}getGroupId(){return this.getUserSessionValue("groupId")}getGroupTraits(){return this.getUserSessionValue("groupTraits")}getInitialReferrer(){return this.getUserSessionValue("initialReferrer")}getInitialReferringDomain(){return this.getUserSessionValue("initialReferringDomain")}getSessionInfo(){return this.getUserSessionValue("sessionInfo")}getAuthToken(){return this.getUserSessionValue("authToken")}getSessionId(){let e=this.getSessionInfo()??A.sessionInfo;return e.autoTrack&&!wn(e)||e.manualTrack?e.id??null:null}refreshSession(){let e=this.getSessionInfo()??A.sessionInfo;(e.autoTrack||e.manualTrack)&&(e.autoTrack&&(this.startOrRenewAutoTracking(e),e=o.session.sessionInfo.value),e.sessionStart===void 0?e={...e,sessionStart:!0}:e.sessionStart&&(e={...e,sessionStart:!1})),o.session.sessionInfo.value=e,o.lifecycle.status.value!=="readyExecuted"&&this.syncValueToStorage("sessionInfo")}resetAndStartNewSession(){let e=o.session,{manualTrack:n,autoTrack:s,timeout:r,cutOff:i}=e.sessionInfo.value;if(s){let a={...A.sessionInfo,timeout:r};i&&(a.cutOff={enabled:i.enabled,duration:i.duration}),e.sessionInfo.value=a,this.startOrRenewAutoTracking(e.sessionInfo.value)}else n&&this.startManualTrackingInternal()}reset(e){let{session:n}=o,s=Hl(e);U(()=>{Object.keys(A).forEach(r=>{let i=r;if(s.entries[i]===!0)switch(r){case"anonymousId":this.setAnonymousId();break;case"sessionInfo":this.resetAndStartNewSession();break;default:n[i].value=A[i];break}})})}setUserId(e){o.session.userId.value=this.isPersistenceEnabledForStorageEntry("userId")&&e?e:A.userId}setUserTraits(e){o.session.userTraits.value=this.isPersistenceEnabledForStorageEntry("userTraits")&&N(e)?L(o.session.userTraits.value??A.userTraits,e):A.userTraits}setGroupId(e){o.session.groupId.value=this.isPersistenceEnabledForStorageEntry("groupId")&&e?e:A.groupId}setGroupTraits(e){o.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry("groupTraits")&&N(e)?L(o.session.groupTraits.value??A.groupTraits,e):A.groupTraits}setInitialReferrer(e){o.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry("initialReferrer")&&e?e:A.initialReferrer}setInitialReferringDomain(e){o.session.initialReferringDomain.value=this.isPersistenceEnabledForStorageEntry("initialReferringDomain")&&e?e:A.initialReferringDomain}startOrRenewAutoTracking(e){let n=e;if(wn(e))n=Vl(e);else{let s=Date.now(),r=e.timeout;n.expiresAt=s+r}if(Us(n)&&(n.cutOff.expiresAt=void 0),n.cutOff){let s=Fl(n.cutOff);n.cutOff.expiresAt=s}o.session.sessionInfo.value=n}start(e){o.session.sessionInfo.value=jl(e,this.logger)}startManualTrackingInternal(){this.start(Date.now())}end(){o.session.sessionInfo.value=A.sessionInfo}setAuthToken(e){o.session.authToken.value=this.isPersistenceEnabledForStorageEntry("authToken")&&e?e:A.authToken}},Jl=["BeaconQueue","CustomConsentManager","DeviceModeDestinations","DeviceModeTransformation","ExternalAnonymousId","GoogleLinker","IubendaConsentManager","KetchConsentManager","NativeDestinationQueue","OneTrustConsentManager","StorageEncryption","StorageEncryptionLegacy","StorageMigrator","XhrQueue"],Zl=Jl,ec=(t,e)=>{let n=b(e);return _(n.setCookieDomain)||(n.setCookieDomain=void 0),["Strict","Lax","None"].includes(n.sameSiteCookie)||(n.sameSiteCookie=void 0),n.secureCookie=z(n.secureCookie,t.secureCookie),n.sameDomainCookiesOnly=z(n.sameDomainCookiesOnly,t.sameDomainCookiesOnly),["none","default","full"].includes(n.uaChTrackLevel)||(n.uaChTrackLevel=void 0),n.integrations=Y(n.integrations),Array.isArray(n.plugins)||(n.plugins=Zl),n.useGlobalIntegrationsConfigInEvents=z(n.useGlobalIntegrationsConfigInEvents,t.useGlobalIntegrationsConfigInEvents),n.bufferDataPlaneEventsUntilReady=z(n.bufferDataPlaneEventsUntilReady,t.bufferDataPlaneEventsUntilReady),n.sendAdblockPage=z(n.sendAdblockPage,t.sendAdblockPage),n.useServerSideCookies=z(n.useServerSideCookies,t.useServerSideCookies),_(n.dataServiceEndpoint)||(n.dataServiceEndpoint=void 0),n.sendAdblockPageOptions=Y(n.sendAdblockPageOptions),n.loadIntegration=z(n.loadIntegration,t.loadIntegration),ee(n.storage)?(n.storage.migrate=z(n.storage.migrate,t.storage?.migrate),n.storage.cookie=Y(n.storage.cookie),n.storage.encryption=Y(n.storage.encryption),n.storage=Qe(n.storage)):n.storage=void 0,n.destinationsQueueOptions=Y(n.destinationsQueueOptions),n.queueOptions=Y(n.queueOptions),n.lockIntegrationsVersion=z(n.lockIntegrationsVersion,t.lockIntegrationsVersion),n.lockPluginsVersion=z(n.lockPluginsVersion,t.lockPluginsVersion),ws(n.dataPlaneEventsBufferTimeout)||(n.dataPlaneEventsBufferTimeout=void 0),n.beaconQueueOptions=Y(n.beaconQueueOptions),n.preConsent=Y(n.preConsent),n.sourceConfigurationOverride=Y(n.sourceConfigurationOverride),L(t,Qe(n))},Un="dataplaneEventsQueue",$n="destinationsEventsQueue",tc="transformEvent",nc=(t,e)=>Object.keys(t).filter(n=>t[n]!==!0||!e[n]).reduce((n,s)=>{let r=b(n);return r[s]=t[s],r},{}),sc=(t,e)=>{let n=b(t),s=e.nativeDestinations.integrationsConfig.value,r=nc(t.integrations,s);return n.integrations=L(s,r),n},rc=t=>t.consents.preConsent.value.enabled&&t.consents.preConsent.value.events?.delivery==="buffer",Ke=(t,e,n,s)=>{if(O(t))if(m(t))try{t(...e)}catch(r){s.error(Gi(n),r)}else s.error(os(n))},Ft=class{constructor(e,n,s,r,i){this.pluginsManager=e,this.errorHandler=r,this.httpClient=s,this.logger=i,this.storeManager=n}init(){this.dataplaneEventsQueue=this.pluginsManager.invokeSingle(`${Un}.init`,o,this.httpClient,this.storeManager,this.errorHandler,this.logger),this.dmtEventsQueue=this.pluginsManager.invokeSingle(`${tc}.init`,o,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger),this.destinationsEventsQueue=this.pluginsManager.invokeSingle(`${$n}.init`,o,this.pluginsManager,this.storeManager,this.dmtEventsQueue,this.errorHandler,this.logger),X(()=>{o.nativeDestinations.clientDestinationsReady.value===!0&&(this.destinationsEventsQueue?.start(),this.dmtEventsQueue?.start())});let e=rc(o),n;X(()=>{let s=o.loadOptions.value.bufferDataPlaneEventsUntilReady===!0&&o.nativeDestinations.clientDestinationsReady.value===!1;(o.nativeDestinations.activeDestinations.value.some(i=>da(i))===!1||s===!1)&&!e&&this.dataplaneEventsQueue?.scheduleTimeoutActive!==!0&&(globalThis.clearTimeout(n),this.dataplaneEventsQueue?.start())}),o.loadOptions.value.bufferDataPlaneEventsUntilReady===!0&&(n=globalThis.setTimeout(()=>{this.dataplaneEventsQueue?.scheduleTimeoutActive!==!0&&this.dataplaneEventsQueue?.start()},o.loadOptions.value.dataPlaneEventsBufferTimeout))}resume(){this.dataplaneEventsQueue?.scheduleTimeoutActive!==!0&&(o.consents.postConsent.value.discardPreConsentEvents&&(this.dataplaneEventsQueue?.clear(),this.destinationsEventsQueue?.clear()),this.dataplaneEventsQueue?.start())}enqueue(e,n){let s=sc(e,o);this.pluginsManager.invokeSingle(`${Un}.enqueue`,o,this.dataplaneEventsQueue,s,this.errorHandler,this.logger);let r=b(e);this.pluginsManager.invokeSingle(`${$n}.enqueue`,o,this.destinationsEventsQueue,r,this.errorHandler,this.logger);let i=`${e.type.charAt(0).toUpperCase()}${e.type.slice(1)}${zt}`;Ke(n,[s],i,this.logger)}},Mn=t=>{let e=new CustomEvent(t,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:!0,cancelable:!0,composed:!0});globalThis.document.dispatchEvent(e)},ic=t=>_(t)&&t.trim().length>0,oc=t=>Ee(t),Vt=class{constructor(){this.preloadBuffer=new Et,this.initialized=!1,this.errorHandler=ys,this.logger=te,this.externalSrcLoader=new Xe(this.logger),this.httpClient=ps,this.httpClient.init(this.errorHandler),this.capabilitiesManager=new $t(this.httpClient,this.errorHandler,this.logger)}load(e,n,s={}){if(!o.lifecycle.status.value){if(!ic(e)){this.logger.error(vi(we,e));return}if(!oc(n)){this.logger.error(mi(we,n));return}U(()=>{o.lifecycle.writeKey.value=b(e),o.lifecycle.dataPlaneUrl.value=b(n),o.loadOptions.value=ec(o.loadOptions.value,s),o.lifecycle.status.value="mounted"}),this.logger.setMinLogLevel(o.loadOptions.value.logLevel??rs),ke("state",o,e),this.startLifecycle()}}startLifecycle(){X(()=>{try{switch(o.lifecycle.status.value){case"mounted":this.onMounted();break;case"browserCapabilitiesReady":this.onBrowserCapabilitiesReady();break;case"configured":this.onConfigured();break;case"pluginsLoading":break;case"pluginsReady":this.onPluginsReady();break;case"initialized":this.onInitialized();break;case"loaded":this.onLoaded();break;case"destinationsLoading":break;case"destinationsReady":this.onDestinationsReady();break;case"ready":this.onReady();break;default:break}}catch(e){let n="Failed to load the SDK";this.errorHandler.onError({error:e,context:we,customMessage:n,groupingHash:n})}})}onBrowserCapabilitiesReady(){jr(this),this.prepareInternalServices(),this.loadConfig()}onLoaded(){this.processBufferedEvents(),o.consents.preConsent.value.enabled===!0?o.lifecycle.status.value="ready":this.loadDestinations()}onMounted(){this.capabilitiesManager.init()}enqueuePreloadBufferEvents(e){Array.isArray(e)&&e.forEach(n=>this.preloadBuffer.enqueue(b(n)))}processDataInPreloadBuffer(){for(;this.preloadBuffer.size()>0;){let e=this.preloadBuffer.dequeue();e&&Hr([...e],this)}}prepareInternalServices(){this.pluginsManager=new Rt(ca,this.errorHandler,this.logger),this.storeManager=new Dt(this.pluginsManager,this.errorHandler,this.logger),this.configManager=new wt(this.httpClient,this.errorHandler,this.logger),this.userSessionManager=new Gt(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger),this.eventRepository=new Ft(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger),this.eventManager=new xt(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger)}loadConfig(){o.lifecycle.writeKey.value&&this.httpClient.setAuthHeader(o.lifecycle.writeKey.value),this.configManager?.init()}onPluginsReady(){this.storeManager?.init(),this.userSessionManager?.init(),o.consents.enabled.value&&!o.consents.initialized.value&&(this.pluginsManager?.invokeSingle("consentManager.init",o,this.logger),o.consents.preConsent.value.enabled===!1&&this.pluginsManager?.invokeSingle("consentManager.updateConsentsInfo",o,this.storeManager,this.logger)),this.eventManager?.init(),o.lifecycle.status.value="initialized"}onConfigured(){this.pluginsManager?.init()}onInitialized(){this.processDataInPreloadBuffer(),U(()=>{o.lifecycle.loaded.value=!0,o.lifecycle.status.value="loaded"}),this.initialized=!0;let e=o.loadOptions.value.onLoaded;Ke(e,[globalThis.rudderanalytics],ar,this.logger),Mn("RSA_Initialised")}onReady(){o.lifecycle.status.value="readyExecuted",o.eventBuffer.readyCallbacksArray.value.forEach(e=>{Ke(e,[],ot,this.logger)}),Mn("RSA_Ready")}processBufferedEvents(){let e=o.eventBuffer.toBeProcessedArray.value;for(;e.length>0;){let n=e.shift();if(o.eventBuffer.toBeProcessedArray.value=e,n){let s=n[0];m(this[s])&&this[s](...n.slice(1),!0)}e=o.eventBuffer.toBeProcessedArray.value}}loadDestinations(){if(o.lifecycle.status.value==="destinationsLoading"||o.lifecycle.status.value==="destinationsReady")return;this.pluginsManager?.invokeSingle("nativeDestinations.setActiveDestinations",o,this.pluginsManager,this.errorHandler,this.logger);let e=o.nativeDestinations.activeDestinations.value.length;if(e===0){o.lifecycle.status.value="destinationsReady";return}o.lifecycle.status.value="destinationsLoading",this.pluginsManager?.invokeSingle("nativeDestinations.load",o,this.externalSrcLoader,this.errorHandler,this.logger),X(()=>{(e===0||o.nativeDestinations.initializedDestinations.value.length+o.nativeDestinations.failedDestinations.value.length===e)&&U(()=>{o.lifecycle.status.value="destinationsReady",o.nativeDestinations.clientDestinationsReady.value=!0})})}onDestinationsReady(){o.lifecycle.status.value!=="ready"&&U(()=>{o.lifecycle.status.value="ready"})}ready(e,n=!1){let s="ready";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}if(this.errorHandler.leaveBreadcrumb(`New ${s} invocation`),!m(e)){this.logger.error(os(ot));return}o.lifecycle.status.value==="readyExecuted"?Ke(e,[],ot,this.logger):o.eventBuffer.readyCallbacksArray.value=[...o.eventBuffer.readyCallbacksArray.value,e]}page(e,n=!1){let s="page";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} event`),o.metrics.triggered.value+=1,this.eventManager?.addEvent({type:"page",category:e.category,name:e.name,properties:e.properties,options:e.options,callback:e.callback}),o.capabilities.isAdBlocked.value===!0&&e.category!==on&&this.page(We(on,Pr,{path:kr},o.loadOptions.value.sendAdblockPageOptions))}track(e,n=!1){let s="track";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} event - ${e.name}`),o.metrics.triggered.value+=1,this.eventManager?.addEvent({type:s,name:e.name||void 0,properties:e.properties,options:e.options,callback:e.callback})}identify(e,n=!1){let s="identify";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} event`),o.metrics.triggered.value+=1,e.userId&&o.session.userId.value&&e.userId!==o.session.userId.value&&this.reset(),G(e.userId)||this.userSessionManager?.setUserId(e.userId),this.userSessionManager?.setUserTraits(e.traits),this.eventManager?.addEvent({type:s,userId:e.userId,traits:e.traits,options:e.options,callback:e.callback})}alias(e,n=!1){let s="alias";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} event`),o.metrics.triggered.value+=1;let r=e.from??(this.getUserId()||this.userSessionManager?.getAnonymousId());this.eventManager?.addEvent({type:s,to:e.to,from:r,options:e.options,callback:e.callback})}group(e,n=!1){let s="group";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} event`),o.metrics.triggered.value+=1,G(e.groupId)||this.userSessionManager?.setGroupId(e.groupId),this.userSessionManager?.setGroupTraits(e.traits),this.eventManager?.addEvent({type:s,groupId:e.groupId,traits:e.traits,options:e.options,callback:e.callback})}reset(e,n=!1){let s="reset";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} invocation`),this.userSessionManager?.reset(e)}getAnonymousId(e){return this.userSessionManager?.getAnonymousId(e)}setAnonymousId(e,n,s=!1){let r="setAnonymousId";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[r,e,n]];return}this.errorHandler.leaveBreadcrumb(`New ${r} invocation`),this.userSessionManager?.setAnonymousId(e,n)}getUserId(){return o.session.userId.value}getUserTraits(){return o.session.userTraits.value}getGroupId(){return o.session.groupId.value}getGroupTraits(){return o.session.groupTraits.value}startSession(e,n=!1){let s="startSession";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} invocation`),this.userSessionManager?.start(e)}endSession(e=!1){let n="endSession";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[n]];return}this.errorHandler.leaveBreadcrumb(`New ${n} invocation`),this.userSessionManager?.end()}getSessionId(){return this.userSessionManager?.getSessionId()??null}consent(e,n=!1){let s="consent";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb("New consent invocation"),U(()=>{o.consents.preConsent.value={...o.consents.preConsent.value,enabled:!1},o.consents.postConsent.value=dl(e);let{initialized:r,consentsData:i}=ks(o.consents.postConsent.value.consentManagement,this.logger);o.consents.initialized.value=r,o.consents.data.value=i}),o.consents.enabled.value&&!o.consents.initialized.value&&this.pluginsManager?.invokeSingle("consentManager.updateConsentsInfo",o,this.storeManager,this.logger),this.storeManager?.initializeStorageState(),this.userSessionManager?.syncStorageDataToState(),this.eventManager?.resume(),this.loadDestinations(),this.sendTrackingEvents(n)}sendTrackingEvents(e){if(o.consents.postConsent.value.trackConsent){let n=Qt(Cr);e?o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,["track",n]]:this.track(n)}if(o.consents.postConsent.value.sendPageEvent){let n=We();e?o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,["page",n]]:this.page(n)}}setAuthToken(e){this.userSessionManager?.setAuthToken(e)}addCustomIntegration(e,n,s=!1){let r="addCustomIntegration";if(s)this.errorHandler.leaveBreadcrumb(`New ${r} invocation`),this.pluginsManager?.invokeSingle("nativeDestinations.addCustomIntegration",e,n,o,this.logger);else{if(o.lifecycle.loaded.value){this.logger.error(qi(we,e));return}o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[r,e,n]]}}},ce=class ce{constructor(){k(this,"analyticsInstances",{});k(this,"defaultAnalyticsKey","");k(this,"logger",te);try{if(ce.globalSingleton)return ce.globalSingleton;ce.initializeGlobalResources(),this.setDefaultInstanceKey=this.setDefaultInstanceKey.bind(this),this.getAnalyticsInstance=this.getAnalyticsInstance.bind(this),this.load=this.load.bind(this),this.ready=this.ready.bind(this),this.triggerBufferedLoadEvent=this.triggerBufferedLoadEvent.bind(this),this.page=this.page.bind(this),this.track=this.track.bind(this),this.identify=this.identify.bind(this),this.alias=this.alias.bind(this),this.group=this.group.bind(this),this.reset=this.reset.bind(this),this.getAnonymousId=this.getAnonymousId.bind(this),this.setAnonymousId=this.setAnonymousId.bind(this),this.getUserId=this.getUserId.bind(this),this.getUserTraits=this.getUserTraits.bind(this),this.getGroupId=this.getGroupId.bind(this),this.getGroupTraits=this.getGroupTraits.bind(this),this.startSession=this.startSession.bind(this),this.endSession=this.endSession.bind(this),this.getSessionId=this.getSessionId.bind(this),this.setAuthToken=this.setAuthToken.bind(this),this.consent=this.consent.bind(this),this.addCustomIntegration=this.addCustomIntegration.bind(this),this.createSafeAnalyticsInstance(),ce.globalSingleton=this,o.autoTrack.pageLifecycle.pageViewId.value=Ze(),o.autoTrack.pageLifecycle.pageLoadedTimestamp.value=Date.now(),this.triggerBufferedLoadEvent(),globalThis.rudderanalytics=this}catch(e){D(e)}}createSafeAnalyticsInstance(){o.lifecycle.safeAnalyticsInstance.value={page:this.page.bind(this),track:this.track.bind(this),identify:this.identify.bind(this),alias:this.alias.bind(this),group:this.group.bind(this),getAnonymousId:this.getAnonymousId.bind(this),getUserId:this.getUserId.bind(this),getUserTraits:this.getUserTraits.bind(this),getGroupId:this.getGroupId.bind(this),getGroupTraits:this.getGroupTraits.bind(this),getSessionId:this.getSessionId.bind(this)}}static initializeGlobalResources(){ys.init(),Zt.configure(),qt.configure(),Jt.configure(),qe.configure()}setDefaultInstanceKey(e){_(e)&&e&&(this.defaultAnalyticsKey=e)}getAnalyticsInstance(e){try{let n=e;return(!_(n)||!n)&&(n=this.defaultAnalyticsKey),this.analyticsInstances[n]||(this.analyticsInstances[n]=new Vt),this.analyticsInstances[n]}catch(n){D(n);return}}load(e,n,s){try{if(this.analyticsInstances[e])return;this.setDefaultInstanceKey(e),this.trackPageLifecycleEvents(s);let r=qn(_e);Vr(r),ke(_e,b(r)),this.getAnalyticsInstance(e)?.load(e,n,I(s))}catch(r){D(r)}}trackPageLifecycleEvents(e){let{autoTrack:n,useBeacon:s}=e??{},{enabled:r=!1,options:i={},pageLifecycle:a}=n??{},{events:l=[it.UNLOADED],enabled:c=r,options:d=i}=a??{};o.autoTrack.pageLifecycle.enabled.value=c,o.autoTrack.enabled.value=r||c,c&&this.setupPageUnloadTracking(l,s,d)}setupPageUnloadTracking(e,n,s){(e.length===0||e.includes(it.UNLOADED))&&(n===!0?pr(r=>{if(r===!1&&o.lifecycle.loaded.value){let i=Date.now(),a=i-o.autoTrack.pageLifecycle.pageLoadedTimestamp.value;this.track(it.UNLOADED,{timeOnPage:a},{...s,originalTimestamp:Qn(new Date(i))})}},!0):this.logger.warn(Wi(cr)))}triggerBufferedLoadEvent(){let e=Array.isArray(globalThis.rudderanalytics)?globalThis.rudderanalytics:[],n=Fr(e);ke(_e,b([...e])),n.length>0&&(n.shift(),this.load.apply(null,n))}ready(e){try{this.getAnalyticsInstance()?.ready(I(e))}catch(n){D(n)}}page(e,n,s,r,i){try{this.getAnalyticsInstance()?.page(We(I(e),I(n),I(s),I(r),I(i)))}catch(a){D(a)}}track(e,n,s,r){try{this.getAnalyticsInstance()?.track(Qt(I(e),I(n),I(s),I(r)))}catch(i){D(i)}}identify(e,n,s,r){try{this.getAnalyticsInstance()?.identify(Fn(I(e),I(n),I(s),I(r)))}catch(i){D(i)}}alias(e,n,s,r){try{this.getAnalyticsInstance()?.alias(Vn(I(e),I(n),I(s),I(r)))}catch(i){D(i)}}group(e,n,s,r){try{this.getAnalyticsInstance()?.group(jn(I(e),I(n),I(s),I(r)))}catch(i){D(i)}}reset(e){try{this.getAnalyticsInstance()?.reset(I(e))}catch(n){D(n)}}getAnonymousId(e){try{return this.getAnalyticsInstance()?.getAnonymousId(I(e))}catch(n){D(n);return}}setAnonymousId(e,n){try{this.getAnalyticsInstance()?.setAnonymousId(I(e),I(n))}catch(s){D(s)}}getUserId(){try{return this.getAnalyticsInstance()?.getUserId()}catch(e){D(e);return}}getUserTraits(){try{return this.getAnalyticsInstance()?.getUserTraits()}catch(e){D(e);return}}getGroupId(){try{return this.getAnalyticsInstance()?.getGroupId()}catch(e){D(e);return}}getGroupTraits(){try{return this.getAnalyticsInstance()?.getGroupTraits()}catch(e){D(e);return}}startSession(e){try{this.getAnalyticsInstance()?.startSession(I(e))}catch(n){D(n)}}endSession(){try{this.getAnalyticsInstance()?.endSession()}catch(e){D(e)}}getSessionId(){try{return this.getAnalyticsInstance()?.getSessionId()}catch(e){D(e);return}}setAuthToken(e){try{this.getAnalyticsInstance()?.setAuthToken(I(e))}catch(n){D(n)}}consent(e){try{this.getAnalyticsInstance()?.consent(I(e))}catch(n){D(n)}}addCustomIntegration(e,n){try{this.getAnalyticsInstance()?.addCustomIntegration(I(e),I(n))}catch(s){D(s)}}};k(ce,"globalSingleton",null);var Bn=ce;export{Bn as a};
14
- //# sourceMappingURL=chunk-YGU4ZMIH.mjs.map
14
+ //# sourceMappingURL=chunk-FY3NPDUL.mjs.map
@@ -0,0 +1,4 @@
1
+ import m from'js-cookie';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
+ var c="https://deriv.com/cdn-cgi/trace",f="https://cdn.growthbook.io",y="https://deriv-dataplane.rudderstack.com",a="https://ph.deriv.com",g="https://us.posthog.com",h=()=>{if(typeof window>"u")return a;let t=window.location.hostname;return t.includes(".deriv.me")?"https://ph.deriv.me":t.includes(".deriv.be")?"https://ph.deriv.be":a},p=["deriv.com","deriv.be","deriv.me","deriv.team","deriv.ae"],l=["deriv.com","derivcrypto.com","besquare.my","besquare.com.my","ewallet.exchange","champion-fx.com","opalstraits.com","binary.com","binary.marketing","championgbs.com","4x.my","re-work.dev","regentmarkets.com","4x.com","binary.me","deriv.team","firstsource.io","firstsource.tech","deriv.hr","vmgbpo.net","mailisk.net","mailosaur.net","mobileapps.mailisk.net","w3e180zd.mailosaur.net"],v=()=>{if(typeof window>"u")return ".deriv.com";let t=window.location.hostname;if(t==="localhost")return "";let e=p.find(o=>t.includes(o));return e?`.${e}`:".deriv.com"};var k=(t,e)=>(...o)=>{e()&&console.log(`[ANALYTIC]${t}`,...o);},b=t=>{let e=t.split("@")[1]?.toLowerCase();return e?l.includes(e):false},O=t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t),i=null,D=async()=>{if(i)return i;let t=JSON.parse(m.get("website_status")||"{}")?.clients_country;return i=(async()=>{try{let e=await fetch(c).catch(()=>null);if(!e)return t||"";let o=await e.text().catch(()=>"");return o?Object.fromEntries(o.split(`
3
+ `).map(r=>r.split("=",2))).loc?.toLowerCase()||t||"":t||""}catch{return t||""}})(),i},d=t=>{if(t==null||typeof t!="object")return t;if(Array.isArray(t)){let n=[];for(let r=0;r<t.length;r++){let s=d(t[r]);s!=null&&n.push(s);}return n.length?n:void 0}let e={},o=false;for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let r=d(t[n]);r==null||r===""||typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0||Array.isArray(r)&&r.length===0||(e[n]=r,o=true);}return o?e:void 0},u=(t,e)=>{for(let o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;let n=t[o];n&&typeof n=="object"&&!Array.isArray(n)?u(n,e):e[o]=n;}},R=t=>{if(t==null||typeof t!="object"||Array.isArray(t))return t;let e={};return u(t,e),e};export{f as a,y as b,g as c,h as d,p as e,v as f,k as g,b as h,O as i,D as j,d as k,R as l};//# sourceMappingURL=chunk-GGU2UVKH.mjs.map
4
+ //# sourceMappingURL=chunk-GGU2UVKH.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/urls.ts","../src/utils/helpers.ts"],"names":["cloudflareTrace","growthbookApi","rudderstackDataplane","posthogApiHost","posthogUiHost","getPosthogApiHost","hostname","allowedDomains","internalEmailDomains","getAllowedDomain","matched","d","createLogger","prefix","isDebugEnabled","args","isInternalEmail","email","domain","isUUID","str","countryPromise","getCountry","cookieCountry","Cookies","response","text","v","cleanObject","obj","out","i","cleaned","hasKeys","key","_flattenInto","target","value","flattenObject"],"mappings":"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","file":"chunk-GGU2UVKH.mjs","sourcesContent":["export const cloudflareTrace = 'https://deriv.com/cdn-cgi/trace'\nexport const growthbookApi = 'https://cdn.growthbook.io'\nexport const rudderstackDataplane = 'https://deriv-dataplane.rudderstack.com'\nexport const posthogApiHost = 'https://ph.deriv.com'\nexport const posthogUiHost = 'https://us.posthog.com'\n\nexport const getPosthogApiHost = (): string => {\n if (typeof window === 'undefined') return posthogApiHost\n const hostname = window.location.hostname\n if (hostname.includes('.deriv.me')) return 'https://ph.deriv.me'\n if (hostname.includes('.deriv.be')) return 'https://ph.deriv.be'\n return posthogApiHost\n}\n\nexport const allowedDomains = ['deriv.com', 'deriv.be', 'deriv.me', 'deriv.team', 'deriv.ae'] as const\n\nexport const internalEmailDomains = [\n 'deriv.com',\n 'derivcrypto.com',\n 'besquare.my',\n 'besquare.com.my',\n 'ewallet.exchange',\n 'champion-fx.com',\n 'opalstraits.com',\n 'binary.com',\n 'binary.marketing',\n 'championgbs.com',\n '4x.my',\n 're-work.dev',\n 'regentmarkets.com',\n '4x.com',\n 'binary.me',\n 'deriv.team',\n 'firstsource.io',\n 'firstsource.tech',\n 'deriv.hr',\n 'vmgbpo.net',\n 'mailisk.net',\n 'mailosaur.net',\n 'mobileapps.mailisk.net',\n 'w3e180zd.mailosaur.net',\n] as const\n\nexport const getAllowedDomain = (): string => {\n if (typeof window === 'undefined') return '.deriv.com'\n const hostname = window.location.hostname\n\n if (hostname === 'localhost') return ''\n\n const matched = allowedDomains.find(d => hostname.includes(d))\n return matched ? `.${matched}` : '.deriv.com'\n}\n","import Cookies from 'js-cookie'\nimport { cloudflareTrace, internalEmailDomains } from './urls'\n\n/**\n * Creates a prefixed logger that only outputs when debug mode is enabled.\n * Pass a getter function so the logger always reads the latest debug state.\n *\n * @param prefix - Optional provider name appended after [ANALYTIC], e.g. '[RudderStack]'\n * @param isDebugEnabled - A function that returns the current debug flag value\n * @returns A log function with the same signature as console.log\n *\n * @example\n * // In a class\n * private log = createLogger('[RudderStack]', () => this.debug)\n *\n * // In a closure\n * const log = createLogger('', () => _debug)\n */\nexport const createLogger =\n (prefix: string, isDebugEnabled: () => boolean) =>\n (...args: any[]): void => {\n if (isDebugEnabled()) console.log(`[ANALYTIC]${prefix}`, ...args)\n }\n\nexport const isInternalEmail = (email: string): boolean => {\n const domain = email.split('@')[1]?.toLowerCase()\n if (!domain) return false\n return (internalEmailDomains as readonly string[]).includes(domain)\n}\n\nexport const isUUID = (str: string): boolean => {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n return uuidRegex.test(str)\n}\n\ntype TraceData = {\n loc?: string\n}\n\nlet countryPromise: Promise<string> | null = null\n\n/**\n * Fetches the country information based on Cloudflare's trace data or a fallback from cookies.\n * This function attempts to retrieve the country location by first fetching trace data from Cloudflare\n * and then falling back to the location stored in the cookies if the fetch fails.\n *\n * @returns {Promise<string>} A Promise that resolves to a string representing the country code in lowercase.\n * Returns an empty string if no country data is available or if an error occurs.\n *\n * @example\n * // Returns the country code in lowercase based on Cloudflare's trace data or cookies.\n * getCountry().then(country => console.log(country));\n */\nexport const getCountry = async (): Promise<string> => {\n if (countryPromise) return countryPromise\n\n const cookieCountry = JSON.parse(Cookies.get('website_status') || '{}')?.clients_country\n\n countryPromise = (async () => {\n try {\n const response = await fetch(cloudflareTrace).catch(() => null)\n if (!response) return cookieCountry || ''\n\n const text = await response.text().catch(() => '')\n if (!text) return cookieCountry || ''\n\n const data: TraceData = Object.fromEntries(text.split('\\n').map(v => v.split('=', 2)))\n return data.loc?.toLowerCase() || cookieCountry || ''\n } catch {\n return cookieCountry || ''\n }\n })()\n\n return countryPromise\n}\n\n/**\n * Recursively cleans an object by removing undefined, null, empty strings, empty objects, and empty arrays\n * Used to sanitize event properties before sending to analytics providers\n *\n * @param obj - The object to clean\n * @returns The cleaned object, or undefined if the result would be empty\n */\nexport const cleanObject = (obj: any): any => {\n if (obj == null || typeof obj !== 'object') return obj\n\n if (Array.isArray(obj)) {\n const out: any[] = []\n for (let i = 0; i < obj.length; i++) {\n const v = cleanObject(obj[i])\n if (v !== undefined && v !== null) out.push(v)\n }\n return out.length ? out : undefined\n }\n\n const cleaned: Record<string, any> = {}\n let hasKeys = false\n for (const key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue\n const v = cleanObject(obj[key])\n if (\n v === undefined ||\n v === null ||\n v === '' ||\n (typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === 0) ||\n (Array.isArray(v) && v.length === 0)\n )\n continue\n cleaned[key] = v\n hasKeys = true\n }\n return hasKeys ? cleaned : undefined\n}\n\n/**\n * Flattens a nested object structure into a single-level object\n * Lifts all nested properties to the top level without prefixing\n *\n * @param obj - The object to flatten\n * @returns A flattened object with all nested properties at the top level\n *\n * @example\n * flattenObject({ action: 'click', event_metadata: { version: 2, user_language: 'en' } })\n * // Returns: { action: 'click', version: 2, user_language: 'en' }\n *\n * flattenObject({ form_name: 'signup', cta_information: { cta_name: 'signup', section_name: 'header' } })\n * // Returns: { form_name: 'signup', cta_name: 'signup', section_name: 'header' }\n */\nconst _flattenInto = (obj: Record<string, any>, target: Record<string, any>): void => {\n for (const key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue\n const value = obj[key]\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n _flattenInto(value, target)\n } else {\n target[key] = value\n }\n }\n}\n\nexport const flattenObject = (obj: any): Record<string, any> => {\n if (obj == null || typeof obj !== 'object' || Array.isArray(obj)) {\n return obj\n }\n const target: Record<string, any> = {}\n _flattenInto(obj, target)\n return target\n}\n"]}
@@ -0,0 +1,4 @@
1
+ 'use strict';var f=require('js-cookie');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var f__default=/*#__PURE__*/_interopDefault(f);/* @deriv-com/analytics - NPM Package - Built with tsup */
2
+ var c="https://deriv.com/cdn-cgi/trace",y="https://cdn.growthbook.io",g="https://deriv-dataplane.rudderstack.com",a="https://ph.deriv.com",h="https://us.posthog.com",v=()=>{if(typeof window>"u")return a;let t=window.location.hostname;return t.includes(".deriv.me")?"https://ph.deriv.me":t.includes(".deriv.be")?"https://ph.deriv.be":a},m=["deriv.com","deriv.be","deriv.me","deriv.team","deriv.ae"],l=["deriv.com","derivcrypto.com","besquare.my","besquare.com.my","ewallet.exchange","champion-fx.com","opalstraits.com","binary.com","binary.marketing","championgbs.com","4x.my","re-work.dev","regentmarkets.com","4x.com","binary.me","deriv.team","firstsource.io","firstsource.tech","deriv.hr","vmgbpo.net","mailisk.net","mailosaur.net","mobileapps.mailisk.net","w3e180zd.mailosaur.net"],x=()=>{if(typeof window>"u")return ".deriv.com";let t=window.location.hostname;if(t==="localhost")return "";let e=m.find(o=>t.includes(o));return e?`.${e}`:".deriv.com"};var O=(t,e)=>(...o)=>{e()&&console.log(`[ANALYTIC]${t}`,...o);},D=t=>{let e=t.split("@")[1]?.toLowerCase();return e?l.includes(e):false},R=t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t),i=null,C=async()=>{if(i)return i;let t=JSON.parse(f__default.default.get("website_status")||"{}")?.clients_country;return i=(async()=>{try{let e=await fetch(c).catch(()=>null);if(!e)return t||"";let o=await e.text().catch(()=>"");return o?Object.fromEntries(o.split(`
3
+ `).map(r=>r.split("=",2))).loc?.toLowerCase()||t||"":t||""}catch{return t||""}})(),i},d=t=>{if(t==null||typeof t!="object")return t;if(Array.isArray(t)){let n=[];for(let r=0;r<t.length;r++){let s=d(t[r]);s!=null&&n.push(s);}return n.length?n:void 0}let e={},o=false;for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let r=d(t[n]);r==null||r===""||typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0||Array.isArray(r)&&r.length===0||(e[n]=r,o=true);}return o?e:void 0},u=(t,e)=>{for(let o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;let n=t[o];n&&typeof n=="object"&&!Array.isArray(n)?u(n,e):e[o]=n;}},P=t=>{if(t==null||typeof t!="object"||Array.isArray(t))return t;let e={};return u(t,e),e};exports.a=y;exports.b=g;exports.c=h;exports.d=v;exports.e=m;exports.f=x;exports.g=O;exports.h=D;exports.i=R;exports.j=C;exports.k=d;exports.l=P;//# sourceMappingURL=chunk-J3V5QNIH.js.map
4
+ //# sourceMappingURL=chunk-J3V5QNIH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/urls.ts","../src/utils/helpers.ts"],"names":["cloudflareTrace","growthbookApi","rudderstackDataplane","posthogApiHost","posthogUiHost","getPosthogApiHost","hostname","allowedDomains","internalEmailDomains","getAllowedDomain","matched","d","createLogger","prefix","isDebugEnabled","args","isInternalEmail","email","domain","isUUID","str","countryPromise","getCountry","cookieCountry","Cookies","response","text","v","cleanObject","obj","out","i","cleaned","hasKeys","key","_flattenInto","target","value","flattenObject"],"mappings":"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","file":"chunk-J3V5QNIH.js","sourcesContent":["export const cloudflareTrace = 'https://deriv.com/cdn-cgi/trace'\nexport const growthbookApi = 'https://cdn.growthbook.io'\nexport const rudderstackDataplane = 'https://deriv-dataplane.rudderstack.com'\nexport const posthogApiHost = 'https://ph.deriv.com'\nexport const posthogUiHost = 'https://us.posthog.com'\n\nexport const getPosthogApiHost = (): string => {\n if (typeof window === 'undefined') return posthogApiHost\n const hostname = window.location.hostname\n if (hostname.includes('.deriv.me')) return 'https://ph.deriv.me'\n if (hostname.includes('.deriv.be')) return 'https://ph.deriv.be'\n return posthogApiHost\n}\n\nexport const allowedDomains = ['deriv.com', 'deriv.be', 'deriv.me', 'deriv.team', 'deriv.ae'] as const\n\nexport const internalEmailDomains = [\n 'deriv.com',\n 'derivcrypto.com',\n 'besquare.my',\n 'besquare.com.my',\n 'ewallet.exchange',\n 'champion-fx.com',\n 'opalstraits.com',\n 'binary.com',\n 'binary.marketing',\n 'championgbs.com',\n '4x.my',\n 're-work.dev',\n 'regentmarkets.com',\n '4x.com',\n 'binary.me',\n 'deriv.team',\n 'firstsource.io',\n 'firstsource.tech',\n 'deriv.hr',\n 'vmgbpo.net',\n 'mailisk.net',\n 'mailosaur.net',\n 'mobileapps.mailisk.net',\n 'w3e180zd.mailosaur.net',\n] as const\n\nexport const getAllowedDomain = (): string => {\n if (typeof window === 'undefined') return '.deriv.com'\n const hostname = window.location.hostname\n\n if (hostname === 'localhost') return ''\n\n const matched = allowedDomains.find(d => hostname.includes(d))\n return matched ? `.${matched}` : '.deriv.com'\n}\n","import Cookies from 'js-cookie'\nimport { cloudflareTrace, internalEmailDomains } from './urls'\n\n/**\n * Creates a prefixed logger that only outputs when debug mode is enabled.\n * Pass a getter function so the logger always reads the latest debug state.\n *\n * @param prefix - Optional provider name appended after [ANALYTIC], e.g. '[RudderStack]'\n * @param isDebugEnabled - A function that returns the current debug flag value\n * @returns A log function with the same signature as console.log\n *\n * @example\n * // In a class\n * private log = createLogger('[RudderStack]', () => this.debug)\n *\n * // In a closure\n * const log = createLogger('', () => _debug)\n */\nexport const createLogger =\n (prefix: string, isDebugEnabled: () => boolean) =>\n (...args: any[]): void => {\n if (isDebugEnabled()) console.log(`[ANALYTIC]${prefix}`, ...args)\n }\n\nexport const isInternalEmail = (email: string): boolean => {\n const domain = email.split('@')[1]?.toLowerCase()\n if (!domain) return false\n return (internalEmailDomains as readonly string[]).includes(domain)\n}\n\nexport const isUUID = (str: string): boolean => {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n return uuidRegex.test(str)\n}\n\ntype TraceData = {\n loc?: string\n}\n\nlet countryPromise: Promise<string> | null = null\n\n/**\n * Fetches the country information based on Cloudflare's trace data or a fallback from cookies.\n * This function attempts to retrieve the country location by first fetching trace data from Cloudflare\n * and then falling back to the location stored in the cookies if the fetch fails.\n *\n * @returns {Promise<string>} A Promise that resolves to a string representing the country code in lowercase.\n * Returns an empty string if no country data is available or if an error occurs.\n *\n * @example\n * // Returns the country code in lowercase based on Cloudflare's trace data or cookies.\n * getCountry().then(country => console.log(country));\n */\nexport const getCountry = async (): Promise<string> => {\n if (countryPromise) return countryPromise\n\n const cookieCountry = JSON.parse(Cookies.get('website_status') || '{}')?.clients_country\n\n countryPromise = (async () => {\n try {\n const response = await fetch(cloudflareTrace).catch(() => null)\n if (!response) return cookieCountry || ''\n\n const text = await response.text().catch(() => '')\n if (!text) return cookieCountry || ''\n\n const data: TraceData = Object.fromEntries(text.split('\\n').map(v => v.split('=', 2)))\n return data.loc?.toLowerCase() || cookieCountry || ''\n } catch {\n return cookieCountry || ''\n }\n })()\n\n return countryPromise\n}\n\n/**\n * Recursively cleans an object by removing undefined, null, empty strings, empty objects, and empty arrays\n * Used to sanitize event properties before sending to analytics providers\n *\n * @param obj - The object to clean\n * @returns The cleaned object, or undefined if the result would be empty\n */\nexport const cleanObject = (obj: any): any => {\n if (obj == null || typeof obj !== 'object') return obj\n\n if (Array.isArray(obj)) {\n const out: any[] = []\n for (let i = 0; i < obj.length; i++) {\n const v = cleanObject(obj[i])\n if (v !== undefined && v !== null) out.push(v)\n }\n return out.length ? out : undefined\n }\n\n const cleaned: Record<string, any> = {}\n let hasKeys = false\n for (const key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue\n const v = cleanObject(obj[key])\n if (\n v === undefined ||\n v === null ||\n v === '' ||\n (typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === 0) ||\n (Array.isArray(v) && v.length === 0)\n )\n continue\n cleaned[key] = v\n hasKeys = true\n }\n return hasKeys ? cleaned : undefined\n}\n\n/**\n * Flattens a nested object structure into a single-level object\n * Lifts all nested properties to the top level without prefixing\n *\n * @param obj - The object to flatten\n * @returns A flattened object with all nested properties at the top level\n *\n * @example\n * flattenObject({ action: 'click', event_metadata: { version: 2, user_language: 'en' } })\n * // Returns: { action: 'click', version: 2, user_language: 'en' }\n *\n * flattenObject({ form_name: 'signup', cta_information: { cta_name: 'signup', section_name: 'header' } })\n * // Returns: { form_name: 'signup', cta_name: 'signup', section_name: 'header' }\n */\nconst _flattenInto = (obj: Record<string, any>, target: Record<string, any>): void => {\n for (const key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue\n const value = obj[key]\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n _flattenInto(value, target)\n } else {\n target[key] = value\n }\n }\n}\n\nexport const flattenObject = (obj: any): Record<string, any> => {\n if (obj == null || typeof obj !== 'object' || Array.isArray(obj)) {\n return obj\n }\n const target: Record<string, any> = {}\n _flattenInto(obj, target)\n return target\n}\n"]}
@@ -1,3 +1,3 @@
1
- import {g}from'./chunk-ID2GN2PS.mjs';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var p=class{constructor(){this.interval=null;this.responses=[];this.isTrackingResponses=false;this.delegatedSelectors=new Set;this.debug=false;this.log=g("[CacheManager]",()=>this.debug);this.addEventhandler=this.addEventHandler.bind(this);}setDebug(e){this.debug=e;}hash(e,n=32){let t=a=>{let r=2166136261;for(let c=0;c<a.length;c++)r^=a.charCodeAt(c),r=r*16777619>>>0;return r.toString(16)},i=a=>btoa(a),s=t(e),o=i(s);for(;o.length<n;)o+=i(t(o));return o.substring(0,n)}getCookies(e){let t=`; ${document.cookie}`.split(`; ${e}=`);if(t.length===2){let i=decodeURIComponent(t.pop().split(";").shift());try{return JSON.parse(i)}catch{return i}}return null}trackPageUnload(){typeof window>"u"||window.addEventListener("beforeunload",()=>{this.isPageViewSent()||this.push("cached_analytics_page_views",{name:window.location.href,properties:{url:window.location.href}});});}trackResponses(){if(typeof window>"u"||typeof XMLHttpRequest>"u")return;let e=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(t,i){return this._url=i,this._method=t,e.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){return this.addEventListener("load",function(){let i=null;if(typeof t=="string")try{i=JSON.parse(t);}catch{i=t;}let s={url:this._url,method:this._method,status:this.status,headers:this.getAllResponseHeaders(),data:this.responseText,payload:i};f.responses.push(s);}),n.apply(this,arguments)},this.isTrackingResponses=true;}getAnalyticsInstance(){return typeof window>"u"?null:window.AnalyticsInstance??window.DerivAnalytics?.Analytics??window.Analytics?.Analytics}isReady(){if(typeof window>"u")return false;let e=this.getAnalyticsInstance();return e?!!e.getInstances?.()?.tracking:false}parseCookies(e){if(typeof document>"u")return null;let n=document.cookie.split("; ");for(let t of n){let i=t.indexOf("=");if(i!==-1&&decodeURIComponent(t.slice(0,i))===e){let s=t.slice(i+1);try{return JSON.parse(decodeURIComponent(s))}catch{return decodeURIComponent(s)}}}return null}isPageViewSent(){return !!this.responses.find(e=>e.payload?.type==="page"&&e.payload?.anonymousId)}set(e){this.log("set | caching event to cookie",e),this.push("cached_analytics_events",e);}push(e,n){if(typeof document>"u")return;let t=[],i=this.parseCookies(e);i&&Array.isArray(i)&&(t=i),t.push(n);let s=this.getAllowedDomain(),o=365*24*60*60,a=`${e}=${encodeURIComponent(JSON.stringify(t))}; path=/; Domain=${s}; max-age=${o}; SameSite=Lax`;document.cookie=a;}getAllowedDomain(){if(typeof window>"u")return "";let e=window.location.hostname;if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return e;let n=e.split(".");return n.length===1?e:`.${n.slice(-2).join(".")}`}processEvent(e){let n=this.getCookies("client_information");if(n){let{email:t=null}=n;t&&(e.properties.email_hash=this.hash(t));}if(e?.properties?.email){let t=e.properties.email;delete e.properties.email,e.properties.email_hash=this.hash(t);}return e}track(e,n=false){if(typeof window>"u")return;let t=this.processEvent(e),i=this.getAnalyticsInstance();this.isReady()&&!n?(this.log("track | analytics ready \u2014 calling trackEvent",{event:t.name,properties:t.properties}),i.trackEvent(t.name,t.properties)):(this.log("track | analytics not ready or cache=true \u2014 storing event",{event:t.name,cache:n}),this.set(t));}pageView(){typeof window>"u"||(this.log("pageView | starting page view polling"),this.isTrackingResponses||(this.trackResponses(),this.trackPageUnload()),this.interval=setInterval(()=>{let e=window.Analytics;typeof e<"u"&&typeof e.Analytics?.pageView=="function"&&this.isReady()&&(this.log("pageView | analytics ready \u2014 sending page view",{href:window.location.href}),e.Analytics.pageView(window.location.href,"Trader's hub")),this.isPageViewSent()&&(this.log("pageView | page view confirmed sent \u2014 clearing interval"),this.interval&&clearInterval(this.interval));},1e3));}listen(e,{name:n="",properties:t={}},i=false,s=null){let o=r=>{r.dataset?.clickEventTracking||(r.addEventListener("click",c=>{let l={name:n,properties:t,cache:i};if(typeof s=="function"){let d=s(c);l={...d,cache:d.cache??i};}this.track(l,l.cache??false);}),r.dataset.clickEventTracking="true");};(e instanceof NodeList?Array.from(e):[e]).forEach(o);}addEventHandler(e){return typeof window>"u"?this:(e.forEach(({element:n,event:t={name:"",properties:{}},cache:i=false,callback:s=null})=>{if(typeof n=="string"){let o=n;if(!this.delegatedSelectors.has(o)){let a=r=>{let c=r.target;if(!c)return;let l=c.closest(o);if(l&&!l.dataset?.clickEventTracking){let d={name:t.name,properties:t.properties,cache:i};if(typeof s=="function"){let h=s(r);d={...h,cache:h.cache??i};}l.dataset.clickEventTracking="true",this.track(d,d.cache??false);}};document.addEventListener("click",a),this.delegatedSelectors.add(o);}}else (n instanceof NodeList?Array.from(n):[n]).forEach(a=>{a&&!a.dataset?.clickEventTracking&&this.listen(a,t,i,s);});}),this)}loadEvent(e){return this.log("loadEvent | firing load events",e.map(n=>n.event.name)),e.forEach(({event:n})=>{let{name:t,properties:i}=n;this.track({name:t,properties:i});}),this}pageLoadEvent(e){if(typeof window>"u")return this;let n=window.location.pathname.slice(1);return this.log("pageLoadEvent | checking page load events",{pathname:n}),e.forEach(({pages:t=[],excludedPages:i=[],event:s,callback:o=null})=>{let a=false;if(t.length?t.includes(n)&&(a=true):i.length&&i.includes(n)||(a=true),a){let r=o?o():s;this.log("pageLoadEvent | dispatching event for page",{pathname:n,event:r.name}),this.loadEvent([{event:r}]);}else this.log("pageLoadEvent | skipped event for page",{pathname:n,event:s.name,pages:t,excludedPages:i});}),this}clearInterval(){this.interval&&(clearInterval(this.interval),this.interval=null);}cleanup(){this.clearInterval(),this.responses=[],this.isTrackingResponses=false;}},f=new p;typeof window<"u"&&(window.cacheTrackEvents=f);export{f as a};//# sourceMappingURL=chunk-7CT4XR74.mjs.map
3
- //# sourceMappingURL=chunk-7CT4XR74.mjs.map
1
+ import {g}from'./chunk-GGU2UVKH.mjs';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
+ var p=class{constructor(){this.interval=null;this.responses=[];this.isTrackingResponses=false;this.delegatedSelectors=new Set;this.debug=false;this.log=g("[CacheManager]",()=>this.debug);this.addEventhandler=this.addEventHandler.bind(this);}setDebug(e){this.debug=e;}hash(e,n=32){let t=a=>{let r=2166136261;for(let c=0;c<a.length;c++)r^=a.charCodeAt(c),r=r*16777619>>>0;return r.toString(16)},i=a=>btoa(a),s=t(e),o=i(s);for(;o.length<n;)o+=i(t(o));return o.substring(0,n)}getCookies(e){let t=`; ${document.cookie}`.split(`; ${e}=`);if(t.length===2){let i=decodeURIComponent(t.pop().split(";").shift());try{return JSON.parse(i)}catch{return i}}return null}trackPageUnload(){typeof window>"u"||window.addEventListener("beforeunload",()=>{this.isPageViewSent()||this.push("cached_analytics_page_views",{name:window.location.href,properties:{url:window.location.href}});});}trackResponses(){if(typeof window>"u"||typeof XMLHttpRequest>"u")return;let e=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(t,i){return this._url=i,this._method=t,e.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){return this.addEventListener("load",function(){let i=null;if(typeof t=="string")try{i=JSON.parse(t);}catch{i=t;}let s={url:this._url,method:this._method,status:this.status,headers:this.getAllResponseHeaders(),data:this.responseText,payload:i};f.responses.push(s);}),n.apply(this,arguments)},this.isTrackingResponses=true;}getAnalyticsInstance(){return typeof window>"u"?null:window.AnalyticsInstance??window.DerivAnalytics?.Analytics??window.Analytics?.Analytics}isReady(){if(typeof window>"u")return false;let e=this.getAnalyticsInstance();return e?!!e.getInstances?.()?.tracking:false}parseCookies(e){if(typeof document>"u")return null;let n=document.cookie.split("; ");for(let t of n){let i=t.indexOf("=");if(i!==-1&&decodeURIComponent(t.slice(0,i))===e){let s=t.slice(i+1);try{return JSON.parse(decodeURIComponent(s))}catch{return decodeURIComponent(s)}}}return null}isPageViewSent(){return !!this.responses.find(e=>e.payload?.type==="page"&&e.payload?.anonymousId)}set(e){this.log("set | caching event to cookie",e),this.push("cached_analytics_events",e);}push(e,n){if(typeof document>"u")return;let t=[],i=this.parseCookies(e);i&&Array.isArray(i)&&(t=i),t.push(n);let s=this.getAllowedDomain(),o=365*24*60*60,a=`${e}=${encodeURIComponent(JSON.stringify(t))}; path=/; Domain=${s}; max-age=${o}; SameSite=Lax`;document.cookie=a;}getAllowedDomain(){if(typeof window>"u")return "";let e=window.location.hostname;if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return e;let n=e.split(".");return n.length===1?e:`.${n.slice(-2).join(".")}`}processEvent(e){let n=this.getCookies("client_information");if(n){let{email:t=null}=n;t&&(e.properties.email_hash=this.hash(t));}if(e?.properties?.email){let t=e.properties.email;delete e.properties.email,e.properties.email_hash=this.hash(t);}return e}track(e,n=false){if(typeof window>"u")return;let t=this.processEvent(e),i=this.getAnalyticsInstance();this.isReady()&&!n?(this.log("track | analytics ready \u2014 calling trackEvent",{event:t.name,properties:t.properties}),i.trackEvent(t.name,t.properties)):(this.log("track | analytics not ready or cache=true \u2014 storing event",{event:t.name,cache:n}),this.set(t));}pageView(){typeof window>"u"||(this.log("pageView | starting page view polling"),this.isTrackingResponses||(this.trackResponses(),this.trackPageUnload()),this.interval=setInterval(()=>{let e=window.Analytics;typeof e<"u"&&typeof e.Analytics?.pageView=="function"&&this.isReady()&&(this.log("pageView | analytics ready \u2014 sending page view",{href:window.location.href}),e.Analytics.pageView(window.location.href,"Trader's hub")),this.isPageViewSent()&&(this.log("pageView | page view confirmed sent \u2014 clearing interval"),this.interval&&clearInterval(this.interval));},1e3));}listen(e,{name:n="",properties:t={}},i=false,s=null){let o=r=>{r.dataset?.clickEventTracking||(r.addEventListener("click",c=>{let l={name:n,properties:t,cache:i};if(typeof s=="function"){let d=s(c);l={...d,cache:d.cache??i};}this.track(l,l.cache??false);}),r.dataset.clickEventTracking="true");};(e instanceof NodeList?Array.from(e):[e]).forEach(o);}addEventHandler(e){return typeof window>"u"?this:(e.forEach(({element:n,event:t={name:"",properties:{}},cache:i=false,callback:s=null})=>{if(typeof n=="string"){let o=n;if(!this.delegatedSelectors.has(o)){let a=r=>{let c=r.target;if(!c)return;let l=c.closest(o);if(l&&!l.dataset?.clickEventTracking){let d={name:t.name,properties:t.properties,cache:i};if(typeof s=="function"){let h=s(r);d={...h,cache:h.cache??i};}l.dataset.clickEventTracking="true",this.track(d,d.cache??false);}};document.addEventListener("click",a),this.delegatedSelectors.add(o);}}else (n instanceof NodeList?Array.from(n):[n]).forEach(a=>{a&&!a.dataset?.clickEventTracking&&this.listen(a,t,i,s);});}),this)}loadEvent(e){return this.log("loadEvent | firing load events",e.map(n=>n.event.name)),e.forEach(({event:n})=>{let{name:t,properties:i}=n;this.track({name:t,properties:i});}),this}pageLoadEvent(e){if(typeof window>"u")return this;let n=window.location.pathname.slice(1);return this.log("pageLoadEvent | checking page load events",{pathname:n}),e.forEach(({pages:t=[],excludedPages:i=[],event:s,callback:o=null})=>{let a=false;if(t.length?t.includes(n)&&(a=true):i.length&&i.includes(n)||(a=true),a){let r=o?o():s;this.log("pageLoadEvent | dispatching event for page",{pathname:n,event:r.name}),this.loadEvent([{event:r}]);}else this.log("pageLoadEvent | skipped event for page",{pathname:n,event:s.name,pages:t,excludedPages:i});}),this}clearInterval(){this.interval&&(clearInterval(this.interval),this.interval=null);}cleanup(){this.clearInterval(),this.responses=[],this.isTrackingResponses=false;}},f=new p;typeof window<"u"&&(window.cacheTrackEvents=f);export{f as a};//# sourceMappingURL=chunk-LIPHY7JK.mjs.map
3
+ //# sourceMappingURL=chunk-LIPHY7JK.mjs.map