@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
@@ -93,10 +93,15 @@ declare class Posthog {
93
93
  * Call this when the user ID is available and PostHog is loaded.
94
94
  * No-op if client_id is already present.
95
95
  *
96
- * @param user_id - The user ID to use as client_id
97
- * @param email - The user's email, used to determine is_internal
96
+ * @param params.user_id - The user ID to use as client_id
97
+ * @param params.email - The user's email, used to determine is_internal
98
+ * @param params.country_of_residence - The user's country of residence
98
99
  */
99
- backfillPersonProperties: (user_id: string, email?: string) => void;
100
+ backfillPersonProperties: ({ user_id, email, country_of_residence, }: {
101
+ user_id: string;
102
+ email?: string;
103
+ country_of_residence?: string;
104
+ }) => void;
100
105
  /**
101
106
  * Capture a custom event with properties
102
107
  * Properties are pre-flattened and cleaned by analytics.ts before being passed here
@@ -93,10 +93,15 @@ declare class Posthog {
93
93
  * Call this when the user ID is available and PostHog is loaded.
94
94
  * No-op if client_id is already present.
95
95
  *
96
- * @param user_id - The user ID to use as client_id
97
- * @param email - The user's email, used to determine is_internal
96
+ * @param params.user_id - The user ID to use as client_id
97
+ * @param params.email - The user's email, used to determine is_internal
98
+ * @param params.country_of_residence - The user's country of residence
98
99
  */
99
- backfillPersonProperties: (user_id: string, email?: string) => void;
100
+ backfillPersonProperties: ({ user_id, email, country_of_residence, }: {
101
+ user_id: string;
102
+ email?: string;
103
+ country_of_residence?: string;
104
+ }) => void;
100
105
  /**
101
106
  * Capture a custom event with properties
102
107
  * Properties are pre-flattened and cleaned by analytics.ts before being passed here
@@ -1,3 +1,3 @@
1
- 'use strict';var chunkBVGYK54Z_js=require('../../chunk-BVGYK54Z.js'),growthbook=require('@growthbook/growthbook'),analyticsJs=require('@rudderstack/analytics-js');/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var i=class i{constructor(t,e,o={},n=false){this.analytics=new analyticsJs.RudderAnalytics;this.isLoaded=false;this.status=void 0;this.debug=false;this.log=chunkBVGYK54Z_js.g("[GrowthBook]",()=>this.debug);this.setAttributes=({id:t,country:e,user_language:o,device_language:n,device_type:s,utm_source:r,utm_medium:a,utm_campaign:d,is_authorised:h,url:u,domain:w,utm_content:l,residence_country:f,loggedIn:c,network_type:g,network_downlink:k,user_id:b,anonymous_id:p,account_mode:G})=>{let v={...this.GrowthBook.getAttributes(),id:t,...b!==void 0&&{user_id:b},...p!==void 0&&{anonymous_id:p},...e!==void 0&&{country:e},...f!==void 0&&{residence_country:f},...o!==void 0&&{user_language:o},...n!==void 0&&{device_language:n},...s!==void 0&&{device_type:s},...r!==void 0&&{utm_source:r},...a!==void 0&&{utm_medium:a},...d!==void 0&&{utm_campaign:d},...h!==void 0&&{is_authorised:h},...u!==void 0&&{url:u},...w!==void 0&&{domain:w},...l!==void 0&&{utm_content:l},...c!==void 0&&{loggedIn:c},...g!==void 0&&{network_type:g},...k!==void 0&&{network_downlink:k},...G!==void 0&&{account_mode:G}};this.log("setAttributes | updating GrowthBook attributes",v),this.GrowthBook.setAttributes(v);};this.getFeatureValue=(t,e)=>{let o=this.GrowthBook.getFeatureValue(t,e);return this.log("getFeatureValue",{key:t,value:o,defaultValue:e}),o};this.getStatus=async()=>(await this.waitForIsLoaded(),{isLoaded:this.isLoaded,status:this.status});this.getFeatureState=t=>{let e=this.GrowthBook.evalFeature(t);return this.log("getFeatureState",{id:t,result:e}),e};this.setUrl=t=>{this.log("setUrl",{href:t}),this.GrowthBook.setURL(t);};this.isOn=t=>{let e=this.GrowthBook.isOn(t);return this.log("isOn",{key:t,result:e}),e};this.init=async()=>{this.log("init | initializing GrowthBook SDK");let t=await this.GrowthBook.init({timeout:2e3,streaming:true}).catch(()=>{});this.status=t,this.isLoaded=true,this.log("init | GrowthBook SDK loaded",{status:t});};this.destroy=()=>{this.GrowthBook.destroy(),this.isLoaded=false,this.status=void 0;};this.debug=n;let s=typeof window<"u"?window.location.hostname.includes("localhost"):false;this.GrowthBook=new growthbook.GrowthBook({apiHost:chunkBVGYK54Z_js.a,clientKey:t,decryptionKey:e,antiFlicker:false,navigateDelay:0,antiFlickerTimeout:3500,subscribeToChanges:true,enableDevMode:s,trackingCallback:(r,a)=>{this.log("trackingCallback | experiment viewed",{experiment_id:r.key,variation_id:a.variationId}),typeof window<"u"&&window.dataLayer&&window.dataLayer.push({event:"experiment_viewed",event_category:"experiment",rudder_anonymous_id:this.analytics.getAnonymousId(),experiment_id:r.key,variation_id:a.variationId}),this.analytics.track("experiment_viewed",{experimentId:r.key,variationId:a.variationId});},...o}),this.init();}reapplyExperiment(t){let e=t??(typeof window<"u"?window.location.href:"");this.GrowthBook.setURL(e);}waitForIsLoaded(t=1e4){return new Promise((e,o)=>{let n=Date.now(),s=setInterval(()=>{this.isLoaded?(clearInterval(s),e()):Date.now()-n>=t&&(clearInterval(s),o(new Error("GrowthBook initialization timeout")));},100);})}};i.getGrowthBookInstance=(t,e,o,n=false)=>i._instance?(typeof window<"u"&&console.warn&&console.warn("GrowthBook instance already exists. Ignoring new initialization parameters."),i._instance):(i._instance=new i(t,e??"",o,n),i._instance),i.resetInstance=()=>{i._instance&&(i._instance.destroy(),i._instance=void 0);};var m=i;exports.Growthbook=m;//# sourceMappingURL=index.js.map
1
+ 'use strict';var chunkJ3V5QNIH_js=require('../../chunk-J3V5QNIH.js'),growthbook=require('@growthbook/growthbook'),analyticsJs=require('@rudderstack/analytics-js');/* @deriv-com/analytics - NPM Package - Built with tsup */
2
+ var i=class i{constructor(t,e,o={},n=false){this.analytics=new analyticsJs.RudderAnalytics;this.isLoaded=false;this.status=void 0;this.debug=false;this.log=chunkJ3V5QNIH_js.g("[GrowthBook]",()=>this.debug);this.setAttributes=({id:t,country:e,user_language:o,device_language:n,device_type:s,utm_source:r,utm_medium:a,utm_campaign:d,is_authorised:h,url:u,domain:w,utm_content:l,residence_country:f,loggedIn:c,network_type:g,network_downlink:k,user_id:b,anonymous_id:p,account_mode:G})=>{let v={...this.GrowthBook.getAttributes(),id:t,...b!==void 0&&{user_id:b},...p!==void 0&&{anonymous_id:p},...e!==void 0&&{country:e},...f!==void 0&&{residence_country:f},...o!==void 0&&{user_language:o},...n!==void 0&&{device_language:n},...s!==void 0&&{device_type:s},...r!==void 0&&{utm_source:r},...a!==void 0&&{utm_medium:a},...d!==void 0&&{utm_campaign:d},...h!==void 0&&{is_authorised:h},...u!==void 0&&{url:u},...w!==void 0&&{domain:w},...l!==void 0&&{utm_content:l},...c!==void 0&&{loggedIn:c},...g!==void 0&&{network_type:g},...k!==void 0&&{network_downlink:k},...G!==void 0&&{account_mode:G}};this.log("setAttributes | updating GrowthBook attributes",v),this.GrowthBook.setAttributes(v);};this.getFeatureValue=(t,e)=>{let o=this.GrowthBook.getFeatureValue(t,e);return this.log("getFeatureValue",{key:t,value:o,defaultValue:e}),o};this.getStatus=async()=>(await this.waitForIsLoaded(),{isLoaded:this.isLoaded,status:this.status});this.getFeatureState=t=>{let e=this.GrowthBook.evalFeature(t);return this.log("getFeatureState",{id:t,result:e}),e};this.setUrl=t=>{this.log("setUrl",{href:t}),this.GrowthBook.setURL(t);};this.isOn=t=>{let e=this.GrowthBook.isOn(t);return this.log("isOn",{key:t,result:e}),e};this.init=async()=>{this.log("init | initializing GrowthBook SDK");let t=await this.GrowthBook.init({timeout:2e3,streaming:true}).catch(()=>{});this.status=t,this.isLoaded=true,this.log("init | GrowthBook SDK loaded",{status:t});};this.destroy=()=>{this.GrowthBook.destroy(),this.isLoaded=false,this.status=void 0;};this.debug=n;let s=typeof window<"u"?window.location.hostname.includes("localhost"):false;this.GrowthBook=new growthbook.GrowthBook({apiHost:chunkJ3V5QNIH_js.a,clientKey:t,decryptionKey:e,antiFlicker:false,navigateDelay:0,antiFlickerTimeout:3500,subscribeToChanges:true,enableDevMode:s,trackingCallback:(r,a)=>{this.log("trackingCallback | experiment viewed",{experiment_id:r.key,variation_id:a.variationId}),typeof window<"u"&&window.dataLayer&&window.dataLayer.push({event:"experiment_viewed",event_category:"experiment",rudder_anonymous_id:this.analytics.getAnonymousId(),experiment_id:r.key,variation_id:a.variationId}),this.analytics.track("experiment_viewed",{experimentId:r.key,variationId:a.variationId});},...o}),this.init();}reapplyExperiment(t){let e=t??(typeof window<"u"?window.location.href:"");this.GrowthBook.setURL(e);}waitForIsLoaded(t=1e4){return new Promise((e,o)=>{let n=Date.now(),s=setInterval(()=>{this.isLoaded?(clearInterval(s),e()):Date.now()-n>=t&&(clearInterval(s),o(new Error("GrowthBook initialization timeout")));},100);})}};i.getGrowthBookInstance=(t,e,o,n=false)=>i._instance?(typeof window<"u"&&console.warn&&console.warn("GrowthBook instance already exists. Ignoring new initialization parameters."),i._instance):(i._instance=new i(t,e??"",o,n),i._instance),i.resetInstance=()=>{i._instance&&(i._instance.destroy(),i._instance=void 0);};var m=i;exports.Growthbook=m;//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
@@ -1,3 +1,3 @@
1
- import {g,a}from'../../chunk-ID2GN2PS.mjs';import {GrowthBook}from'@growthbook/growthbook';import {RudderAnalytics}from'@rudderstack/analytics-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
1
+ import {g,a}from'../../chunk-GGU2UVKH.mjs';import {GrowthBook}from'@growthbook/growthbook';import {RudderAnalytics}from'@rudderstack/analytics-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
2
  var i=class i{constructor(t,e,o={},n=false){this.analytics=new RudderAnalytics;this.isLoaded=false;this.status=void 0;this.debug=false;this.log=g("[GrowthBook]",()=>this.debug);this.setAttributes=({id:t,country:e,user_language:o,device_language:n,device_type:s,utm_source:r,utm_medium:a,utm_campaign:d,is_authorised:h,url:u,domain:w,utm_content:l,residence_country:f,loggedIn:c,network_type:g,network_downlink:k,user_id:b,anonymous_id:p,account_mode:G})=>{let v={...this.GrowthBook.getAttributes(),id:t,...b!==void 0&&{user_id:b},...p!==void 0&&{anonymous_id:p},...e!==void 0&&{country:e},...f!==void 0&&{residence_country:f},...o!==void 0&&{user_language:o},...n!==void 0&&{device_language:n},...s!==void 0&&{device_type:s},...r!==void 0&&{utm_source:r},...a!==void 0&&{utm_medium:a},...d!==void 0&&{utm_campaign:d},...h!==void 0&&{is_authorised:h},...u!==void 0&&{url:u},...w!==void 0&&{domain:w},...l!==void 0&&{utm_content:l},...c!==void 0&&{loggedIn:c},...g!==void 0&&{network_type:g},...k!==void 0&&{network_downlink:k},...G!==void 0&&{account_mode:G}};this.log("setAttributes | updating GrowthBook attributes",v),this.GrowthBook.setAttributes(v);};this.getFeatureValue=(t,e)=>{let o=this.GrowthBook.getFeatureValue(t,e);return this.log("getFeatureValue",{key:t,value:o,defaultValue:e}),o};this.getStatus=async()=>(await this.waitForIsLoaded(),{isLoaded:this.isLoaded,status:this.status});this.getFeatureState=t=>{let e=this.GrowthBook.evalFeature(t);return this.log("getFeatureState",{id:t,result:e}),e};this.setUrl=t=>{this.log("setUrl",{href:t}),this.GrowthBook.setURL(t);};this.isOn=t=>{let e=this.GrowthBook.isOn(t);return this.log("isOn",{key:t,result:e}),e};this.init=async()=>{this.log("init | initializing GrowthBook SDK");let t=await this.GrowthBook.init({timeout:2e3,streaming:true}).catch(()=>{});this.status=t,this.isLoaded=true,this.log("init | GrowthBook SDK loaded",{status:t});};this.destroy=()=>{this.GrowthBook.destroy(),this.isLoaded=false,this.status=void 0;};this.debug=n;let s=typeof window<"u"?window.location.hostname.includes("localhost"):false;this.GrowthBook=new GrowthBook({apiHost:a,clientKey:t,decryptionKey:e,antiFlicker:false,navigateDelay:0,antiFlickerTimeout:3500,subscribeToChanges:true,enableDevMode:s,trackingCallback:(r,a)=>{this.log("trackingCallback | experiment viewed",{experiment_id:r.key,variation_id:a.variationId}),typeof window<"u"&&window.dataLayer&&window.dataLayer.push({event:"experiment_viewed",event_category:"experiment",rudder_anonymous_id:this.analytics.getAnonymousId(),experiment_id:r.key,variation_id:a.variationId}),this.analytics.track("experiment_viewed",{experimentId:r.key,variationId:a.variationId});},...o}),this.init();}reapplyExperiment(t){let e=t??(typeof window<"u"?window.location.href:"");this.GrowthBook.setURL(e);}waitForIsLoaded(t=1e4){return new Promise((e,o)=>{let n=Date.now(),s=setInterval(()=>{this.isLoaded?(clearInterval(s),e()):Date.now()-n>=t&&(clearInterval(s),o(new Error("GrowthBook initialization timeout")));},100);})}};i.getGrowthBookInstance=(t,e,o,n=false)=>i._instance?(typeof window<"u"&&console.warn&&console.warn("GrowthBook instance already exists. Ignoring new initialization parameters."),i._instance):(i._instance=new i(t,e??"",o,n),i._instance),i.resetInstance=()=>{i._instance&&(i._instance.destroy(),i._instance=void 0);};var m=i;export{m as Growthbook};//# sourceMappingURL=index.mjs.map
3
3
  //# sourceMappingURL=index.mjs.map
@@ -1,3 +1,3 @@
1
- export { P as Posthog } from '../../posthog-Ds4g1sJf.mjs';
1
+ export { P as Posthog } from '../../posthog-CRa194Jm.mjs';
2
2
  import '../../types-DoMejCXv.mjs';
3
3
  import 'posthog-js';
@@ -1,3 +1,3 @@
1
- export { P as Posthog } from '../../posthog-DvDj4azD.js';
1
+ export { P as Posthog } from '../../posthog-CZnsy0at.js';
2
2
  import '../../types-DoMejCXv.js';
3
3
  import 'posthog-js';
@@ -1,3 +1,3 @@
1
- 'use strict';var chunkBVGYK54Z_js=require('../../chunk-BVGYK54Z.js'),s=require('posthog-js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var s__default=/*#__PURE__*/_interopDefault(s);/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var r=class r{constructor(i,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=chunkBVGYK54Z_js.g("[PostHog]",()=>this.debug);this.init=()=>{try{let{apiKey:i,api_host:t,config:e={}}=this.options;if(!i){console.warn("Posthog: No API key provided");return}this.log("init | loading PostHog SDK",{api_host:t||chunkBVGYK54Z_js.c});let o={api_host:t||chunkBVGYK54Z_js.c,ui_host:chunkBVGYK54Z_js.d,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...e.session_recording},before_send:n=>{if(typeof window>"u")return null;let a=window.location.hostname;if(a==="localhost"||a==="127.0.0.1")return n;let h=chunkBVGYK54Z_js.e.some(c=>a.endsWith(`.${c}`)||a===c);return h||this.log("init | before_send blocked event from disallowed host",{currentHost:a}),h?n:null},...e};s__default.default.init(i,o),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(i){console.error("Posthog: Failed to initialize",i);}};this.identifyEvent=(i,t)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let e=typeof s__default.default._isIdentified=="function"?s__default.default._isIdentified():this.has_identified;if(i&&!e){let{email:o,...n}=t;this.log("identifyEvent | identifying user",{user_id:i,safeTraits:n}),s__default.default.identify(i,{...n,client_id:i,...o&&{is_internal:chunkBVGYK54Z_js.h(o)}}),this.has_identified=!0;}else this.log("identifyEvent | skipped \u2014 user already identified",{user_id:i});}catch(e){console.error("Posthog: Failed to identify user",e);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),s__default.default.reset(),this.has_identified=!1;}catch(i){console.error("Posthog: Failed to reset",i);}};this.backfillPersonProperties=(i,t)=>{if(!(!this.has_initialized||!i))try{let e=s__default.default.get_property("$stored_person_properties"),o={};e?.client_id||(o.client_id=i),t&&e?.is_internal===void 0&&(o.is_internal=chunkBVGYK54Z_js.h(t)),Object.keys(o).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:i,updates:o}),s__default.default.setPersonProperties(o)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:i});}catch(e){console.error("Posthog: Failed to backfill person properties",e);}};this.capture=(i,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:i,properties:t}),s__default.default.capture(i,t);}catch(e){console.error("Posthog: Failed to capture event",e);}};this.options=i,this.debug=t,this.init();}};r.getPosthogInstance=(i,t=false)=>(r._instance||(r._instance=new r(i,t)),r._instance);var u=r;exports.Posthog=u;//# sourceMappingURL=index.js.map
1
+ 'use strict';var chunkJ3V5QNIH_js=require('../../chunk-J3V5QNIH.js'),r=require('posthog-js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var r__default=/*#__PURE__*/_interopDefault(r);/* @deriv-com/analytics - NPM Package - Built with tsup */
2
+ var n=class n{constructor(i,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=chunkJ3V5QNIH_js.g("[PostHog]",()=>this.debug);this.init=()=>{try{let{apiKey:i,api_host:t,config:e={}}=this.options;if(!i){console.warn("Posthog: No API key provided");return}let o=t||chunkJ3V5QNIH_js.d();this.log("init | loading PostHog SDK",{api_host:o});let s={api_host:o,ui_host:chunkJ3V5QNIH_js.c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...e.session_recording},before_send:d=>{if(typeof window>"u")return null;let a=window.location.hostname;if(a==="localhost"||a==="127.0.0.1")return d;let c=chunkJ3V5QNIH_js.e.some(h=>a.endsWith(`.${h}`)||a===h);return c||this.log("init | before_send blocked event from disallowed host",{currentHost:a}),c?d:null},...e};r__default.default.init(i,s),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(i){console.error("Posthog: Failed to initialize",i);}};this.identifyEvent=(i,t)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let e=typeof r__default.default._isIdentified=="function"?r__default.default._isIdentified():this.has_identified;if(i&&!e){let{email:o,...s}=t;this.log("identifyEvent | identifying user",{user_id:i,safeTraits:s}),r__default.default.identify(i,{...s,client_id:i,...o&&{is_internal:chunkJ3V5QNIH_js.h(o)}}),this.has_identified=!0;}else this.log("identifyEvent | skipped \u2014 user already identified",{user_id:i});}catch(e){console.error("Posthog: Failed to identify user",e);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),r__default.default.reset(),this.has_identified=!1;}catch(i){console.error("Posthog: Failed to reset",i);}};this.backfillPersonProperties=({user_id:i,email:t,country_of_residence:e})=>{if(!(!this.has_initialized||!i))try{let o=r__default.default.get_property("$stored_person_properties")??{},s={};o.client_id||(s.client_id=i),t&&o.is_internal===void 0&&(s.is_internal=chunkJ3V5QNIH_js.h(t)),e&&!o.country_of_residence&&(s.country_of_residence=e),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:i,updates:s}),r__default.default.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:i,country_of_residence:e});}catch(o){console.error("Posthog: Failed to backfill person properties",o);}};this.capture=(i,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:i,properties:t}),r__default.default.capture(i,t);}catch(e){console.error("Posthog: Failed to capture event",e);}};this.options=i,this.debug=t,this.init();}};n.getPosthogInstance=(i,t=false)=>(n._instance||(n._instance=new n(i,t)),n._instance);var P=n;exports.Posthog=P;//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","apiKey","api_host","config","posthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","domain","posthog","error","user_id","traits","isIdentified","email","safeTraits","isInternalEmail","storedProperties","updates","event_name","properties","Posthog"],"mappings":";AAqBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,IAAA,CAAA,eAAA,CAAkB,KAAA,CAClB,oBAAiB,KAAA,CAGjB,IAAA,CAAQ,MAAQ,KAAA,CAChB,IAAA,CAAQ,GAAA,CAAMC,kBAAAA,CAAa,WAAA,CAAa,IAAM,KAAK,KAAK,CAAA,CAyBxD,UAAO,IAAY,CACf,GAAI,CACA,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAAC,EAAU,MAAA,CAAAC,CAAAA,CAAS,EAAG,CAAA,CAAI,KAAK,OAAA,CAE/C,GAAI,CAACF,CAAAA,CAAQ,CACT,OAAA,CAAQ,KAAK,8BAA8B,CAAA,CAC3C,MACJ,CAEA,IAAA,CAAK,IAAI,4BAAA,CAA8B,CAAE,QAAA,CAAUC,CAAAA,EAAYE,kBAAe,CAAC,EAE/E,IAAMC,CAAAA,CAAgC,CAClC,QAAA,CAAUH,CAAAA,EAAYE,mBACtB,OAAA,CAASE,kBAAAA,CACT,WAAA,CAAa,CA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BF,CAAK,CAAA,CAAA,CAG3C,MAAA,CAAO,KAAKI,CAAO,CAAA,CAAE,OAAS,CAAA,EAC9B,IAAA,CAAK,GAAA,CAAI,0DAAA,CAA4D,CAAE,OAAA,CAAAP,EAAS,OAAA,CAAAO,CAAQ,CAAC,CAAA,CACzFT,kBAAAA,CAAQ,oBAAoBS,CAAO,CAAA,EAEnC,IAAA,CAAK,GAAA,CAAI,0EAAA,CAAuE,CAAE,QAAAP,CAAQ,CAAC,EAEnG,CAAA,MAASD,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,+CAAA,CAAiDA,CAAK,EACxE,CACJ,EASA,IAAA,CAAA,OAAA,CAAU,CAACS,CAAAA,CAAoBC,CAAAA,GAAsE,CACjG,GAAK,KAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,GAAA,CAAI,oCAAA,CAAsC,CAAE,UAAA,CAAAD,CAAAA,CAAY,WAAAC,CAAW,CAAC,EACzEX,kBAAAA,CAAQ,OAAA,CAAQU,CAAAA,CAAYC,CAAU,EAC1C,CAAA,MAASV,EAAO,CACZ,OAAA,CAAQ,MAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CAvKI,IAAA,CAAK,OAAA,CAAUf,CAAAA,CACf,IAAA,CAAK,MAAQC,CAAAA,CACb,IAAA,CAAK,OACT,CAqKJ,EAjLaF,CAAAA,CAoBK,kBAAA,CAAqB,CAACC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,IAC7DF,EAAQ,SAAA,GACTA,CAAAA,CAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,CAxBhB,IAAM2B,CAAAA,CAAN3B","file":"index.js","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport type { TCoreAttributes } from '../types'\nimport { allowedDomains, posthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Initialize PostHog with configuration\n * Configures PostHog instance with provided options\n */\n init = (): void => {\n try {\n const { apiKey, api_host, config = {} } = this.options\n\n if (!apiKey) {\n console.warn('Posthog: No API key provided')\n return\n }\n\n this.log('init | loading PostHog SDK', { api_host: api_host || posthogApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: api_host || posthogApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n session_recording: {\n recordCrossOriginIframes: true,\n minimumDurationMilliseconds: 30000,\n ...config.session_recording,\n },\n before_send: event => {\n if (typeof window === 'undefined') return null\n\n const currentHost = window.location.hostname\n if (currentHost === 'localhost' || currentHost === '127.0.0.1') return event\n\n const isAllowed = allowedDomains.some(\n domain => currentHost.endsWith(`.${domain}`) || currentHost === domain\n )\n if (!isAllowed) this.log('init | before_send blocked event from disallowed host', { currentHost })\n return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n this.log('init | PostHog SDK loaded successfully')\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog.\n * Skipped if the user is already identified — use backfillPersonProperties to backfill\n * client_id for users identified in previous sessions.\n *\n * @param user_id - The user ID to identify\n * @param traits - User properties (language, country_of_residence, etc.)\n */\n identifyEvent = (user_id: string, traits: TPosthogIdentifyTraits): void => {\n if (!this.has_initialized) {\n console.warn('Posthog: Cannot identify - not initialized')\n return\n }\n\n try {\n const isIdentified =\n typeof posthog._isIdentified === 'function' ? posthog._isIdentified() : this.has_identified\n\n if (user_id && !isIdentified) {\n const { email, ...safeTraits } = traits\n this.log('identifyEvent | identifying user', { user_id, safeTraits })\n posthog.identify(user_id, {\n ...safeTraits,\n client_id: user_id,\n ...(email && { is_internal: isInternalEmail(email) }),\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param user_id - The user ID to use as client_id\n * @param email - The user's email, used to determine is_internal\n */\n backfillPersonProperties = (user_id: string, email?: string): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties = posthog.get_property('$stored_person_properties')\n const updates: Record<string, any> = {}\n\n if (!storedProperties?.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties?.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any> & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","apiKey","api_host","config","resolvedApiHost","getPosthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","domain","posthog","error","user_id","traits","isIdentified","email","safeTraits","isInternalEmail","country_of_residence","storedProperties","updates","event_name","properties","Posthog"],"mappings":";AAqBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,IAAA,CAAA,eAAA,CAAkB,KAAA,CAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,IAAA,CAAQ,KAAA,CAAQ,MAChB,IAAA,CAAQ,GAAA,CAAMC,kBAAAA,CAAa,WAAA,CAAa,IAAM,IAAA,CAAK,KAAK,CAAA,CAyBxD,IAAA,CAAA,IAAA,CAAO,IAAY,CACf,GAAI,CACA,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAAC,CAAAA,CAAU,MAAA,CAAAC,EAAS,EAAG,CAAA,CAAI,IAAA,CAAK,OAAA,CAE/C,GAAI,CAACF,CAAAA,CAAQ,CACT,OAAA,CAAQ,IAAA,CAAK,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AA,CAvLI,IAAA,CAAK,OAAA,CAAUhB,CAAAA,CACf,KAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,GACT,CAqLJ,EAjMaF,CAAAA,CAoBK,kBAAA,CAAqB,CAACC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,IAC7DF,EAAQ,SAAA,GACTA,CAAAA,CAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,CAxBhB,IAAM6B,CAAAA,CAAN7B","file":"index.js","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport type { TCoreAttributes } from '../types'\nimport { allowedDomains, getPosthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Initialize PostHog with configuration\n * Configures PostHog instance with provided options\n */\n init = (): void => {\n try {\n const { apiKey, api_host, config = {} } = this.options\n\n if (!apiKey) {\n console.warn('Posthog: No API key provided')\n return\n }\n\n const resolvedApiHost = api_host || getPosthogApiHost()\n this.log('init | loading PostHog SDK', { api_host: resolvedApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: resolvedApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n session_recording: {\n recordCrossOriginIframes: true,\n minimumDurationMilliseconds: 30000,\n ...config.session_recording,\n },\n before_send: event => {\n if (typeof window === 'undefined') return null\n\n const currentHost = window.location.hostname\n if (currentHost === 'localhost' || currentHost === '127.0.0.1') return event\n\n const isAllowed = allowedDomains.some(\n domain => currentHost.endsWith(`.${domain}`) || currentHost === domain\n )\n if (!isAllowed) this.log('init | before_send blocked event from disallowed host', { currentHost })\n return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n this.log('init | PostHog SDK loaded successfully')\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog.\n * Skipped if the user is already identified — use backfillPersonProperties to backfill\n * client_id for users identified in previous sessions.\n *\n * @param user_id - The user ID to identify\n * @param traits - User properties (language, country_of_residence, etc.)\n */\n identifyEvent = (user_id: string, traits: TPosthogIdentifyTraits): void => {\n if (!this.has_initialized) {\n console.warn('Posthog: Cannot identify - not initialized')\n return\n }\n\n try {\n const isIdentified =\n typeof posthog._isIdentified === 'function' ? posthog._isIdentified() : this.has_identified\n\n if (user_id && !isIdentified) {\n const { email, ...safeTraits } = traits\n this.log('identifyEvent | identifying user', { user_id, safeTraits })\n posthog.identify(user_id, {\n ...safeTraits,\n client_id: user_id,\n ...(email && { is_internal: isInternalEmail(email) }),\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param params.user_id - The user ID to use as client_id\n * @param params.email - The user's email, used to determine is_internal\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n country_of_residence?: string\n }): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties: Record<string, any> = posthog.get_property('$stored_person_properties') ?? {}\n const updates: Record<string, any> = {}\n\n if (!storedProperties.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n if (country_of_residence && !storedProperties.country_of_residence) {\n updates.country_of_residence = country_of_residence\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', {\n user_id,\n country_of_residence,\n })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any> & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n}\n"]}
@@ -1,3 +1,3 @@
1
- import {g,c,e,d,h}from'../../chunk-ID2GN2PS.mjs';import s from'posthog-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var r=class r{constructor(i,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=g("[PostHog]",()=>this.debug);this.init=()=>{try{let{apiKey:i,api_host:t,config:e$1={}}=this.options;if(!i){console.warn("Posthog: No API key provided");return}this.log("init | loading PostHog SDK",{api_host:t||c});let o={api_host:t||c,ui_host:d,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...e$1.session_recording},before_send:n=>{if(typeof window>"u")return null;let a=window.location.hostname;if(a==="localhost"||a==="127.0.0.1")return n;let h=e.some(c=>a.endsWith(`.${c}`)||a===c);return h||this.log("init | before_send blocked event from disallowed host",{currentHost:a}),h?n:null},...e$1};s.init(i,o),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(i){console.error("Posthog: Failed to initialize",i);}};this.identifyEvent=(i,t)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let e=typeof s._isIdentified=="function"?s._isIdentified():this.has_identified;if(i&&!e){let{email:o,...n}=t;this.log("identifyEvent | identifying user",{user_id:i,safeTraits:n}),s.identify(i,{...n,client_id:i,...o&&{is_internal:h(o)}}),this.has_identified=!0;}else this.log("identifyEvent | skipped \u2014 user already identified",{user_id:i});}catch(e){console.error("Posthog: Failed to identify user",e);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),s.reset(),this.has_identified=!1;}catch(i){console.error("Posthog: Failed to reset",i);}};this.backfillPersonProperties=(i,t)=>{if(!(!this.has_initialized||!i))try{let e=s.get_property("$stored_person_properties"),o={};e?.client_id||(o.client_id=i),t&&e?.is_internal===void 0&&(o.is_internal=h(t)),Object.keys(o).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:i,updates:o}),s.setPersonProperties(o)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:i});}catch(e){console.error("Posthog: Failed to backfill person properties",e);}};this.capture=(i,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:i,properties:t}),s.capture(i,t);}catch(e){console.error("Posthog: Failed to capture event",e);}};this.options=i,this.debug=t,this.init();}};r.getPosthogInstance=(i,t=false)=>(r._instance||(r._instance=new r(i,t)),r._instance);var u=r;export{u as Posthog};//# sourceMappingURL=index.mjs.map
1
+ import {g,d,e,c,h}from'../../chunk-GGU2UVKH.mjs';import r from'posthog-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
+ var n=class n{constructor(i,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=g("[PostHog]",()=>this.debug);this.init=()=>{try{let{apiKey:i,api_host:t,config:e$1={}}=this.options;if(!i){console.warn("Posthog: No API key provided");return}let o=t||d();this.log("init | loading PostHog SDK",{api_host:o});let s={api_host:o,ui_host:c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...e$1.session_recording},before_send:d=>{if(typeof window>"u")return null;let a=window.location.hostname;if(a==="localhost"||a==="127.0.0.1")return d;let c=e.some(h=>a.endsWith(`.${h}`)||a===h);return c||this.log("init | before_send blocked event from disallowed host",{currentHost:a}),c?d:null},...e$1};r.init(i,s),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(i){console.error("Posthog: Failed to initialize",i);}};this.identifyEvent=(i,t)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let e=typeof r._isIdentified=="function"?r._isIdentified():this.has_identified;if(i&&!e){let{email:o,...s}=t;this.log("identifyEvent | identifying user",{user_id:i,safeTraits:s}),r.identify(i,{...s,client_id:i,...o&&{is_internal:h(o)}}),this.has_identified=!0;}else this.log("identifyEvent | skipped \u2014 user already identified",{user_id:i});}catch(e){console.error("Posthog: Failed to identify user",e);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),r.reset(),this.has_identified=!1;}catch(i){console.error("Posthog: Failed to reset",i);}};this.backfillPersonProperties=({user_id:i,email:t,country_of_residence:e})=>{if(!(!this.has_initialized||!i))try{let o=r.get_property("$stored_person_properties")??{},s={};o.client_id||(s.client_id=i),t&&o.is_internal===void 0&&(s.is_internal=h(t)),e&&!o.country_of_residence&&(s.country_of_residence=e),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:i,updates:s}),r.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:i,country_of_residence:e});}catch(o){console.error("Posthog: Failed to backfill person properties",o);}};this.capture=(i,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:i,properties:t}),r.capture(i,t);}catch(e){console.error("Posthog: Failed to capture event",e);}};this.options=i,this.debug=t,this.init();}};n.getPosthogInstance=(i,t=false)=>(n._instance||(n._instance=new n(i,t)),n._instance);var P=n;export{P as Posthog};//# sourceMappingURL=index.mjs.map
3
3
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","apiKey","api_host","config","posthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","domain","posthog","error","user_id","traits","isIdentified","email","safeTraits","isInternalEmail","storedProperties","updates","event_name","properties","Posthog"],"mappings":";AAqBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,IAAA,CAAA,eAAA,CAAkB,KAAA,CAClB,oBAAiB,KAAA,CAGjB,IAAA,CAAQ,MAAQ,KAAA,CAChB,IAAA,CAAQ,GAAA,CAAMC,CAAAA,CAAa,WAAA,CAAa,IAAM,KAAK,KAAK,CAAA,CAyBxD,UAAO,IAAY,CACf,GAAI,CACA,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAAC,EAAU,MAAA,CAAAC,GAAAA,CAAS,EAAG,CAAA,CAAI,KAAK,OAAA,CAE/C,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AAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,CAxBhB,IAAM2B,CAAAA,CAAN3B","file":"index.mjs","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport type { TCoreAttributes } from '../types'\nimport { allowedDomains, posthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Initialize PostHog with configuration\n * Configures PostHog instance with provided options\n */\n init = (): void => {\n try {\n const { apiKey, api_host, config = {} } = this.options\n\n if (!apiKey) {\n console.warn('Posthog: No API key provided')\n return\n }\n\n this.log('init | loading PostHog SDK', { api_host: api_host || posthogApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: api_host || posthogApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n session_recording: {\n recordCrossOriginIframes: true,\n minimumDurationMilliseconds: 30000,\n ...config.session_recording,\n },\n before_send: event => {\n if (typeof window === 'undefined') return null\n\n const currentHost = window.location.hostname\n if (currentHost === 'localhost' || currentHost === '127.0.0.1') return event\n\n const isAllowed = allowedDomains.some(\n domain => currentHost.endsWith(`.${domain}`) || currentHost === domain\n )\n if (!isAllowed) this.log('init | before_send blocked event from disallowed host', { currentHost })\n return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n this.log('init | PostHog SDK loaded successfully')\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog.\n * Skipped if the user is already identified — use backfillPersonProperties to backfill\n * client_id for users identified in previous sessions.\n *\n * @param user_id - The user ID to identify\n * @param traits - User properties (language, country_of_residence, etc.)\n */\n identifyEvent = (user_id: string, traits: TPosthogIdentifyTraits): void => {\n if (!this.has_initialized) {\n console.warn('Posthog: Cannot identify - not initialized')\n return\n }\n\n try {\n const isIdentified =\n typeof posthog._isIdentified === 'function' ? posthog._isIdentified() : this.has_identified\n\n if (user_id && !isIdentified) {\n const { email, ...safeTraits } = traits\n this.log('identifyEvent | identifying user', { user_id, safeTraits })\n posthog.identify(user_id, {\n ...safeTraits,\n client_id: user_id,\n ...(email && { is_internal: isInternalEmail(email) }),\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param user_id - The user ID to use as client_id\n * @param email - The user's email, used to determine is_internal\n */\n backfillPersonProperties = (user_id: string, email?: string): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties = posthog.get_property('$stored_person_properties')\n const updates: Record<string, any> = {}\n\n if (!storedProperties?.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties?.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any> & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","apiKey","api_host","config","resolvedApiHost","getPosthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","domain","posthog","error","user_id","traits","isIdentified","email","safeTraits","isInternalEmail","country_of_residence","storedProperties","updates","event_name","properties","Posthog"],"mappings":";AAqBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,IAAA,CAAA,eAAA,CAAkB,KAAA,CAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,IAAA,CAAQ,KAAA,CAAQ,MAChB,IAAA,CAAQ,GAAA,CAAMC,CAAAA,CAAa,WAAA,CAAa,IAAM,IAAA,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CAAI,oCAAA,CAAsC,CAAE,UAAA,CAAAD,CAAAA,CAAY,UAAA,CAAAC,CAAW,CAAC,CAAA,CACzEZ,CAAAA,CAAQ,OAAA,CAAQW,CAAAA,CAAYC,CAAU,EAC1C,CAAA,MAASX,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CAvLI,IAAA,CAAK,OAAA,CAAUhB,CAAAA,CACf,KAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,GACT,CAqLJ,EAjMaF,CAAAA,CAoBK,kBAAA,CAAqB,CAACC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,IAC7DF,EAAQ,SAAA,GACTA,CAAAA,CAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,CAxBhB,IAAM6B,CAAAA,CAAN7B","file":"index.mjs","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport type { TCoreAttributes } from '../types'\nimport { allowedDomains, getPosthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Initialize PostHog with configuration\n * Configures PostHog instance with provided options\n */\n init = (): void => {\n try {\n const { apiKey, api_host, config = {} } = this.options\n\n if (!apiKey) {\n console.warn('Posthog: No API key provided')\n return\n }\n\n const resolvedApiHost = api_host || getPosthogApiHost()\n this.log('init | loading PostHog SDK', { api_host: resolvedApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: resolvedApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n session_recording: {\n recordCrossOriginIframes: true,\n minimumDurationMilliseconds: 30000,\n ...config.session_recording,\n },\n before_send: event => {\n if (typeof window === 'undefined') return null\n\n const currentHost = window.location.hostname\n if (currentHost === 'localhost' || currentHost === '127.0.0.1') return event\n\n const isAllowed = allowedDomains.some(\n domain => currentHost.endsWith(`.${domain}`) || currentHost === domain\n )\n if (!isAllowed) this.log('init | before_send blocked event from disallowed host', { currentHost })\n return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n this.log('init | PostHog SDK loaded successfully')\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog.\n * Skipped if the user is already identified — use backfillPersonProperties to backfill\n * client_id for users identified in previous sessions.\n *\n * @param user_id - The user ID to identify\n * @param traits - User properties (language, country_of_residence, etc.)\n */\n identifyEvent = (user_id: string, traits: TPosthogIdentifyTraits): void => {\n if (!this.has_initialized) {\n console.warn('Posthog: Cannot identify - not initialized')\n return\n }\n\n try {\n const isIdentified =\n typeof posthog._isIdentified === 'function' ? posthog._isIdentified() : this.has_identified\n\n if (user_id && !isIdentified) {\n const { email, ...safeTraits } = traits\n this.log('identifyEvent | identifying user', { user_id, safeTraits })\n posthog.identify(user_id, {\n ...safeTraits,\n client_id: user_id,\n ...(email && { is_internal: isInternalEmail(email) }),\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param params.user_id - The user ID to use as client_id\n * @param params.email - The user's email, used to determine is_internal\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n country_of_residence?: string\n }): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties: Record<string, any> = posthog.get_property('$stored_person_properties') ?? {}\n const updates: Record<string, any> = {}\n\n if (!storedProperties.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n if (country_of_residence && !storedProperties.country_of_residence) {\n updates.country_of_residence = country_of_residence\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', {\n user_id,\n country_of_residence,\n })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any> & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n}\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkILN7DKKL_js=require('../../chunk-ILN7DKKL.js');require('../../chunk-BVGYK54Z.js');Object.defineProperty(exports,"RudderStack",{enumerable:true,get:function(){return chunkILN7DKKL_js.a}});//# sourceMappingURL=index.js.map
1
+ 'use strict';var chunkY3QT7NAG_js=require('../../chunk-Y3QT7NAG.js');require('../../chunk-J3V5QNIH.js');Object.defineProperty(exports,"RudderStack",{enumerable:true,get:function(){return chunkY3QT7NAG_js.a}});//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- export{a as RudderStack}from'../../chunk-D2MKQCJB.mjs';import'../../chunk-ID2GN2PS.mjs';//# sourceMappingURL=index.mjs.map
1
+ export{a as RudderStack}from'../../chunk-44P2MMGV.mjs';import'../../chunk-GGU2UVKH.mjs';//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkFE5YWK6A_js=require('../../chunk-FE5YWK6A.js');require('../../chunk-BVGYK54Z.js');Object.defineProperty(exports,"cacheTrackEvents",{enumerable:true,get:function(){return chunkFE5YWK6A_js.a}});//# sourceMappingURL=index.js.map
1
+ 'use strict';var chunkSQ6Q4Z5S_js=require('../../chunk-SQ6Q4Z5S.js');require('../../chunk-J3V5QNIH.js');Object.defineProperty(exports,"cacheTrackEvents",{enumerable:true,get:function(){return chunkSQ6Q4Z5S_js.a}});//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- export{a as cacheTrackEvents}from'../../chunk-7CT4XR74.mjs';import'../../chunk-ID2GN2PS.mjs';//# sourceMappingURL=index.mjs.map
1
+ export{a as cacheTrackEvents}from'../../chunk-LIPHY7JK.mjs';import'../../chunk-GGU2UVKH.mjs';//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deriv-com/analytics",
3
- "version": "1.38.9",
3
+ "version": "1.39.0",
4
4
  "description": "Comprehensive analytics package for Deriv applications. Provides unified event tracking, A/B testing, and user analytics through RudderStack, PostHog and GrowthBook integrations with built-in caching and offline support.",
5
5
  "keywords": [
6
6
  "rudderstack",
@@ -1,4 +0,0 @@
1
- 'use strict';var m=require('js-cookie');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var m__default=/*#__PURE__*/_interopDefault(m);/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var i="https://deriv.com/cdn-cgi/trace",y="https://cdn.growthbook.io",f="https://deriv-dataplane.rudderstack.com",g="https://ph.deriv.com",h="https://us.posthog.com",p=["deriv.com","deriv.be","deriv.me","deriv.team","deriv.ae"],c=["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=p.find(o=>t.includes(o));return e?`.${e}`:".deriv.com"};var b=(t,e)=>(...o)=>{e()&&console.log(`[ANALYTIC]${t}`,...o);},O=t=>{let e=t.split("@")[1]?.toLowerCase();return e?c.includes(e):false},D=t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t),a=null,R=async()=>{if(a)return a;let t=JSON.parse(m__default.default.get("website_status")||"{}")?.clients_country;return a=(async()=>{try{let e=await fetch(i).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||""}})(),a},l=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=l(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=l(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;}},C=t=>{if(t==null||typeof t!="object"||Array.isArray(t))return t;let e={};return u(t,e),e};exports.a=y;exports.b=f;exports.c=g;exports.d=h;exports.e=p;exports.f=x;exports.g=b;exports.h=O;exports.i=D;exports.j=R;exports.k=l;exports.l=C;//# sourceMappingURL=chunk-BVGYK54Z.js.map
4
- //# sourceMappingURL=chunk-BVGYK54Z.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/urls.ts","../src/utils/helpers.ts"],"names":["cloudflareTrace","growthbookApi","rudderstackDataplane","posthogApiHost","posthogUiHost","allowedDomains","internalEmailDomains","getAllowedDomain","hostname","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":";AAAO,IAAMA,EAAkB,iCAAA,CAClBC,CAAAA,CAAgB,4BAChBC,CAAAA,CAAuB,yCAAA,CACvBC,EAAiB,sBAAA,CACjBC,CAAAA,CAAgB,yBAEhBC,CAAAA,CAAiB,CAAC,YAAa,UAAA,CAAY,UAAA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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 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,4 +0,0 @@
1
- import p from'js-cookie';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var i="https://deriv.com/cdn-cgi/trace",m="https://cdn.growthbook.io",y="https://deriv-dataplane.rudderstack.com",f="https://ph.deriv.com",g="https://us.posthog.com",d=["deriv.com","deriv.be","deriv.me","deriv.team","deriv.ae"],c=["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"],h=()=>{if(typeof window>"u")return ".deriv.com";let t=window.location.hostname;if(t==="localhost")return "";let e=d.find(o=>t.includes(o));return e?`.${e}`:".deriv.com"};var A=(t,e)=>(...o)=>{e()&&console.log(`[ANALYTIC]${t}`,...o);},k=t=>{let e=t.split("@")[1]?.toLowerCase();return e?c.includes(e):false},b=t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t),a=null,O=async()=>{if(a)return a;let t=JSON.parse(p.get("website_status")||"{}")?.clients_country;return a=(async()=>{try{let e=await fetch(i).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||""}})(),a},l=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=l(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=l(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;}},D=t=>{if(t==null||typeof t!="object"||Array.isArray(t))return t;let e={};return u(t,e),e};export{m as a,y as b,f as c,g as d,d as e,h as f,A as g,k as h,b as i,O as j,l as k,D as l};//# sourceMappingURL=chunk-ID2GN2PS.mjs.map
4
- //# sourceMappingURL=chunk-ID2GN2PS.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/urls.ts","../src/utils/helpers.ts"],"names":["cloudflareTrace","growthbookApi","rudderstackDataplane","posthogApiHost","posthogUiHost","allowedDomains","internalEmailDomains","getAllowedDomain","hostname","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":";AAAO,IAAMA,EAAkB,iCAAA,CAClBC,CAAAA,CAAgB,4BAChBC,CAAAA,CAAuB,yCAAA,CACvBC,EAAiB,sBAAA,CACjBC,CAAAA,CAAgB,yBAEhBC,CAAAA,CAAiB,CAAC,YAAa,UAAA,CAAY,UAAA,CAAY,aAAc,UAAU,CAAA,CAE/EC,EAAuB,CAChC,WAAA,CACA,kBACA,aAAA,CACA,iBAAA,CACA,mBACA,iBAAA,CACA,iBAAA,CACA,aACA,kBAAA,CACA,iBAAA,CACA,QACA,aAAA,CACA,mBAAA,CACA,SACA,WAAA,CACA,YAAA,CACA,iBACA,kBAAA,CACA,UAAA,CACA,aACA,aAAA,CACA,eAAA,CACA,yBACA,wBACJ,CAAA,CAEaC,EAAmB,IAAc,CAC1C,GAAI,OAAO,MAAA,CAAW,IAAa,OAAO,YAAA,CAC1C,IAAMC,CAAAA,CAAW,MAAA,CAAO,SAAS,QAAA,CAEjC,GAAIA,IAAa,WAAA,CAAa,OAAO,GAErC,IAAMC,CAAAA,CAAUJ,EAAe,IAAA,CAAKK,CAAAA,EAAKF,EAAS,QAAA,CAASE,CAAC,CAAC,CAAA,CAC7D,OAAOD,EAAU,CAAA,CAAA,EAAIA,CAAO,GAAK,YACrC,MCzBaE,CAAAA,CACT,CAACC,EAAgBC,CAAAA,GACjB,CAAA,GAAIC,IAAsB,CAClBD,CAAAA,IAAkB,OAAA,CAAQ,GAAA,CAAI,aAAaD,CAAM,CAAA,CAAA,CAAI,GAAGE,CAAI,EACpE,EAESC,CAAAA,CAAmBC,CAAAA,EAA2B,CACvD,IAAMC,CAAAA,CAASD,EAAM,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA,EAAG,aAAY,CAChD,OAAKC,EACGX,CAAAA,CAA2C,QAAA,CAASW,CAAM,CAAA,CAD9C,KAExB,EAEaC,CAAAA,CAAU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AAA,EAAY,KAAA,CAAM,OAAA,CAAQA,CAAG,EAC3D,OAAOA,CAAAA,CAEX,IAAMO,CAAAA,CAA8B,EAAC,CACrC,OAAAD,CAAAA,CAAaN,CAAAA,CAAKO,CAAM,CAAA,CACjBA,CACX","file":"chunk-ID2GN2PS.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 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,9 +0,0 @@
1
- /* @deriv-com/analytics - Browser ESM Bundle (RudderStack + PostHog) - Built with tsup */
2
- var x=Object.defineProperty;var w=(e,t,r)=>t in e?x(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var R=(e,t,r)=>w(e,typeof t!="symbol"?t+"":t,r);var f="https://deriv.com/cdn-cgi/trace",O="https://cdn.growthbook.io",I="https://deriv-dataplane.rudderstack.com",U="https://ph.deriv.com",b="https://us.posthog.com",k=["deriv.com","deriv.be","deriv.me","deriv.team","deriv.ae"],m=["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"],E=()=>{if(typeof window>"u")return".deriv.com";let e=window.location.hostname;if(e==="localhost")return"";let t=k.find(r=>e.includes(r));return t?`.${t}`:".deriv.com"};function l(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)e[o]=r[o]}return e}var A={read:function(e){return e[0]==='"'&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function u(e,t){function r(n,c,i){if(!(typeof document>"u")){i=l({},t,i),typeof i.expires=="number"&&(i.expires=new Date(Date.now()+i.expires*864e5)),i.expires&&(i.expires=i.expires.toUTCString()),n=encodeURIComponent(n).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var s="";for(var a in i)i[a]&&(s+="; "+a,i[a]!==!0&&(s+="="+i[a].split(";")[0]));return document.cookie=n+"="+e.write(c,n)+s}}function o(n){if(!(typeof document>"u"||arguments.length&&!n)){for(var c=document.cookie?document.cookie.split("; "):[],i={},s=0;s<c.length;s++){var a=c[s].split("="),v=a.slice(1).join("=");try{var d=decodeURIComponent(a[0]);if(i[d]=e.read(v,d),n===d)break}catch{}}return n?i[n]:i}}return Object.create({set:r,get:o,remove:function(n,c){r(n,"",l({},c,{expires:-1}))},withAttributes:function(n){return u(this.converter,l({},this.attributes,n))},withConverter:function(n){return u(l({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(e)}})}var y=u(A,{path:"/"});var z=(e,t)=>(...r)=>{t()&&console.log(`[ANALYTIC]${e}`,...r)},F=e=>{let t=e.split("@")[1]?.toLowerCase();return t?m.includes(t):!1},_=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),p=null,$=async()=>{if(p)return p;let e=JSON.parse(y.get("website_status")||"{}")?.clients_country;return p=(async()=>{try{let t=await fetch(f).catch(()=>null);if(!t)return e||"";let r=await t.text().catch(()=>"");return r?Object.fromEntries(r.split(`
3
- `).map(n=>n.split("=",2))).loc?.toLowerCase()||e||"":e||""}catch{return e||""}})(),p},g=e=>{if(e==null||typeof e!="object")return e;if(Array.isArray(e)){let o=[];for(let n=0;n<e.length;n++){let c=g(e[n]);c!=null&&o.push(c)}return o.length?o:void 0}let t={},r=!1;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;let n=g(e[o]);n==null||n===""||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0||Array.isArray(n)&&n.length===0||(t[o]=n,r=!0)}return r?t:void 0},h=(e,t)=>{for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let o=e[r];o&&typeof o=="object"&&!Array.isArray(o)?h(o,t):t[r]=o}},q=e=>{if(e==null||typeof e!="object"||Array.isArray(e))return e;let t={};return h(e,t),t};export{R as a,O as b,I as c,U as d,b as e,k as f,E as g,y as h,z as i,F as j,_ as k,$ as l,g as m,q as n};
4
- /*! Bundled license information:
5
-
6
- js-cookie/dist/js.cookie.mjs:
7
- (*! js-cookie v3.0.5 | MIT *)
8
- */
9
- //# sourceMappingURL=chunk-OB6HH25Z.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/urls.ts","../node_modules/js-cookie/dist/js.cookie.mjs","../src/utils/helpers.ts"],"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 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","/*! js-cookie v3.0.5 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n function set (name, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n name = encodeURIComponent(name)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n name + '=' + converter.write(value, name) + stringifiedAttributes)\n }\n\n function get (name) {\n if (typeof document === 'undefined' || (arguments.length && !name)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var found = decodeURIComponent(parts[0]);\n jar[found] = converter.read(value, found);\n\n if (name === found) {\n break\n }\n } catch (e) {}\n }\n\n return name ? jar[name] : jar\n }\n\n return Object.create(\n {\n set,\n get,\n remove: function (name, attributes) {\n set(\n name,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n/* eslint-enable no-var */\n\nexport { api as default };\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"],"mappings":";oKAAO,IAAMA,EAAkB,kCAClBC,EAAgB,4BAChBC,EAAuB,0CACvBC,EAAiB,uBACjBC,EAAgB,yBAEhBC,EAAiB,CAAC,YAAa,WAAY,WAAY,aAAc,UAAU,EAE/EC,EAAuB,CAChC,YACA,kBACA,cACA,kBACA,mBACA,kBACA,kBACA,aACA,mBACA,kBACA,QACA,cACA,oBACA,SACA,YACA,aACA,iBACA,mBACA,WACA,aACA,cACA,gBACA,yBACA,wBACJ,EAEaC,EAAmB,IAAc,CAC1C,GAAI,OAAO,OAAW,IAAa,MAAO,aAC1C,IAAMC,EAAW,OAAO,SAAS,SAEjC,GAAIA,IAAa,YAAa,MAAO,GAErC,IAAMC,EAAUJ,EAAe,KAAKK,GAAKF,EAAS,SAASE,CAAC,CAAC,EAC7D,OAAOD,EAAU,IAAIA,CAAO,GAAK,YACrC,ECzCA,SAASE,EAAQC,EAAQ,CACvB,QAASC,EAAI,EAAGA,EAAI,UAAU,OAAQA,IAAK,CACzC,IAAIC,EAAS,UAAUD,CAAC,EACxB,QAASE,KAAOD,EACdF,EAAOG,CAAG,EAAID,EAAOC,CAAG,CAE5B,CACA,OAAOH,CACT,CAIA,IAAII,EAAmB,CACrB,KAAM,SAAUC,EAAO,CACrB,OAAIA,EAAM,CAAC,IAAM,MACfA,EAAQA,EAAM,MAAM,EAAG,EAAE,GAEpBA,EAAM,QAAQ,mBAAoB,kBAAkB,CAC7D,EACA,MAAO,SAAUA,EAAO,CACtB,OAAO,mBAAmBA,CAAK,EAAE,QAC/B,2CACA,kBACF,CACF,CACF,EAKA,SAASC,EAAMC,EAAWC,EAAmB,CAC3C,SAASC,EAAKC,EAAML,EAAOM,EAAY,CACrC,GAAI,SAAO,SAAa,KAIxB,CAAAA,EAAaZ,EAAO,CAAC,EAAGS,EAAmBG,CAAU,EAEjD,OAAOA,EAAW,SAAY,WAChCA,EAAW,QAAU,IAAI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A,GAAQ,SAAU,OAAOA,EAEnD,GAAI,MAAM,QAAQA,CAAG,EAAG,CACpB,IAAMC,EAAa,CAAC,EACpB,QAASC,EAAI,EAAGA,EAAIF,EAAI,OAAQE,IAAK,CACjC,IAAMJ,EAAIC,EAAYC,EAAIE,CAAC,CAAC,EACLJ,GAAM,MAAMG,EAAI,KAAKH,CAAC,CACjD,CACA,OAAOG,EAAI,OAASA,EAAM,MAC9B,CAEA,IAAME,EAA+B,CAAC,EAClCC,EAAU,GACd,QAAWC,KAAOL,EAAK,CACnB,GAAI,CAAC,OAAO,UAAU,eAAe,KAAKA,EAAKK,CAAG,EAAG,SACrD,IAAMP,EAAIC,EAAYC,EAAIK,CAAG,CAAC,EAG1BP,GAAM,MACNA,IAAM,IACL,OAAOA,GAAM,UAAY,CAAC,MAAM,QAAQA,CAAC,GAAK,OAAO,KAAKA,CAAC,EAAE,SAAW,GACxE,MAAM,QAAQA,CAAC,GAAKA,EAAE,SAAW,IAGtCK,EAAQE,CAAG,EAAIP,EACfM,EAAU,GACd,CACA,OAAOA,EAAUD,EAAU,MAC/B,EAgBMG,EAAe,CAACN,EAA0BO,IAAsC,CAClF,QAAWF,KAAOL,EAAK,CACnB,GAAI,CAAC,OAAO,UAAU,eAAe,KAAKA,EAAKK,CAAG,EAAG,SACrD,IAAMG,EAAQR,EAAIK,CAAG,EACjBG,GAAS,OAAOA,GAAU,UAAY,CAAC,MAAM,QAAQA,CAAK,EAC1DF,EAAaE,EAAOD,CAAM,EAE1BA,EAAOF,CAAG,EAAIG,CAEtB,CACJ,EAEaC,EAAiBT,GAAkC,CAC5D,GAAIA,GAAO,MAAQ,OAAOA,GAAQ,UAAY,MAAM,QAAQA,CAAG,EAC3D,OAAOA,EAEX,IAAMO,EAA8B,CAAC,EACrC,OAAAD,EAAaN,EAAKO,CAAM,EACjBA,CACX","names":["cloudflareTrace","growthbookApi","rudderstackDataplane","posthogApiHost","posthogUiHost","allowedDomains","internalEmailDomains","getAllowedDomain","hostname","matched","d","assign","target","i","source","key","defaultConverter","value","init","converter","defaultAttributes","set","name","attributes","stringifiedAttributes","attributeName","get","cookies","jar","parts","found","api","createLogger","prefix","isDebugEnabled","args","isInternalEmail","email","domain","internalEmailDomains","isUUID","str","countryPromise","getCountry","cookieCountry","api","response","cloudflareTrace","text","v","cleanObject","obj","out","i","cleaned","hasKeys","key","_flattenInto","target","value","flattenObject"]}