@deriv-com/analytics 1.38.7 → 1.38.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +38 -8
  2. package/dist/browser/analytics.bundle.global.js +12 -12
  3. package/dist/browser/analytics.bundle.global.js.map +1 -1
  4. package/dist/browser/analytics.esm.mjs +1 -7
  5. package/dist/browser/analytics.esm.mjs.map +1 -1
  6. package/dist/chunk-7CT4XR74.mjs +3 -0
  7. package/dist/chunk-7CT4XR74.mjs.map +1 -0
  8. package/dist/chunk-BVGYK54Z.js +4 -0
  9. package/dist/chunk-BVGYK54Z.js.map +1 -0
  10. package/dist/chunk-D2MKQCJB.mjs +3 -0
  11. package/dist/chunk-D2MKQCJB.mjs.map +1 -0
  12. package/dist/chunk-FE5YWK6A.js +3 -0
  13. package/dist/chunk-FE5YWK6A.js.map +1 -0
  14. package/dist/chunk-ID2GN2PS.mjs +4 -0
  15. package/dist/chunk-ID2GN2PS.mjs.map +1 -0
  16. package/dist/chunk-ILN7DKKL.js +3 -0
  17. package/dist/chunk-ILN7DKKL.js.map +1 -0
  18. package/dist/chunk-OB6HH25Z.mjs +9 -0
  19. package/dist/chunk-OB6HH25Z.mjs.map +1 -0
  20. package/dist/chunk-YGU4ZMIH.mjs +14 -0
  21. package/dist/chunk-YGU4ZMIH.mjs.map +1 -0
  22. package/dist/growthbook-3K6VUME4.mjs +3 -0
  23. package/dist/growthbook-3K6VUME4.mjs.map +1 -0
  24. package/dist/index.d.mts +9 -5
  25. package/dist/index.d.ts +9 -5
  26. package/dist/index.js +2 -3
  27. package/dist/index.js.map +1 -1
  28. package/dist/index.mjs +2 -3
  29. package/dist/index.mjs.map +1 -1
  30. package/dist/metafile-cjs.json +1 -1
  31. package/dist/metafile-esm.json +1 -1
  32. package/dist/metafile-iife.json +1 -1
  33. package/dist/posthog-ANAV4RFJ.mjs +6 -0
  34. package/dist/posthog-ANAV4RFJ.mjs.map +1 -0
  35. package/dist/{posthog-lAeI7PhD.d.mts → posthog-Ds4g1sJf.d.mts} +21 -6
  36. package/dist/{posthog-DV6iayrn.d.ts → posthog-DvDj4azD.d.ts} +21 -6
  37. package/dist/providers/growthbook/index.d.mts +5 -3
  38. package/dist/providers/growthbook/index.d.ts +5 -3
  39. package/dist/providers/growthbook/index.js +2 -2
  40. package/dist/providers/growthbook/index.js.map +1 -1
  41. package/dist/providers/growthbook/index.mjs +2 -2
  42. package/dist/providers/growthbook/index.mjs.map +1 -1
  43. package/dist/providers/posthog/index.d.mts +1 -1
  44. package/dist/providers/posthog/index.d.ts +1 -1
  45. package/dist/providers/posthog/index.js +2 -2
  46. package/dist/providers/posthog/index.js.map +1 -1
  47. package/dist/providers/posthog/index.mjs +2 -2
  48. package/dist/providers/posthog/index.mjs.map +1 -1
  49. package/dist/providers/rudderstack/index.d.mts +5 -2
  50. package/dist/providers/rudderstack/index.d.ts +5 -2
  51. package/dist/providers/rudderstack/index.js +1 -1
  52. package/dist/providers/rudderstack/index.mjs +1 -1
  53. package/dist/utils/analytics-cache/index.d.mts +14 -5
  54. package/dist/utils/analytics-cache/index.d.ts +14 -5
  55. package/dist/utils/analytics-cache/index.js +1 -1
  56. package/dist/utils/analytics-cache/index.mjs +1 -1
  57. package/package.json +1 -1
  58. package/dist/chunk-3LFZFQL4.mjs +0 -3
  59. package/dist/chunk-3LFZFQL4.mjs.map +0 -1
  60. package/dist/chunk-CAKVOFLO.js +0 -3
  61. package/dist/chunk-CAKVOFLO.js.map +0 -1
  62. package/dist/chunk-DNCZM4KN.mjs +0 -4
  63. package/dist/chunk-DNCZM4KN.mjs.map +0 -1
  64. package/dist/chunk-EMF3RT6E.mjs +0 -14
  65. package/dist/chunk-EMF3RT6E.mjs.map +0 -1
  66. package/dist/chunk-HQX3Z7PF.mjs +0 -3
  67. package/dist/chunk-HQX3Z7PF.mjs.map +0 -1
  68. package/dist/chunk-LKLVBL24.js +0 -3
  69. package/dist/chunk-LKLVBL24.js.map +0 -1
  70. package/dist/chunk-NOEKD4DT.js +0 -4
  71. package/dist/chunk-NOEKD4DT.js.map +0 -1
  72. package/dist/chunk-UDVSKE3Y.mjs +0 -3
  73. package/dist/chunk-UDVSKE3Y.mjs.map +0 -1
  74. package/dist/growthbook-NJGOOJH4.mjs +0 -3
  75. package/dist/growthbook-NJGOOJH4.mjs.map +0 -1
  76. package/dist/posthog-ZJSIYY5Q.mjs +0 -6
  77. package/dist/posthog-ZJSIYY5Q.mjs.map +0 -1
@@ -17,6 +17,7 @@ type TPosthogConfig = Partial<Omit<PostHogConfig, 'session_recording'>> & {
17
17
  session_recording?: Partial<TExtendedSessionRecordingOptions>;
18
18
  };
19
19
  type TPosthogIdentifyTraits = {
20
+ email?: string;
20
21
  language?: string;
21
22
  country_of_residence?: string;
22
23
  [key: string]: any;
@@ -45,7 +46,8 @@ type TPosthogOptions = {
45
46
  * Features:
46
47
  * - Dynamically loads PostHog SDK on demand
47
48
  * - Domain allowlisting for security
48
- * - Automatic user identification and aliasing
49
+ * - Automatic user identification with client_id enforcement
50
+ * - client_id backfill for previously identified users via backfillPersonProperties
49
51
  * - Custom event tracking with property sanitization
50
52
  * - Built-in caching and retry mechanisms (handled by posthog-js library)
51
53
  *
@@ -57,31 +59,44 @@ declare class Posthog {
57
59
  has_identified: boolean;
58
60
  private static _instance;
59
61
  private options;
60
- constructor(options: TPosthogOptions);
62
+ private debug;
63
+ private log;
64
+ constructor(options: TPosthogOptions, debug?: boolean);
61
65
  /**
62
66
  * Get or create the singleton instance of Posthog
63
67
  * @param options - PostHog configuration options including API key
68
+ * @param debug - Enable debug logging
64
69
  * @returns The Posthog singleton instance
65
70
  */
66
- static getPosthogInstance: (options: TPosthogOptions) => Posthog;
71
+ static getPosthogInstance: (options: TPosthogOptions, debug?: boolean) => Posthog;
67
72
  /**
68
73
  * Initialize PostHog with configuration
69
74
  * Configures PostHog instance with provided options
70
75
  */
71
76
  init: () => void;
72
77
  /**
73
- * Identify a user with PostHog
74
- * Creates an alias between anonymous ID and user ID, then identifies with traits
78
+ * Identify a user with PostHog.
79
+ * Skipped if the user is already identified use backfillPersonProperties to backfill
80
+ * client_id for users identified in previous sessions.
75
81
  *
76
82
  * @param user_id - The user ID to identify
77
83
  * @param traits - User properties (language, country_of_residence, etc.)
78
84
  */
79
- identifyEvent: (user_id: string, traits?: TPosthogIdentifyTraits) => void;
85
+ identifyEvent: (user_id: string, traits: TPosthogIdentifyTraits) => void;
80
86
  /**
81
87
  * Reset PostHog state
82
88
  * Clears user identification and resets the instance
83
89
  */
84
90
  reset: () => void;
91
+ /**
92
+ * Ensure client_id is set in PostHog stored person properties.
93
+ * Call this when the user ID is available and PostHog is loaded.
94
+ * No-op if client_id is already present.
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
98
+ */
99
+ backfillPersonProperties: (user_id: string, email?: string) => void;
85
100
  /**
86
101
  * Capture a custom event with properties
87
102
  * Properties are pre-flattened and cleaned by analytics.ts before being passed here
@@ -17,6 +17,7 @@ type TPosthogConfig = Partial<Omit<PostHogConfig, 'session_recording'>> & {
17
17
  session_recording?: Partial<TExtendedSessionRecordingOptions>;
18
18
  };
19
19
  type TPosthogIdentifyTraits = {
20
+ email?: string;
20
21
  language?: string;
21
22
  country_of_residence?: string;
22
23
  [key: string]: any;
@@ -45,7 +46,8 @@ type TPosthogOptions = {
45
46
  * Features:
46
47
  * - Dynamically loads PostHog SDK on demand
47
48
  * - Domain allowlisting for security
48
- * - Automatic user identification and aliasing
49
+ * - Automatic user identification with client_id enforcement
50
+ * - client_id backfill for previously identified users via backfillPersonProperties
49
51
  * - Custom event tracking with property sanitization
50
52
  * - Built-in caching and retry mechanisms (handled by posthog-js library)
51
53
  *
@@ -57,31 +59,44 @@ declare class Posthog {
57
59
  has_identified: boolean;
58
60
  private static _instance;
59
61
  private options;
60
- constructor(options: TPosthogOptions);
62
+ private debug;
63
+ private log;
64
+ constructor(options: TPosthogOptions, debug?: boolean);
61
65
  /**
62
66
  * Get or create the singleton instance of Posthog
63
67
  * @param options - PostHog configuration options including API key
68
+ * @param debug - Enable debug logging
64
69
  * @returns The Posthog singleton instance
65
70
  */
66
- static getPosthogInstance: (options: TPosthogOptions) => Posthog;
71
+ static getPosthogInstance: (options: TPosthogOptions, debug?: boolean) => Posthog;
67
72
  /**
68
73
  * Initialize PostHog with configuration
69
74
  * Configures PostHog instance with provided options
70
75
  */
71
76
  init: () => void;
72
77
  /**
73
- * Identify a user with PostHog
74
- * Creates an alias between anonymous ID and user ID, then identifies with traits
78
+ * Identify a user with PostHog.
79
+ * Skipped if the user is already identified use backfillPersonProperties to backfill
80
+ * client_id for users identified in previous sessions.
75
81
  *
76
82
  * @param user_id - The user ID to identify
77
83
  * @param traits - User properties (language, country_of_residence, etc.)
78
84
  */
79
- identifyEvent: (user_id: string, traits?: TPosthogIdentifyTraits) => void;
85
+ identifyEvent: (user_id: string, traits: TPosthogIdentifyTraits) => void;
80
86
  /**
81
87
  * Reset PostHog state
82
88
  * Clears user identification and resets the instance
83
89
  */
84
90
  reset: () => void;
91
+ /**
92
+ * Ensure client_id is set in PostHog stored person properties.
93
+ * Call this when the user ID is available and PostHog is loaded.
94
+ * No-op if client_id is already present.
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
98
+ */
99
+ backfillPersonProperties: (user_id: string, email?: string) => void;
85
100
  /**
86
101
  * Capture a custom event with properties
87
102
  * Properties are pre-flattened and cleaned by analytics.ts before being passed here
@@ -52,8 +52,10 @@ declare class Growthbook {
52
52
  private static _instance;
53
53
  isLoaded: boolean;
54
54
  status: void | InitResponse;
55
- constructor(clientKey: string, decryptionKey: string, growthbookOptions?: TGrowthbookOptions);
56
- static getGrowthBookInstance: (clientKey: string, decryptionKey?: string, growthbookOptions?: TGrowthbookOptions) => Growthbook;
55
+ private debug;
56
+ private log;
57
+ constructor(clientKey: string, decryptionKey: string, growthbookOptions?: TGrowthbookOptions, debug?: boolean);
58
+ static getGrowthBookInstance: (clientKey: string, decryptionKey?: string, growthbookOptions?: TGrowthbookOptions, debug?: boolean) => Growthbook;
57
59
  reapplyExperiment(url?: string): void;
58
60
  private waitForIsLoaded;
59
61
  setAttributes: ({ id, country, user_language, device_language, device_type, utm_source, utm_medium, utm_campaign, is_authorised, url, domain, utm_content, residence_country, loggedIn, network_type, network_downlink, user_id, anonymous_id, account_mode, }: TGrowthbookAttributes) => void;
@@ -63,7 +65,7 @@ declare class Growthbook {
63
65
  status: void | InitResponse;
64
66
  }>;
65
67
  getFeatureState: (id: string) => _growthbook_growthbook.FeatureResult<string | boolean | [] | Record<string, boolean> | null>;
66
- setUrl: (href: string) => Promise<void>;
68
+ setUrl: (href: string) => void;
67
69
  isOn: (key: string) => boolean;
68
70
  init: () => Promise<void>;
69
71
  destroy: () => void;
@@ -52,8 +52,10 @@ declare class Growthbook {
52
52
  private static _instance;
53
53
  isLoaded: boolean;
54
54
  status: void | InitResponse;
55
- constructor(clientKey: string, decryptionKey: string, growthbookOptions?: TGrowthbookOptions);
56
- static getGrowthBookInstance: (clientKey: string, decryptionKey?: string, growthbookOptions?: TGrowthbookOptions) => Growthbook;
55
+ private debug;
56
+ private log;
57
+ constructor(clientKey: string, decryptionKey: string, growthbookOptions?: TGrowthbookOptions, debug?: boolean);
58
+ static getGrowthBookInstance: (clientKey: string, decryptionKey?: string, growthbookOptions?: TGrowthbookOptions, debug?: boolean) => Growthbook;
57
59
  reapplyExperiment(url?: string): void;
58
60
  private waitForIsLoaded;
59
61
  setAttributes: ({ id, country, user_language, device_language, device_type, utm_source, utm_medium, utm_campaign, is_authorised, url, domain, utm_content, residence_country, loggedIn, network_type, network_downlink, user_id, anonymous_id, account_mode, }: TGrowthbookAttributes) => void;
@@ -63,7 +65,7 @@ declare class Growthbook {
63
65
  status: void | InitResponse;
64
66
  }>;
65
67
  getFeatureState: (id: string) => _growthbook_growthbook.FeatureResult<string | boolean | [] | Record<string, boolean> | null>;
66
- setUrl: (href: string) => Promise<void>;
68
+ setUrl: (href: string) => void;
67
69
  isOn: (key: string) => boolean;
68
70
  init: () => Promise<void>;
69
71
  destroy: () => void;
@@ -1,3 +1,3 @@
1
- 'use strict';var chunkNOEKD4DT_js=require('../../chunk-NOEKD4DT.js'),growthbook=require('@growthbook/growthbook'),analyticsJs=require('@rudderstack/analytics-js');/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var o=class o{constructor(t,e,i={}){this.analytics=new analyticsJs.RudderAnalytics;this.isLoaded=false;this.status=void 0;this.setAttributes=({id:t,country:e,user_language:i,device_language:s,device_type:n,utm_source:r,utm_medium:a,utm_campaign:d,is_authorised:w,url:h,domain:u,utm_content:f,residence_country:c,loggedIn:k,network_type:l,network_downlink:b,user_id:p,anonymous_id:G,account_mode:g})=>{let B=this.GrowthBook.getAttributes();this.GrowthBook.setAttributes({...B,id:t,...p!==void 0&&{user_id:p},...G!==void 0&&{anonymous_id:G},...e!==void 0&&{country:e},...c!==void 0&&{residence_country:c},...i!==void 0&&{user_language:i},...s!==void 0&&{device_language:s},...n!==void 0&&{device_type:n},...r!==void 0&&{utm_source:r},...a!==void 0&&{utm_medium:a},...d!==void 0&&{utm_campaign:d},...w!==void 0&&{is_authorised:w},...h!==void 0&&{url:h},...u!==void 0&&{domain:u},...f!==void 0&&{utm_content:f},...k!==void 0&&{loggedIn:k},...l!==void 0&&{network_type:l},...b!==void 0&&{network_downlink:b},...g!==void 0&&{account_mode:g}});};this.getFeatureValue=(t,e)=>this.GrowthBook.getFeatureValue(t,e);this.getStatus=async()=>(await this.waitForIsLoaded(),{isLoaded:this.isLoaded,status:this.status});this.getFeatureState=t=>this.GrowthBook.evalFeature(t);this.setUrl=t=>this.GrowthBook.setURL(t);this.isOn=t=>this.GrowthBook.isOn(t);this.init=async()=>{let t=await this.GrowthBook.init({timeout:2e3,streaming:true}).catch(()=>{});this.status=t,this.isLoaded=true;};this.destroy=()=>{this.GrowthBook.destroy(),this.isLoaded=false,this.status=void 0;};let s=typeof window<"u"?window.location.hostname.includes("localhost"):false;this.GrowthBook=new growthbook.GrowthBook({apiHost:chunkNOEKD4DT_js.b,clientKey:t,decryptionKey:e,antiFlicker:false,navigateDelay:0,antiFlickerTimeout:3500,subscribeToChanges:true,enableDevMode:s,trackingCallback:(n,r)=>{typeof window<"u"&&window.dataLayer&&window.dataLayer.push({event:"experiment_viewed",event_category:"experiment",rudder_anonymous_id:this.analytics.getAnonymousId(),experiment_id:n.key,variation_id:r.variationId}),this.analytics.track("experiment_viewed",{experimentId:n.key,variationId:r.variationId});},...i}),this.init();}reapplyExperiment(t){let e=t??(typeof window<"u"?window.location.href:"");this.GrowthBook.setURL(e);}waitForIsLoaded(t=1e4){return new Promise((e,i)=>{let s=Date.now(),n=setInterval(()=>{this.isLoaded?(clearInterval(n),e()):Date.now()-s>=t&&(clearInterval(n),i(new Error("GrowthBook initialization timeout")));},100);})}};o.getGrowthBookInstance=(t,e,i)=>o._instance?(typeof window<"u"&&console.warn&&console.warn("GrowthBook instance already exists. Ignoring new initialization parameters."),o._instance):(o._instance=new o(t,e??"",i),o._instance),o.resetInstance=()=>{o._instance&&(o._instance.destroy(),o._instance=void 0);};var v=o;exports.Growthbook=v;//# sourceMappingURL=index.js.map
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
3
3
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/providers/growthbook.ts"],"names":["_Growthbook","clientKey","decryptionKey","growthbookOptions","RudderAnalytics","id","country","user_language","device_language","device_type","utm_source","utm_medium","utm_campaign","is_authorised","url","domain","utm_content","residence_country","loggedIn","network_type","network_downlink","user_id","anonymous_id","account_mode","currentAttributes","key","defaultValue","href","status","isLocalhost","GrowthBook","growthbookApi","experiment","result","currentUrl","timeout","resolve","reject","startTime","checkInterval","Growthbook"],"mappings":";AAUO,IAAMA,CAAAA,CAAN,MAAMA,CAAW,CAQpB,WAAA,CAAYC,CAAAA,CAAmBC,CAAAA,CAAuBC,CAAAA,CAAwC,EAAC,CAAG,CAPlG,IAAA,CAAA,SAAA,CAAY,IAAIC,2BAAAA,CAGhB,IAAA,CAAA,QAAA,CAAW,KAAA,CACX,IAAA,CAAA,MAAA,CAA8B,MAAA,CA2E9B,IAAA,CAAA,aAAA,CAAgB,CAAC,CACb,GAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,WAA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,SAAA,CAAU,OAAA,EAAQ,CAC7BA,CAAAA,CAAW,SAAA,CAAY,MAAA,EAE/B,CAAA,CAlKG,IAAMwC,CAAAA,CAANxC","file":"index.js","sourcesContent":["import { GrowthBook, InitResponse } from '@growthbook/growthbook'\nimport { RudderAnalytics } from '@rudderstack/analytics-js'\nimport {\n TGrowthbookAttributes,\n TGrowthbookOptions,\n GrowthbookConfigs,\n TGrowthbookCoreAttributes,\n} from './growthbookTypes'\nimport { growthbookApi } from '../utils/urls'\n\nexport class Growthbook {\n analytics = new RudderAnalytics()\n GrowthBook: GrowthBook<GrowthbookConfigs>\n private static _instance: Growthbook\n isLoaded = false\n status: void | InitResponse = undefined\n\n // we have to pass settings due the specific framework implementation\n constructor(clientKey: string, decryptionKey: string, growthbookOptions: TGrowthbookOptions = {}) {\n const isLocalhost = typeof window !== 'undefined' ? window.location.hostname.includes('localhost') : false\n\n this.GrowthBook = new GrowthBook<GrowthbookConfigs>({\n apiHost: growthbookApi,\n clientKey,\n decryptionKey,\n antiFlicker: false,\n navigateDelay: 0,\n antiFlickerTimeout: 3500,\n subscribeToChanges: true,\n enableDevMode: isLocalhost,\n trackingCallback: (experiment, result) => {\n if (typeof window !== 'undefined' && window.dataLayer) {\n window.dataLayer.push({\n event: 'experiment_viewed',\n event_category: 'experiment',\n rudder_anonymous_id: this.analytics.getAnonymousId(),\n experiment_id: experiment.key,\n variation_id: result.variationId,\n })\n }\n this.analytics.track('experiment_viewed', {\n experimentId: experiment.key,\n variationId: result.variationId,\n })\n },\n ...growthbookOptions,\n })\n this.init()\n }\n\n // for make instance by singleton\n public static getGrowthBookInstance = (\n clientKey: string,\n decryptionKey?: string,\n growthbookOptions?: TGrowthbookOptions\n ) => {\n if (!Growthbook._instance) {\n Growthbook._instance = new Growthbook(clientKey, decryptionKey ?? '', growthbookOptions)\n return Growthbook._instance\n }\n\n // Warn if trying to reinitialize with different parameters\n if (typeof window !== 'undefined' && console.warn) {\n console.warn('GrowthBook instance already exists. Ignoring new initialization parameters.')\n }\n\n return Growthbook._instance\n }\n\n reapplyExperiment(url?: string) {\n const currentUrl = url ?? (typeof window !== 'undefined' ? window.location.href : '')\n this.GrowthBook.setURL(currentUrl)\n }\n\n // Utility function to wait for isLoaded to become true\n private waitForIsLoaded(timeout = 10000): Promise<void> {\n return new Promise((resolve, reject) => {\n const startTime = Date.now()\n const checkInterval = setInterval(() => {\n if (this.isLoaded) {\n clearInterval(checkInterval)\n resolve()\n } else if (Date.now() - startTime >= timeout) {\n clearInterval(checkInterval)\n reject(new Error('GrowthBook initialization timeout'))\n }\n }, 100)\n })\n }\n\n setAttributes = ({\n id,\n country,\n user_language,\n device_language,\n device_type,\n utm_source,\n utm_medium,\n utm_campaign,\n is_authorised,\n url,\n domain,\n utm_content,\n residence_country,\n loggedIn,\n network_type,\n network_downlink,\n user_id,\n anonymous_id,\n account_mode,\n }: TGrowthbookAttributes) => {\n const currentAttributes = this.GrowthBook.getAttributes()\n this.GrowthBook.setAttributes({\n ...currentAttributes,\n id,\n ...(user_id !== undefined && { user_id }),\n ...(anonymous_id !== undefined && { anonymous_id }),\n ...(country !== undefined && { country }),\n ...(residence_country !== undefined && { residence_country }),\n ...(user_language !== undefined && { user_language }),\n ...(device_language !== undefined && { device_language }),\n ...(device_type !== undefined && { device_type }),\n ...(utm_source !== undefined && { utm_source }),\n ...(utm_medium !== undefined && { utm_medium }),\n ...(utm_campaign !== undefined && { utm_campaign }),\n ...(is_authorised !== undefined && { is_authorised }),\n ...(url !== undefined && { url }),\n ...(domain !== undefined && { domain }),\n ...(utm_content !== undefined && { utm_content }),\n ...(loggedIn !== undefined && { loggedIn }),\n ...(network_type !== undefined && { network_type }),\n ...(network_downlink !== undefined && { network_downlink }),\n ...(account_mode !== undefined && { account_mode }),\n })\n }\n getFeatureValue = <K extends keyof GrowthbookConfigs, V extends GrowthbookConfigs[K]>(key: K, defaultValue: V) => {\n return this.GrowthBook.getFeatureValue(key as string, defaultValue)\n }\n getStatus = async (): Promise<{ isLoaded: boolean; status: void | InitResponse }> => {\n await this.waitForIsLoaded()\n\n return {\n isLoaded: this.isLoaded,\n status: this.status,\n }\n }\n getFeatureState = (id: string) => this.GrowthBook.evalFeature(id)\n setUrl = (href: string) => this.GrowthBook.setURL(href)\n isOn = (key: string) => this.GrowthBook.isOn(key)\n\n init = async () => {\n const status = await this.GrowthBook.init({ timeout: 2000, streaming: true }).catch(() => {\n // Silently handle initialization errors\n })\n\n this.status = status\n this.isLoaded = true\n }\n\n // Destroy the GrowthBook instance and reset singleton\n destroy = () => {\n this.GrowthBook.destroy()\n this.isLoaded = false\n this.status = undefined\n }\n\n // Reset the singleton instance (useful for testing)\n public static resetInstance = () => {\n if (Growthbook._instance) {\n Growthbook._instance.destroy()\n Growthbook._instance = undefined as any\n }\n }\n}\n\nexport type { GrowthbookConfigs, TGrowthbookAttributes, TGrowthbookOptions, TGrowthbookCoreAttributes }\n"]}
1
+ {"version":3,"sources":["../../../src/providers/growthbook.ts"],"names":["_Growthbook","clientKey","decryptionKey","growthbookOptions","debug","RudderAnalytics","createLogger","id","country","user_language","device_language","device_type","utm_source","utm_medium","utm_campaign","is_authorised","url","domain","utm_content","residence_country","loggedIn","network_type","network_downlink","user_id","anonymous_id","account_mode","newAttributes","key","defaultValue","value","state","href","result","status","isLocalhost","GrowthBook","growthbookApi","experiment","currentUrl","timeout","resolve","reject","startTime","checkInterval","Growthbook"],"mappings":";AAWO,IAAMA,CAAAA,CAAN,MAAMA,CAAW,CAUpB,WAAA,CAAYC,EAAmBC,CAAAA,CAAuBC,CAAAA,CAAwC,EAAC,CAAGC,CAAAA,CAAQ,KAAA,CAAO,CATjH,IAAA,CAAA,SAAA,CAAY,IAAIC,2BAAAA,CAGhB,IAAA,CAAA,QAAA,CAAW,KAAA,CACX,IAAA,CAAA,MAAA,CAA8B,OAC9B,IAAA,CAAQ,KAAA,CAAQ,KAAA,CAChB,IAAA,CAAQ,IAAMC,kBAAAA,CAAa,cAAA,CAAgB,IAAM,IAAA,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IAAI,OAAA,CAAQ,CAACC,CAAAA,CAASC,IAAW,CACpC,IAAMC,CAAAA,CAAY,IAAA,CAAK,KAAI,CACrBC,CAAAA,CAAgB,WAAA,CAAY,IAAM,CAChC,IAAA,CAAK,QAAA,EACL,aAAA,CAAcA,CAAa,CAAA,CAC3BH,CAAAA,EAAQ,EACD,IAAA,CAAK,KAAI,CAAIE,CAAAA,EAAaH,CAAAA,GACjC,aAAA,CAAcI,CAAa,CAAA,CAC3BF,CAAAA,CAAO,IAAI,KAAA,CAAM,mCAAmC,CAAC,CAAA,EAE7D,CAAA,CAAG,GAAG,EACV,CAAC,CACL,CAsGJ,EA5LazC,CAAAA,CAgDK,qBAAA,CAAwB,CAClCC,CAAAA,CACAC,EACAC,CAAAA,CACAC,CAAAA,CAAQ,KAAA,GAEHJ,CAAAA,CAAW,WAMZ,OAAO,MAAA,CAAW,GAAA,EAAe,OAAA,CAAQ,IAAA,EACzC,OAAA,CAAQ,IAAA,CAAK,6EAA6E,EAGvFA,CAAAA,CAAW,SAAA,GATdA,CAAAA,CAAW,SAAA,CAAY,IAAIA,CAAAA,CAAWC,CAAAA,CAAWC,CAAAA,EAAiB,EAAA,CAAIC,EAAmBC,CAAK,CAAA,CACvFJ,CAAAA,CAAW,SAAA,CAAA,CAxDjBA,CAAAA,CAsLK,aAAA,CAAgB,IAAM,CAC5BA,EAAW,SAAA,GACXA,CAAAA,CAAW,SAAA,CAAU,OAAA,GACrBA,CAAAA,CAAW,SAAA,CAAY,MAAA,EAE/B,CAAA,KA3LS4C,CAAAA,CAAN5C","file":"index.js","sourcesContent":["import { GrowthBook, InitResponse } from '@growthbook/growthbook'\nimport { RudderAnalytics } from '@rudderstack/analytics-js'\nimport {\n TGrowthbookAttributes,\n TGrowthbookOptions,\n GrowthbookConfigs,\n TGrowthbookCoreAttributes,\n} from './growthbookTypes'\nimport { growthbookApi } from '../utils/urls'\nimport { createLogger } from '../utils/helpers'\n\nexport class Growthbook {\n analytics = new RudderAnalytics()\n GrowthBook: GrowthBook<GrowthbookConfigs>\n private static _instance: Growthbook\n isLoaded = false\n status: void | InitResponse = undefined\n private debug = false\n private log = createLogger('[GrowthBook]', () => this.debug)\n\n // we have to pass settings due the specific framework implementation\n constructor(clientKey: string, decryptionKey: string, growthbookOptions: TGrowthbookOptions = {}, debug = false) {\n this.debug = debug\n const isLocalhost = typeof window !== 'undefined' ? window.location.hostname.includes('localhost') : false\n\n this.GrowthBook = new GrowthBook<GrowthbookConfigs>({\n apiHost: growthbookApi,\n clientKey,\n decryptionKey,\n antiFlicker: false,\n navigateDelay: 0,\n antiFlickerTimeout: 3500,\n subscribeToChanges: true,\n enableDevMode: isLocalhost,\n trackingCallback: (experiment, result) => {\n this.log('trackingCallback | experiment viewed', {\n experiment_id: experiment.key,\n variation_id: result.variationId,\n })\n if (typeof window !== 'undefined' && window.dataLayer) {\n window.dataLayer.push({\n event: 'experiment_viewed',\n event_category: 'experiment',\n rudder_anonymous_id: this.analytics.getAnonymousId(),\n experiment_id: experiment.key,\n variation_id: result.variationId,\n })\n }\n this.analytics.track('experiment_viewed', {\n experimentId: experiment.key,\n variationId: result.variationId,\n })\n },\n ...growthbookOptions,\n })\n this.init()\n }\n\n // for make instance by singleton\n public static getGrowthBookInstance = (\n clientKey: string,\n decryptionKey?: string,\n growthbookOptions?: TGrowthbookOptions,\n debug = false\n ) => {\n if (!Growthbook._instance) {\n Growthbook._instance = new Growthbook(clientKey, decryptionKey ?? '', growthbookOptions, debug)\n return Growthbook._instance\n }\n\n // Warn if trying to reinitialize with different parameters\n if (typeof window !== 'undefined' && console.warn) {\n console.warn('GrowthBook instance already exists. Ignoring new initialization parameters.')\n }\n\n return Growthbook._instance\n }\n\n reapplyExperiment(url?: string) {\n const currentUrl = url ?? (typeof window !== 'undefined' ? window.location.href : '')\n this.GrowthBook.setURL(currentUrl)\n }\n\n // Utility function to wait for isLoaded to become true\n private waitForIsLoaded(timeout = 10000): Promise<void> {\n return new Promise((resolve, reject) => {\n const startTime = Date.now()\n const checkInterval = setInterval(() => {\n if (this.isLoaded) {\n clearInterval(checkInterval)\n resolve()\n } else if (Date.now() - startTime >= timeout) {\n clearInterval(checkInterval)\n reject(new Error('GrowthBook initialization timeout'))\n }\n }, 100)\n })\n }\n\n setAttributes = ({\n id,\n country,\n user_language,\n device_language,\n device_type,\n utm_source,\n utm_medium,\n utm_campaign,\n is_authorised,\n url,\n domain,\n utm_content,\n residence_country,\n loggedIn,\n network_type,\n network_downlink,\n user_id,\n anonymous_id,\n account_mode,\n }: TGrowthbookAttributes) => {\n const currentAttributes = this.GrowthBook.getAttributes()\n const newAttributes = {\n ...currentAttributes,\n id,\n ...(user_id !== undefined && { user_id }),\n ...(anonymous_id !== undefined && { anonymous_id }),\n ...(country !== undefined && { country }),\n ...(residence_country !== undefined && { residence_country }),\n ...(user_language !== undefined && { user_language }),\n ...(device_language !== undefined && { device_language }),\n ...(device_type !== undefined && { device_type }),\n ...(utm_source !== undefined && { utm_source }),\n ...(utm_medium !== undefined && { utm_medium }),\n ...(utm_campaign !== undefined && { utm_campaign }),\n ...(is_authorised !== undefined && { is_authorised }),\n ...(url !== undefined && { url }),\n ...(domain !== undefined && { domain }),\n ...(utm_content !== undefined && { utm_content }),\n ...(loggedIn !== undefined && { loggedIn }),\n ...(network_type !== undefined && { network_type }),\n ...(network_downlink !== undefined && { network_downlink }),\n ...(account_mode !== undefined && { account_mode }),\n }\n this.log('setAttributes | updating GrowthBook attributes', newAttributes)\n this.GrowthBook.setAttributes(newAttributes)\n }\n getFeatureValue = <K extends keyof GrowthbookConfigs, V extends GrowthbookConfigs[K]>(key: K, defaultValue: V) => {\n const value = this.GrowthBook.getFeatureValue(key as string, defaultValue)\n this.log('getFeatureValue', { key, value, defaultValue })\n return value\n }\n getStatus = async (): Promise<{ isLoaded: boolean; status: void | InitResponse }> => {\n await this.waitForIsLoaded()\n\n return {\n isLoaded: this.isLoaded,\n status: this.status,\n }\n }\n getFeatureState = (id: string) => {\n const state = this.GrowthBook.evalFeature(id)\n this.log('getFeatureState', { id, result: state })\n return state\n }\n setUrl = (href: string) => {\n this.log('setUrl', { href })\n this.GrowthBook.setURL(href)\n }\n isOn = (key: string) => {\n const result = this.GrowthBook.isOn(key)\n this.log('isOn', { key, result })\n return result\n }\n\n init = async () => {\n this.log('init | initializing GrowthBook SDK')\n const status = await this.GrowthBook.init({ timeout: 2000, streaming: true }).catch(() => {\n // Silently handle initialization errors\n })\n\n this.status = status\n this.isLoaded = true\n this.log('init | GrowthBook SDK loaded', { status })\n }\n\n // Destroy the GrowthBook instance and reset singleton\n destroy = () => {\n this.GrowthBook.destroy()\n this.isLoaded = false\n this.status = undefined\n }\n\n // Reset the singleton instance (useful for testing)\n public static resetInstance = () => {\n if (Growthbook._instance) {\n Growthbook._instance.destroy()\n Growthbook._instance = undefined as any\n }\n }\n}\n\nexport type { GrowthbookConfigs, TGrowthbookAttributes, TGrowthbookOptions, TGrowthbookCoreAttributes }\n"]}
@@ -1,3 +1,3 @@
1
- import {b}from'../../chunk-DNCZM4KN.mjs';import {GrowthBook}from'@growthbook/growthbook';import {RudderAnalytics}from'@rudderstack/analytics-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var o=class o{constructor(t,e,i={}){this.analytics=new RudderAnalytics;this.isLoaded=false;this.status=void 0;this.setAttributes=({id:t,country:e,user_language:i,device_language:s,device_type:n,utm_source:r,utm_medium:a,utm_campaign:d,is_authorised:w,url:h,domain:u,utm_content:f,residence_country:c,loggedIn:k,network_type:l,network_downlink:b,user_id:p,anonymous_id:G,account_mode:g})=>{let B=this.GrowthBook.getAttributes();this.GrowthBook.setAttributes({...B,id:t,...p!==void 0&&{user_id:p},...G!==void 0&&{anonymous_id:G},...e!==void 0&&{country:e},...c!==void 0&&{residence_country:c},...i!==void 0&&{user_language:i},...s!==void 0&&{device_language:s},...n!==void 0&&{device_type:n},...r!==void 0&&{utm_source:r},...a!==void 0&&{utm_medium:a},...d!==void 0&&{utm_campaign:d},...w!==void 0&&{is_authorised:w},...h!==void 0&&{url:h},...u!==void 0&&{domain:u},...f!==void 0&&{utm_content:f},...k!==void 0&&{loggedIn:k},...l!==void 0&&{network_type:l},...b!==void 0&&{network_downlink:b},...g!==void 0&&{account_mode:g}});};this.getFeatureValue=(t,e)=>this.GrowthBook.getFeatureValue(t,e);this.getStatus=async()=>(await this.waitForIsLoaded(),{isLoaded:this.isLoaded,status:this.status});this.getFeatureState=t=>this.GrowthBook.evalFeature(t);this.setUrl=t=>this.GrowthBook.setURL(t);this.isOn=t=>this.GrowthBook.isOn(t);this.init=async()=>{let t=await this.GrowthBook.init({timeout:2e3,streaming:true}).catch(()=>{});this.status=t,this.isLoaded=true;};this.destroy=()=>{this.GrowthBook.destroy(),this.isLoaded=false,this.status=void 0;};let s=typeof window<"u"?window.location.hostname.includes("localhost"):false;this.GrowthBook=new GrowthBook({apiHost:b,clientKey:t,decryptionKey:e,antiFlicker:false,navigateDelay:0,antiFlickerTimeout:3500,subscribeToChanges:true,enableDevMode:s,trackingCallback:(n,r)=>{typeof window<"u"&&window.dataLayer&&window.dataLayer.push({event:"experiment_viewed",event_category:"experiment",rudder_anonymous_id:this.analytics.getAnonymousId(),experiment_id:n.key,variation_id:r.variationId}),this.analytics.track("experiment_viewed",{experimentId:n.key,variationId:r.variationId});},...i}),this.init();}reapplyExperiment(t){let e=t??(typeof window<"u"?window.location.href:"");this.GrowthBook.setURL(e);}waitForIsLoaded(t=1e4){return new Promise((e,i)=>{let s=Date.now(),n=setInterval(()=>{this.isLoaded?(clearInterval(n),e()):Date.now()-s>=t&&(clearInterval(n),i(new Error("GrowthBook initialization timeout")));},100);})}};o.getGrowthBookInstance=(t,e,i)=>o._instance?(typeof window<"u"&&console.warn&&console.warn("GrowthBook instance already exists. Ignoring new initialization parameters."),o._instance):(o._instance=new o(t,e??"",i),o._instance),o.resetInstance=()=>{o._instance&&(o._instance.destroy(),o._instance=void 0);};var v=o;export{v as Growthbook};//# sourceMappingURL=index.mjs.map
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 */
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 +1 @@
1
- {"version":3,"sources":["../../../src/providers/growthbook.ts"],"names":["_Growthbook","clientKey","decryptionKey","growthbookOptions","RudderAnalytics","id","country","user_language","device_language","device_type","utm_source","utm_medium","utm_campaign","is_authorised","url","domain","utm_content","residence_country","loggedIn","network_type","network_downlink","user_id","anonymous_id","account_mode","currentAttributes","key","defaultValue","href","status","isLocalhost","GrowthBook","growthbookApi","experiment","result","currentUrl","timeout","resolve","reject","startTime","checkIn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AC,CAAAA,GAEKH,CAAAA,CAAW,SAAA,EAMZ,OAAO,MAAA,CAAW,GAAA,EAAe,OAAA,CAAQ,IAAA,EACzC,OAAA,CAAQ,IAAA,CAAK,6EAA6E,CAAA,CAGvFA,CAAAA,CAAW,SAAA,GATdA,CAAAA,CAAW,SAAA,CAAY,IAAIA,CAAAA,CAAWC,CAAAA,CAAWC,CAAAA,EAAiB,EAAA,CAAIC,CAAiB,CAAA,CAChFH,CAAAA,CAAW,SAAA,CAAA,CAhDjBA,CAAAA,CA6JK,aAAA,CAAgB,IAAM,CAC5BA,CAAAA,CAAW,SAAA,GACXA,CAAAA,CAAW,SAAA,CAAU,OAAA,EAAQ,CAC7BA,CAAAA,CAAW,SAAA,CAAY,MAAA,EAE/B,CAAA,CAlKG,IAAMwC,CAAAA,CAANxC","file":"index.mjs","sourcesContent":["import { GrowthBook, InitResponse } from '@growthbook/growthbook'\nimport { RudderAnalytics } from '@rudderstack/analytics-js'\nimport {\n TGrowthbookAttributes,\n TGrowthbookOptions,\n GrowthbookConfigs,\n TGrowthbookCoreAttributes,\n} from './growthbookTypes'\nimport { growthbookApi } from '../utils/urls'\n\nexport class Growthbook {\n analytics = new RudderAnalytics()\n GrowthBook: GrowthBook<GrowthbookConfigs>\n private static _instance: Growthbook\n isLoaded = false\n status: void | InitResponse = undefined\n\n // we have to pass settings due the specific framework implementation\n constructor(clientKey: string, decryptionKey: string, growthbookOptions: TGrowthbookOptions = {}) {\n const isLocalhost = typeof window !== 'undefined' ? window.location.hostname.includes('localhost') : false\n\n this.GrowthBook = new GrowthBook<GrowthbookConfigs>({\n apiHost: growthbookApi,\n clientKey,\n decryptionKey,\n antiFlicker: false,\n navigateDelay: 0,\n antiFlickerTimeout: 3500,\n subscribeToChanges: true,\n enableDevMode: isLocalhost,\n trackingCallback: (experiment, result) => {\n if (typeof window !== 'undefined' && window.dataLayer) {\n window.dataLayer.push({\n event: 'experiment_viewed',\n event_category: 'experiment',\n rudder_anonymous_id: this.analytics.getAnonymousId(),\n experiment_id: experiment.key,\n variation_id: result.variationId,\n })\n }\n this.analytics.track('experiment_viewed', {\n experimentId: experiment.key,\n variationId: result.variationId,\n })\n },\n ...growthbookOptions,\n })\n this.init()\n }\n\n // for make instance by singleton\n public static getGrowthBookInstance = (\n clientKey: string,\n decryptionKey?: string,\n growthbookOptions?: TGrowthbookOptions\n ) => {\n if (!Growthbook._instance) {\n Growthbook._instance = new Growthbook(clientKey, decryptionKey ?? '', growthbookOptions)\n return Growthbook._instance\n }\n\n // Warn if trying to reinitialize with different parameters\n if (typeof window !== 'undefined' && console.warn) {\n console.warn('GrowthBook instance already exists. Ignoring new initialization parameters.')\n }\n\n return Growthbook._instance\n }\n\n reapplyExperiment(url?: string) {\n const currentUrl = url ?? (typeof window !== 'undefined' ? window.location.href : '')\n this.GrowthBook.setURL(currentUrl)\n }\n\n // Utility function to wait for isLoaded to become true\n private waitForIsLoaded(timeout = 10000): Promise<void> {\n return new Promise((resolve, reject) => {\n const startTime = Date.now()\n const checkInterval = setInterval(() => {\n if (this.isLoaded) {\n clearInterval(checkInterval)\n resolve()\n } else if (Date.now() - startTime >= timeout) {\n clearInterval(checkInterval)\n reject(new Error('GrowthBook initialization timeout'))\n }\n }, 100)\n })\n }\n\n setAttributes = ({\n id,\n country,\n user_language,\n device_language,\n device_type,\n utm_source,\n utm_medium,\n utm_campaign,\n is_authorised,\n url,\n domain,\n utm_content,\n residence_country,\n loggedIn,\n network_type,\n network_downlink,\n user_id,\n anonymous_id,\n account_mode,\n }: TGrowthbookAttributes) => {\n const currentAttributes = this.GrowthBook.getAttributes()\n this.GrowthBook.setAttributes({\n ...currentAttributes,\n id,\n ...(user_id !== undefined && { user_id }),\n ...(anonymous_id !== undefined && { anonymous_id }),\n ...(country !== undefined && { country }),\n ...(residence_country !== undefined && { residence_country }),\n ...(user_language !== undefined && { user_language }),\n ...(device_language !== undefined && { device_language }),\n ...(device_type !== undefined && { device_type }),\n ...(utm_source !== undefined && { utm_source }),\n ...(utm_medium !== undefined && { utm_medium }),\n ...(utm_campaign !== undefined && { utm_campaign }),\n ...(is_authorised !== undefined && { is_authorised }),\n ...(url !== undefined && { url }),\n ...(domain !== undefined && { domain }),\n ...(utm_content !== undefined && { utm_content }),\n ...(loggedIn !== undefined && { loggedIn }),\n ...(network_type !== undefined && { network_type }),\n ...(network_downlink !== undefined && { network_downlink }),\n ...(account_mode !== undefined && { account_mode }),\n })\n }\n getFeatureValue = <K extends keyof GrowthbookConfigs, V extends GrowthbookConfigs[K]>(key: K, defaultValue: V) => {\n return this.GrowthBook.getFeatureValue(key as string, defaultValue)\n }\n getStatus = async (): Promise<{ isLoaded: boolean; status: void | InitResponse }> => {\n await this.waitForIsLoaded()\n\n return {\n isLoaded: this.isLoaded,\n status: this.status,\n }\n }\n getFeatureState = (id: string) => this.GrowthBook.evalFeature(id)\n setUrl = (href: string) => this.GrowthBook.setURL(href)\n isOn = (key: string) => this.GrowthBook.isOn(key)\n\n init = async () => {\n const status = await this.GrowthBook.init({ timeout: 2000, streaming: true }).catch(() => {\n // Silently handle initialization errors\n })\n\n this.status = status\n this.isLoaded = true\n }\n\n // Destroy the GrowthBook instance and reset singleton\n destroy = () => {\n this.GrowthBook.destroy()\n this.isLoaded = false\n this.status = undefined\n }\n\n // Reset the singleton instance (useful for testing)\n public static resetInstance = () => {\n if (Growthbook._instance) {\n Growthbook._instance.destroy()\n Growthbook._instance = undefined as any\n }\n }\n}\n\nexport type { GrowthbookConfigs, TGrowthbookAttributes, TGrowthbookOptions, TGrowthbookCoreAttributes }\n"]}
1
+ {"version":3,"sources":["../../../src/providers/growthbook.ts"],"names":["_Growthbook","clientKey","decryptionKey","growthbookOptions","debug","RudderAnalytics","createLogger","id","country","user_language","device_language","device_type","utm_source","utm_medium","utm_campaign","is_authorised","url","domain","utm_content","residence_country","loggedIn","network_type","network_downlink","user_id","anonymous_id","account_mode","newAttributes","key","defaultValue","value","state","href","result","status","isLocalhost","GrowthBook","growthbookApi","experiment","currentUrl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5BA,EAAW,SAAA,GACXA,CAAAA,CAAW,SAAA,CAAU,OAAA,GACrBA,CAAAA,CAAW,SAAA,CAAY,MAAA,EAE/B,CAAA,KA3LS4C,CAAAA,CAAN5C","file":"index.mjs","sourcesContent":["import { GrowthBook, InitResponse } from '@growthbook/growthbook'\nimport { RudderAnalytics } from '@rudderstack/analytics-js'\nimport {\n TGrowthbookAttributes,\n TGrowthbookOptions,\n GrowthbookConfigs,\n TGrowthbookCoreAttributes,\n} from './growthbookTypes'\nimport { growthbookApi } from '../utils/urls'\nimport { createLogger } from '../utils/helpers'\n\nexport class Growthbook {\n analytics = new RudderAnalytics()\n GrowthBook: GrowthBook<GrowthbookConfigs>\n private static _instance: Growthbook\n isLoaded = false\n status: void | InitResponse = undefined\n private debug = false\n private log = createLogger('[GrowthBook]', () => this.debug)\n\n // we have to pass settings due the specific framework implementation\n constructor(clientKey: string, decryptionKey: string, growthbookOptions: TGrowthbookOptions = {}, debug = false) {\n this.debug = debug\n const isLocalhost = typeof window !== 'undefined' ? window.location.hostname.includes('localhost') : false\n\n this.GrowthBook = new GrowthBook<GrowthbookConfigs>({\n apiHost: growthbookApi,\n clientKey,\n decryptionKey,\n antiFlicker: false,\n navigateDelay: 0,\n antiFlickerTimeout: 3500,\n subscribeToChanges: true,\n enableDevMode: isLocalhost,\n trackingCallback: (experiment, result) => {\n this.log('trackingCallback | experiment viewed', {\n experiment_id: experiment.key,\n variation_id: result.variationId,\n })\n if (typeof window !== 'undefined' && window.dataLayer) {\n window.dataLayer.push({\n event: 'experiment_viewed',\n event_category: 'experiment',\n rudder_anonymous_id: this.analytics.getAnonymousId(),\n experiment_id: experiment.key,\n variation_id: result.variationId,\n })\n }\n this.analytics.track('experiment_viewed', {\n experimentId: experiment.key,\n variationId: result.variationId,\n })\n },\n ...growthbookOptions,\n })\n this.init()\n }\n\n // for make instance by singleton\n public static getGrowthBookInstance = (\n clientKey: string,\n decryptionKey?: string,\n growthbookOptions?: TGrowthbookOptions,\n debug = false\n ) => {\n if (!Growthbook._instance) {\n Growthbook._instance = new Growthbook(clientKey, decryptionKey ?? '', growthbookOptions, debug)\n return Growthbook._instance\n }\n\n // Warn if trying to reinitialize with different parameters\n if (typeof window !== 'undefined' && console.warn) {\n console.warn('GrowthBook instance already exists. Ignoring new initialization parameters.')\n }\n\n return Growthbook._instance\n }\n\n reapplyExperiment(url?: string) {\n const currentUrl = url ?? (typeof window !== 'undefined' ? window.location.href : '')\n this.GrowthBook.setURL(currentUrl)\n }\n\n // Utility function to wait for isLoaded to become true\n private waitForIsLoaded(timeout = 10000): Promise<void> {\n return new Promise((resolve, reject) => {\n const startTime = Date.now()\n const checkInterval = setInterval(() => {\n if (this.isLoaded) {\n clearInterval(checkInterval)\n resolve()\n } else if (Date.now() - startTime >= timeout) {\n clearInterval(checkInterval)\n reject(new Error('GrowthBook initialization timeout'))\n }\n }, 100)\n })\n }\n\n setAttributes = ({\n id,\n country,\n user_language,\n device_language,\n device_type,\n utm_source,\n utm_medium,\n utm_campaign,\n is_authorised,\n url,\n domain,\n utm_content,\n residence_country,\n loggedIn,\n network_type,\n network_downlink,\n user_id,\n anonymous_id,\n account_mode,\n }: TGrowthbookAttributes) => {\n const currentAttributes = this.GrowthBook.getAttributes()\n const newAttributes = {\n ...currentAttributes,\n id,\n ...(user_id !== undefined && { user_id }),\n ...(anonymous_id !== undefined && { anonymous_id }),\n ...(country !== undefined && { country }),\n ...(residence_country !== undefined && { residence_country }),\n ...(user_language !== undefined && { user_language }),\n ...(device_language !== undefined && { device_language }),\n ...(device_type !== undefined && { device_type }),\n ...(utm_source !== undefined && { utm_source }),\n ...(utm_medium !== undefined && { utm_medium }),\n ...(utm_campaign !== undefined && { utm_campaign }),\n ...(is_authorised !== undefined && { is_authorised }),\n ...(url !== undefined && { url }),\n ...(domain !== undefined && { domain }),\n ...(utm_content !== undefined && { utm_content }),\n ...(loggedIn !== undefined && { loggedIn }),\n ...(network_type !== undefined && { network_type }),\n ...(network_downlink !== undefined && { network_downlink }),\n ...(account_mode !== undefined && { account_mode }),\n }\n this.log('setAttributes | updating GrowthBook attributes', newAttributes)\n this.GrowthBook.setAttributes(newAttributes)\n }\n getFeatureValue = <K extends keyof GrowthbookConfigs, V extends GrowthbookConfigs[K]>(key: K, defaultValue: V) => {\n const value = this.GrowthBook.getFeatureValue(key as string, defaultValue)\n this.log('getFeatureValue', { key, value, defaultValue })\n return value\n }\n getStatus = async (): Promise<{ isLoaded: boolean; status: void | InitResponse }> => {\n await this.waitForIsLoaded()\n\n return {\n isLoaded: this.isLoaded,\n status: this.status,\n }\n }\n getFeatureState = (id: string) => {\n const state = this.GrowthBook.evalFeature(id)\n this.log('getFeatureState', { id, result: state })\n return state\n }\n setUrl = (href: string) => {\n this.log('setUrl', { href })\n this.GrowthBook.setURL(href)\n }\n isOn = (key: string) => {\n const result = this.GrowthBook.isOn(key)\n this.log('isOn', { key, result })\n return result\n }\n\n init = async () => {\n this.log('init | initializing GrowthBook SDK')\n const status = await this.GrowthBook.init({ timeout: 2000, streaming: true }).catch(() => {\n // Silently handle initialization errors\n })\n\n this.status = status\n this.isLoaded = true\n this.log('init | GrowthBook SDK loaded', { status })\n }\n\n // Destroy the GrowthBook instance and reset singleton\n destroy = () => {\n this.GrowthBook.destroy()\n this.isLoaded = false\n this.status = undefined\n }\n\n // Reset the singleton instance (useful for testing)\n public static resetInstance = () => {\n if (Growthbook._instance) {\n Growthbook._instance.destroy()\n Growthbook._instance = undefined as any\n }\n }\n}\n\nexport type { GrowthbookConfigs, TGrowthbookAttributes, TGrowthbookOptions, TGrowthbookCoreAttributes }\n"]}
@@ -1,3 +1,3 @@
1
- export { P as Posthog } from '../../posthog-lAeI7PhD.mjs';
1
+ export { P as Posthog } from '../../posthog-Ds4g1sJf.mjs';
2
2
  import '../../types-DoMejCXv.mjs';
3
3
  import 'posthog-js';
@@ -1,3 +1,3 @@
1
- export { P as Posthog } from '../../posthog-DV6iayrn.js';
1
+ export { P as Posthog } from '../../posthog-DvDj4azD.js';
2
2
  import '../../types-DoMejCXv.js';
3
3
  import 'posthog-js';
@@ -1,3 +1,3 @@
1
- 'use strict';var chunkNOEKD4DT_js=require('../../chunk-NOEKD4DT.js'),o=require('posthog-js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var o__default=/*#__PURE__*/_interopDefault(o);/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var e=class e{constructor(t){this.has_initialized=false;this.has_identified=false;this.init=()=>{try{let{apiKey:t,api_host:s,config:i={}}=this.options;if(!t){console.warn("Posthog: No API key provided");return}let n={api_host:s||chunkNOEKD4DT_js.d,ui_host:chunkNOEKD4DT_js.e,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...i.session_recording},before_send:a=>{if(typeof window>"u")return null;let r=window.location.hostname;return r==="localhost"||r==="127.0.0.1"||chunkNOEKD4DT_js.f.some(h=>r.endsWith(`.${h}`)||r===h)?a:null},...i};o__default.default.init(t,n),this.has_initialized=!0;}catch(t){console.error("Posthog: Failed to initialize",t);}};this.identifyEvent=(t,s)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let i=typeof o__default.default._isIdentified=="function"?o__default.default._isIdentified():this.has_identified;if(t&&!i){let n=o__default.default.get_distinct_id();n&&n!==t&&o__default.default.alias(t,n);}o__default.default.identify(t,s),this.has_identified=!0;}catch(i){console.error("Posthog: Failed to identify user",i);}};this.reset=()=>{if(this.has_initialized)try{o__default.default.reset(),this.has_identified=!1;}catch(t){console.error("Posthog: Failed to reset",t);}};this.capture=(t,s)=>{if(this.has_initialized)try{o__default.default.capture(t,s);}catch(i){console.error("Posthog: Failed to capture event",i);}};this.options=t,this.init();}};e.getPosthogInstance=t=>(e._instance||(e._instance=new e(t)),e._instance);var l=e;exports.Posthog=l;//# sourceMappingURL=index.js.map
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
3
3
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","apiKey","api_host","config","posthogConfig","posthogApiHost","posthogUiHost","event","currentHost","allowedDomains","domain","posthog","error","user_id","traits","isIdentified","anonId","event_name","properties","Posthog"],"mappings":";AAmBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAMjB,WAAA,CAAYC,CAAAA,CAA0B,CALtC,IAAA,CAAA,eAAA,CAAkB,KAAA,CAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAyBjB,IAAA,CAAA,IAAA,CAAO,IAAY,CACf,GAAI,CACA,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAAC,CAAAA,CAAU,MAAA,CAAAC,CAAAA,CAAS,EAAG,CAAA,CAAI,IAAA,CAAK,OAAA,CAE/C,GAAI,CAACF,CAAAA,CAAQ,CACT,OAAA,CAAQ,IAAA,CAAK,8BAA8B,CAAA,CAC3C,MACJ,CAEA,IAAMG,CAAAA,CAAgC,CAClC,QAAA,CAAUF,CAAAA,EAAYG,kBAAAA,CACtB,OAAA,CAASC,kBAAAA,CACT,WAAA,CAAa,CAAA,CAAA,CACb,gBAAA,CAAkB,gBAAA,CAClB,iBAAA,CAAmB,CACf,wBAAA,CAA0B,CAAA,CA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,QAAA,CAASE,CAAAA,CAASC,CAAM,CAAA,CAChC,IAAA,CAAK,cAAA,CAAiB,CAAA,EAC1B,CAAA,MAASF,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CAMA,IAAA,CAAA,KAAA,CAAQ,IAAY,CAChB,GAAK,IAAA,CAAK,gBAEV,GAAI,CACAD,kBAAAA,CAAQ,KAAA,EAAM,CACd,IAAA,CAAK,cAAA,CAAiB,CAAA,EAC1B,CAAA,MAASC,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,0BAAA,CAA4BA,CAAK,EACnD,CACJ,CAAA,CASA,IAAA,CAAA,OAAA,CAAU,CAACK,CAAAA,CAAoBC,CAAAA,GAAsE,CACjG,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACAP,kBAAAA,CAAQ,OAAA,CAAQM,CAAAA,CAAYC,CAAU,EAC1C,CAAA,MAASN,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CA5HI,IAAA,CAAK,OAAA,CAAUZ,CAAAA,CACf,IAAA,CAAK,IAAA,GACT,CA2HJ,CAAA,CApIaD,CAAAA,CAgBK,kBAAA,CAAsBC,CAAAA,GAC3BD,CAAAA,CAAQ,SAAA,GACTA,CAAAA,CAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAO,CAAA,CAAA,CAEpCD,CAAAA,CAAQ,SAAA,CAAA,KApBVoB,CAAAA,CAANpB","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'\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 and aliasing\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\n constructor(options: TPosthogOptions) {\n this.options = options\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 * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options)\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 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 return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog\n * Creates an alias between anonymous ID and user ID, then identifies with traits\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 // Only alias if not already identified\n const isIdentified =\n typeof posthog._isIdentified === 'function' ? posthog._isIdentified() : this.has_identified\n\n if (user_id && !isIdentified) {\n const anonId = posthog.get_distinct_id()\n if (anonId && anonId !== user_id) {\n posthog.alias(user_id, anonId)\n }\n }\n\n // Identify with traits\n posthog.identify(user_id, traits)\n this.has_identified = true\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 posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', 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 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","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,QAA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AACC,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,3 +1,3 @@
1
- import {f,e as e$1,d}from'../../chunk-DNCZM4KN.mjs';import o from'posthog-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var e=class e{constructor(t){this.has_initialized=false;this.has_identified=false;this.init=()=>{try{let{apiKey:t,api_host:s,config:i={}}=this.options;if(!t){console.warn("Posthog: No API key provided");return}let n={api_host:s||d,ui_host:e$1,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...i.session_recording},before_send:a=>{if(typeof window>"u")return null;let r=window.location.hostname;return r==="localhost"||r==="127.0.0.1"||f.some(h=>r.endsWith(`.${h}`)||r===h)?a:null},...i};o.init(t,n),this.has_initialized=!0;}catch(t){console.error("Posthog: Failed to initialize",t);}};this.identifyEvent=(t,s)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let i=typeof o._isIdentified=="function"?o._isIdentified():this.has_identified;if(t&&!i){let n=o.get_distinct_id();n&&n!==t&&o.alias(t,n);}o.identify(t,s),this.has_identified=!0;}catch(i){console.error("Posthog: Failed to identify user",i);}};this.reset=()=>{if(this.has_initialized)try{o.reset(),this.has_identified=!1;}catch(t){console.error("Posthog: Failed to reset",t);}};this.capture=(t,s)=>{if(this.has_initialized)try{o.capture(t,s);}catch(i){console.error("Posthog: Failed to capture event",i);}};this.options=t,this.init();}};e.getPosthogInstance=t=>(e._instance||(e._instance=new e(t)),e._instance);var l=e;export{l as Posthog};//# sourceMappingURL=index.mjs.map
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
3
3
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","apiKey","api_host","config","posthogConfig","posthogApiHost","posthogUiHost","event","currentHost","allowedDomains","domain","posthog","error","user_id","traits","isIdentified","anonId","event_name","properties","Posthog"],"mappings":";AAmBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAMjB,WAAA,CAAYC,CAAAA,CAA0B,CALtC,IAAA,CAAA,eAAA,CAAkB,KAAA,CAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAyBjB,IAAA,CAAA,IAAA,CAAO,IAAY,CACf,GAAI,CACA,GAAM,CAAE,MAAA,CAAAC,CAAA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A,CAAAA,CAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAO,CAAA,CAAA,CAEpCD,CAAAA,CAAQ,SAAA,CAAA,KApBVoB,CAAAA,CAANpB","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'\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 and aliasing\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\n constructor(options: TPosthogOptions) {\n this.options = options\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 * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options)\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 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 return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog\n * Creates an alias between anonymous ID and user ID, then identifies with traits\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 // Only alias if not already identified\n const isIdentified =\n typeof posthog._isIdentified === 'function' ? posthog._isIdentified() : this.has_identified\n\n if (user_id && !isIdentified) {\n const anonId = posthog.get_distinct_id()\n if (anonId && anonId !== user_id) {\n posthog.alias(user_id, anonId)\n }\n }\n\n // Identify with traits\n posthog.identify(user_id, traits)\n this.has_identified = true\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 posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', 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 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","posthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","domain","posthog","error","user_id","traits","isIdentified","email","safeTraits","isInternalEmail","storedProperties","updates","event_name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A,CAAI,oCAAA,CAAsC,CAAE,UAAA,CAAAD,CAAAA,CAAY,WAAAC,CAAW,CAAC,EACzEX,CAAAA,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.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"]}
@@ -13,14 +13,17 @@ declare class RudderStack {
13
13
  rudderstack_anonymous_cookie_key: string;
14
14
  private static _instance;
15
15
  private onLoadedCallback?;
16
- constructor(RUDDERSTACK_KEY: string, onLoaded?: () => void);
16
+ private debug;
17
+ private log;
18
+ constructor(RUDDERSTACK_KEY: string, onLoaded?: () => void, debug?: boolean);
17
19
  /**
18
20
  * Get or create the singleton instance of RudderStack
19
21
  * @param RUDDERSTACK_KEY - RudderStack write key
20
22
  * @param onLoaded - Optional callback when RudderStack is loaded
23
+ * @param debug - Enable debug logging
21
24
  * @returns The RudderStack singleton instance
22
25
  */
23
- static getRudderStackInstance: (RUDDERSTACK_KEY: string, onLoaded?: () => void) => RudderStack;
26
+ static getRudderStackInstance: (RUDDERSTACK_KEY: string, onLoaded?: () => void, debug?: boolean) => RudderStack;
24
27
  /**
25
28
  * Get the anonymous ID from cookies
26
29
  * @returns The anonymous ID or undefined if not found
@@ -13,14 +13,17 @@ declare class RudderStack {
13
13
  rudderstack_anonymous_cookie_key: string;
14
14
  private static _instance;
15
15
  private onLoadedCallback?;
16
- constructor(RUDDERSTACK_KEY: string, onLoaded?: () => void);
16
+ private debug;
17
+ private log;
18
+ constructor(RUDDERSTACK_KEY: string, onLoaded?: () => void, debug?: boolean);
17
19
  /**
18
20
  * Get or create the singleton instance of RudderStack
19
21
  * @param RUDDERSTACK_KEY - RudderStack write key
20
22
  * @param onLoaded - Optional callback when RudderStack is loaded
23
+ * @param debug - Enable debug logging
21
24
  * @returns The RudderStack singleton instance
22
25
  */
23
- static getRudderStackInstance: (RUDDERSTACK_KEY: string, onLoaded?: () => void) => RudderStack;
26
+ static getRudderStackInstance: (RUDDERSTACK_KEY: string, onLoaded?: () => void, debug?: boolean) => RudderStack;
24
27
  /**
25
28
  * Get the anonymous ID from cookies
26
29
  * @returns The anonymous ID or undefined if not found
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkCAKVOFLO_js=require('../../chunk-CAKVOFLO.js');require('../../chunk-NOEKD4DT.js');Object.defineProperty(exports,"RudderStack",{enumerable:true,get:function(){return chunkCAKVOFLO_js.a}});//# sourceMappingURL=index.js.map
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
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- export{a as RudderStack}from'../../chunk-UDVSKE3Y.mjs';import'../../chunk-DNCZM4KN.mjs';//# sourceMappingURL=index.mjs.map
1
+ export{a as RudderStack}from'../../chunk-D2MKQCJB.mjs';import'../../chunk-ID2GN2PS.mjs';//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map