@deriv-com/analytics 1.39.5 → 1.39.7

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 (42) hide show
  1. package/dist/browser/analytics.bundle.global.js +5 -16
  2. package/dist/browser/analytics.bundle.global.js.map +1 -1
  3. package/dist/browser/analytics.esm.mjs +1 -1
  4. package/dist/browser/analytics.esm.mjs.map +1 -1
  5. package/dist/chunk-GTT7DF4Y.mjs +3 -0
  6. package/dist/chunk-GTT7DF4Y.mjs.map +1 -0
  7. package/dist/chunk-YVBRA3QD.mjs +5 -0
  8. package/dist/chunk-YVBRA3QD.mjs.map +1 -0
  9. package/dist/chunk-YZ34YKBW.js +3 -0
  10. package/dist/chunk-YZ34YKBW.js.map +1 -0
  11. package/dist/{growthbook-FZV644NE.mjs → growthbook-T47IBUAJ.mjs} +2 -2
  12. package/dist/index.d.mts +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +2 -2
  15. package/dist/index.js.map +1 -1
  16. package/dist/index.mjs +2 -2
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/metafile-cjs.json +1 -1
  19. package/dist/metafile-esm.json +1 -1
  20. package/dist/metafile-iife.json +1 -1
  21. package/dist/posthog-B3LUVMYU.mjs +4 -0
  22. package/dist/posthog-B3LUVMYU.mjs.map +1 -0
  23. package/dist/{posthog-CZnsy0at.d.ts → posthog-DUxm7AzZ.d.ts} +6 -0
  24. package/dist/{posthog-CRa194Jm.d.mts → posthog-DfHTd53-.d.mts} +6 -0
  25. package/dist/providers/posthog/index.d.mts +1 -1
  26. package/dist/providers/posthog/index.d.ts +1 -1
  27. package/dist/providers/posthog/index.js +1 -1
  28. package/dist/providers/posthog/index.js.map +1 -1
  29. package/dist/providers/posthog/index.mjs +1 -1
  30. package/dist/providers/posthog/index.mjs.map +1 -1
  31. package/dist/providers/rudderstack/index.js +1 -1
  32. package/dist/providers/rudderstack/index.mjs +1 -1
  33. package/package.json +13 -16
  34. package/dist/chunk-BGCEXYPC.mjs +0 -3
  35. package/dist/chunk-BGCEXYPC.mjs.map +0 -1
  36. package/dist/chunk-GVFVS6VE.js +0 -3
  37. package/dist/chunk-GVFVS6VE.js.map +0 -1
  38. package/dist/chunk-OMGH3V7W.mjs +0 -14
  39. package/dist/chunk-OMGH3V7W.mjs.map +0 -1
  40. package/dist/posthog-ZW7SFGPQ.mjs +0 -6
  41. package/dist/posthog-ZW7SFGPQ.mjs.map +0 -1
  42. /package/dist/{growthbook-FZV644NE.mjs.map → growthbook-T47IBUAJ.mjs.map} +0 -0
@@ -69,6 +69,12 @@ declare class Posthog {
69
69
  * @returns The Posthog singleton instance
70
70
  */
71
71
  static getPosthogInstance: (options: TPosthogOptions, debug?: boolean) => Posthog;
72
+ /**
73
+ * Remove stale PostHog cookies that don't belong to the current project key.
74
+ * PostHog sets cookies named `ph_{apiKey}_posthog` — if multiple project keys
75
+ * have been used in the same browser, old cookies pile up and should be cleaned.
76
+ */
77
+ private cleanupStalePosthogCookies;
72
78
  /**
73
79
  * Initialize PostHog with configuration
74
80
  * Configures PostHog instance with provided options
@@ -69,6 +69,12 @@ declare class Posthog {
69
69
  * @returns The Posthog singleton instance
70
70
  */
71
71
  static getPosthogInstance: (options: TPosthogOptions, debug?: boolean) => Posthog;
72
+ /**
73
+ * Remove stale PostHog cookies that don't belong to the current project key.
74
+ * PostHog sets cookies named `ph_{apiKey}_posthog` — if multiple project keys
75
+ * have been used in the same browser, old cookies pile up and should be cleaned.
76
+ */
77
+ private cleanupStalePosthogCookies;
72
78
  /**
73
79
  * Initialize PostHog with configuration
74
80
  * Configures PostHog instance with provided options
@@ -1,3 +1,3 @@
1
- export { P as Posthog } from '../../posthog-CRa194Jm.mjs';
1
+ export { P as Posthog } from '../../posthog-DfHTd53-.mjs';
2
2
  import '../../types-DoMejCXv.mjs';
3
3
  import 'posthog-js';
@@ -1,3 +1,3 @@
1
- export { P as Posthog } from '../../posthog-CZnsy0at.js';
1
+ export { P as Posthog } from '../../posthog-DUxm7AzZ.js';
2
2
  import '../../types-DoMejCXv.js';
3
3
  import 'posthog-js';
@@ -1,3 +1,3 @@
1
1
  'use strict';var chunkT4BXL6JM_js=require('../../chunk-T4BXL6JM.js'),r=require('posthog-js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var r__default=/*#__PURE__*/_interopDefault(r);/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var n=class n{constructor(i,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=chunkT4BXL6JM_js.f("[PostHog]",()=>this.debug);this.init=()=>{try{let{apiKey:i,api_host:t,config:e={}}=this.options;if(!i){console.warn("Posthog: No API key provided");return}let o=t||chunkT4BXL6JM_js.d();this.log("init | loading PostHog SDK",{api_host:o});let s={api_host:o,ui_host:chunkT4BXL6JM_js.c,autocapture:!0,capture_pageview:"history_change",persistence:"localStorage",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...e.session_recording},before_send:l=>{if(typeof window>"u")return null;let a=window.location.hostname;if(a==="localhost"||a==="127.0.0.1")return l;let d=chunkT4BXL6JM_js.e.some(c=>a.endsWith(`.${c}`)||a===c);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:a}),d?l:null},...e};r__default.default.init(i,s),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(i){console.error("Posthog: Failed to initialize",i);}};this.identifyEvent=(i,t)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let e=typeof r__default.default._isIdentified=="function"?r__default.default._isIdentified():this.has_identified;i&&!e?(this.log("identifyEvent | identifying user",{user_id:i,traits:t}),r__default.default.identify(i,{...t,client_id:i}),this.has_identified=!0):this.log("identifyEvent | skipped \u2014 user already identified",{user_id:i});}catch(e){console.error("Posthog: Failed to identify user",e);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),r__default.default.reset(),this.has_identified=!1;}catch(i){console.error("Posthog: Failed to reset",i);}};this.backfillPersonProperties=({user_id:i,email:t,country_of_residence:e})=>{if(!(!this.has_initialized||!i))try{let o=r__default.default.get_property("$stored_person_properties")??{},s={};o.client_id||(s.client_id=i),t&&o.is_internal===void 0&&(s.is_internal=chunkT4BXL6JM_js.g(t)),e&&!o.country_of_residence&&(s.country_of_residence=e),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:i,updates:s}),r__default.default.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:i,country_of_residence:e});}catch(o){console.error("Posthog: Failed to backfill person properties",o);}};this.capture=(i,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:i,properties:t}),r__default.default.capture(i,t);}catch(e){console.error("Posthog: Failed to capture event",e);}};this.options=i,this.debug=t,this.init();}};n.getPosthogInstance=(i,t=false)=>(n._instance||(n._instance=new n(i,t)),n._instance);var P=n;exports.Posthog=P;//# sourceMappingURL=index.js.map
2
+ var l=class l{constructor(t,i=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=chunkT4BXL6JM_js.f("[PostHog]",()=>this.debug);this.cleanupStalePosthogCookies=t=>{if(typeof document>"u"||typeof window>"u")return;let i=`ph_${t}_posthog`,o=document.cookie.split(";").map(e=>e.trim().split("=")[0]??"").filter(e=>/^ph_.+_posthog$/.test(e)&&e!==i);if(o.length===0)return;let s=window.location.hostname,n=s.split("."),c=n.length>=2?`.${n.slice(-2).join(".")}`:s;o.forEach(e=>{[c,s,""].forEach(a=>{let y=a?`; Domain=${a}`:"";document.cookie=`${e}=; path=/${y}; max-age=0; SameSite=Lax`;});let d=!document.cookie.split(";").some(a=>a.trim().startsWith(`${e}=`));this.log(`cleanupStalePosthogCookies | ${d?"removed":"failed to remove"} stale cookie: ${e}`);});};this.init=()=>{try{let{apiKey:t,api_host:i,config:o={}}=this.options;if(!t){console.warn("Posthog: No API key provided");return}this.cleanupStalePosthogCookies(t);let s=i||chunkT4BXL6JM_js.d();this.log("init | loading PostHog SDK",{api_host:s});let n={api_host:s,ui_host:chunkT4BXL6JM_js.c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...o.session_recording},before_send:c=>{if(typeof window>"u")return null;let e=window.location.hostname;if(e==="localhost"||e==="127.0.0.1")return c;let d=chunkT4BXL6JM_js.e.some(a=>e.endsWith(`.${a}`)||e===a);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:e}),d?c:null},...o};r__default.default.init(t,n),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(t){console.error("Posthog: Failed to initialize",t);}};this.identifyEvent=(t,i)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let o=typeof r__default.default._isIdentified=="function"?r__default.default._isIdentified():this.has_identified;t&&!o?(this.log("identifyEvent | identifying user",{user_id:t,traits:i}),r__default.default.identify(t,{...i,client_id:t}),this.has_identified=!0):this.log("identifyEvent | skipped \u2014 user already identified",{user_id:t});}catch(o){console.error("Posthog: Failed to identify user",o);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),r__default.default.reset(),this.has_identified=!1;}catch(t){console.error("Posthog: Failed to reset",t);}};this.backfillPersonProperties=({user_id:t,email:i,country_of_residence:o})=>{if(!(!this.has_initialized||!t))try{let s=r__default.default.get_property("$stored_person_properties")??{},n={};s.client_id||(n.client_id=t),i&&s.is_internal===void 0&&(n.is_internal=chunkT4BXL6JM_js.g(i)),o&&!s.country_of_residence&&(n.country_of_residence=o),Object.keys(n).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:t,updates:n}),r__default.default.setPersonProperties(n)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:t,country_of_residence:o});}catch(s){console.error("Posthog: Failed to backfill person properties",s);}};this.capture=(t,i)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:t,properties:i}),r__default.default.capture(t,i);}catch(o){console.error("Posthog: Failed to capture event",o);}};this.options=t,this.debug=i,this.init();}};l.getPosthogInstance=(t,i=false)=>(l._instance||(l._instance=new l(t,i)),l._instance);var P=l;exports.Posthog=P;//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","apiKey","api_host","config","resolvedApiHost","getPosthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","domain","posthog","error","user_id","traits","isIdentified","email","country_of_residence","storedProperties","updates","isInternalEmail","event_name","properties","Posthog"],"mappings":";AAqBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,IAAA,CAAA,eAAA,CAAkB,KAAA,CAClB,oBAAiB,KAAA,CAGjB,IAAA,CAAQ,MAAQ,KAAA,CAChB,IAAA,CAAQ,GAAA,CAAMC,kBAAAA,CAAa,WAAA,CAAa,IAAM,KAAK,KAAK,CAAA,CAyBxD,UAAO,IAAY,CACf,GAAI,CACA,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAAC,EAAU,MAAA,CAAAC,CAAAA,CAAS,EAAG,CAAA,CAAI,IAAA,CAAK,QAE/C,GAAI,CAACF,CAAAA,CAAQ,CACT,OAAA,CAAQ,IAAA,CAAK,8BAA8B,CAAA,CAC3C,MACJ,CAEA,IAAMG,CAAAA,CAAkBF,GAAYG,kBAAAA,EAAkB,CACtD,IAAA,CAAK,GAAA,CAAI,4BAAA,CAA8B,CAAE,SAAUD,CAAgB,CAAC,EAEpE,IAAME,CAAAA,CAAgC,CAClC,QAAA,CAAUF,CAAAA,CACV,OAAA,CAASG,kBAAAA,CACT,WAAA,CAAa,CAAA,CAAA,CACb,iBAAkB,gBAAA,CAClB,WAAA,CAAa,eACb,iBAAA,CAAmB,CACf,yBAA0B,CAAA,CAAA,CAC1B,2BAAA,CAA6B,GAAA,CAC7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,CAAS,QAAAM,CAAQ,CAAC,EACzFR,kBAAAA,CAAQ,mBAAA,CAAoBQ,CAAO,CAAA,EAEnC,IAAA,CAAK,GAAA,CAAI,0EAAA,CAAuE,CAC5E,OAAA,CAAAN,EACA,oBAAA,CAAAI,CACJ,CAAC,EAET,CAAA,MAASL,EAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,+CAAA,CAAiDA,CAAK,EACxE,CACJ,CAAA,CASA,IAAA,CAAA,OAAA,CAAU,CAACS,CAAAA,CAAoBC,CAAAA,GAAsE,CACjG,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,GAAA,CAAI,qCAAsC,CAAE,UAAA,CAAAD,EAAY,UAAA,CAAAC,CAAW,CAAC,CAAA,CACzEX,kBAAAA,CAAQ,OAAA,CAAQU,CAAAA,CAAYC,CAAU,EAC1C,OAASV,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CAtLI,IAAA,CAAK,OAAA,CAAUhB,CAAAA,CACf,IAAA,CAAK,MAAQC,CAAAA,CACb,IAAA,CAAK,OACT,CAoLJ,EAhMaF,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,IAAM4B,CAAAA,CAAN5B","file":"index.js","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport type { TCoreAttributes } from '../types'\nimport { allowedDomains, getPosthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Initialize PostHog with configuration\n * Configures PostHog instance with provided options\n */\n init = (): void => {\n try {\n const { apiKey, api_host, config = {} } = this.options\n\n if (!apiKey) {\n console.warn('Posthog: No API key provided')\n return\n }\n\n const resolvedApiHost = api_host || getPosthogApiHost()\n this.log('init | loading PostHog SDK', { api_host: resolvedApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: resolvedApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n persistence: 'localStorage',\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 this.log('identifyEvent | identifying user', { user_id, traits })\n posthog.identify(user_id, {\n ...traits,\n client_id: user_id,\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param params.user_id - The user ID to use as client_id\n * @param params.email - The user's email, used to determine is_internal\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n country_of_residence?: string\n }): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties: Record<string, any> = posthog.get_property('$stored_person_properties') ?? {}\n const updates: Record<string, any> = {}\n\n if (!storedProperties.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n if (country_of_residence && !storedProperties.country_of_residence) {\n updates.country_of_residence = country_of_residence\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', {\n user_id,\n country_of_residence,\n })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any> & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","currentApiKey","currentCookieName","staleCookies","c","name","hostname","domainParts","rootDomain","domain","domainAttr","deleted","apiKey","api_host","config","resolvedApiHost","getPosthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","posthog","error","user_id","traits","isIdentified","email","country_of_residence","storedProperties","updates","isInternalEmail","event_name","properties","Posthog"],"mappings":";AAqBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,qBAAkB,KAAA,CAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,IAAA,CAAQ,KAAA,CAAQ,KAAA,CAChB,IAAA,CAAQ,GAAA,CAAMC,mBAAa,WAAA,CAAa,IAAM,IAAA,CAAK,KAAK,CAAA,CA0BxD,IAAA,CAAQ,0BAAA,CAA8BC,CAAAA,EAAgC,CAClE,GAAI,OAAO,QAAA,CAAa,GAAA,EAAe,OAAO,MAAA,CAAW,GAAA,CAAa,OAEtE,IAAMC,CAAAA,CAAoB,CAAA,GAAA,E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AU,CAACS,CAAAA,CAAoBC,CAAAA,GAAsE,CACjG,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,KAAK,GAAA,CAAI,oCAAA,CAAsC,CAAE,UAAA,CAAAD,CAAAA,CAAY,UAAA,CAAAC,CAAW,CAAC,EACzEX,kBAAAA,CAAQ,OAAA,CAAQU,CAAAA,CAAYC,CAAU,EAC1C,CAAA,MAASV,CAAAA,CAAO,CACZ,QAAQ,KAAA,CAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CAxNI,IAAA,CAAK,OAAA,CAAU1B,CAAAA,CACf,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,GACT,CAsNJ,EAlOaF,CAAAA,CAoBK,kBAAA,CAAqB,CAACC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,IAC7DF,CAAAA,CAAQ,SAAA,GACTA,EAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,KAxBVsC,CAAAA,CAANtC","file":"index.js","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport type { TCoreAttributes } from '../types'\nimport { allowedDomains, getPosthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Remove stale PostHog cookies that don't belong to the current project key.\n * PostHog sets cookies named `ph_{apiKey}_posthog` — if multiple project keys\n * have been used in the same browser, old cookies pile up and should be cleaned.\n */\n private cleanupStalePosthogCookies = (currentApiKey: string): void => {\n if (typeof document === 'undefined' || typeof window === 'undefined') return\n\n const currentCookieName = `ph_${currentApiKey}_posthog`\n const staleCookies = document.cookie\n .split(';')\n .map(c => c.trim().split('=')[0] ?? '')\n .filter(name => /^ph_.+_posthog$/.test(name) && name !== currentCookieName)\n\n if (staleCookies.length === 0) return\n\n const hostname = window.location.hostname\n const domainParts = hostname.split('.')\n // TLD+2 assumption: works for deriv.com → .deriv.com but would produce\n // .co.uk for app.deriv.co.uk. Acceptable for current Deriv domains.\n const rootDomain = domainParts.length >= 2 ? `.${domainParts.slice(-2).join('.')}` : hostname\n\n staleCookies.forEach(name => {\n // Try deleting with root domain, subdomain, and no domain\n ;[rootDomain, hostname, ''].forEach(domain => {\n const domainAttr = domain ? `; Domain=${domain}` : ''\n document.cookie = `${name}=; path=/${domainAttr}; max-age=0; SameSite=Lax`\n })\n const deleted = !document.cookie.split(';').some(c => c.trim().startsWith(`${name}=`))\n this.log(`cleanupStalePosthogCookies | ${deleted ? 'removed' : 'failed to remove'} stale cookie: ${name}`)\n })\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.cleanupStalePosthogCookies(apiKey)\n\n const resolvedApiHost = api_host || getPosthogApiHost()\n this.log('init | loading PostHog SDK', { api_host: resolvedApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: resolvedApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n session_recording: {\n recordCrossOriginIframes: true,\n minimumDurationMilliseconds: 30000,\n ...config.session_recording,\n },\n before_send: event => {\n if (typeof window === 'undefined') return null\n\n const currentHost = window.location.hostname\n if (currentHost === 'localhost' || currentHost === '127.0.0.1') return event\n\n const isAllowed = allowedDomains.some(\n domain => currentHost.endsWith(`.${domain}`) || currentHost === domain\n )\n if (!isAllowed) this.log('init | before_send blocked event from disallowed host', { currentHost })\n return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n this.log('init | PostHog SDK loaded successfully')\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog.\n * Skipped if the user is already identified — use backfillPersonProperties to backfill\n * client_id for users identified in previous sessions.\n *\n * @param user_id - The user ID to identify\n * @param traits - User properties (language, country_of_residence, etc.)\n */\n identifyEvent = (user_id: string, traits: TPosthogIdentifyTraits): void => {\n if (!this.has_initialized) {\n console.warn('Posthog: Cannot identify - not initialized')\n return\n }\n\n try {\n const isIdentified =\n typeof posthog._isIdentified === 'function' ? posthog._isIdentified() : this.has_identified\n\n if (user_id && !isIdentified) {\n this.log('identifyEvent | identifying user', { user_id, traits })\n posthog.identify(user_id, {\n ...traits,\n client_id: user_id,\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param params.user_id - The user ID to use as client_id\n * @param params.email - The user's email, used to determine is_internal\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n country_of_residence?: string\n }): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties: Record<string, any> = posthog.get_property('$stored_person_properties') ?? {}\n const updates: Record<string, any> = {}\n\n if (!storedProperties.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n if (country_of_residence && !storedProperties.country_of_residence) {\n updates.country_of_residence = country_of_residence\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', {\n user_id,\n country_of_residence,\n })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any> & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n}\n"]}
@@ -1,3 +1,3 @@
1
1
  import {f,d,e,c,g}from'../../chunk-TE3DYZVQ.mjs';import r from'posthog-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var n=class n{constructor(i,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=f("[PostHog]",()=>this.debug);this.init=()=>{try{let{apiKey:i,api_host:t,config:e$1={}}=this.options;if(!i){console.warn("Posthog: No API key provided");return}let o=t||d();this.log("init | loading PostHog SDK",{api_host:o});let s={api_host:o,ui_host:c,autocapture:!0,capture_pageview:"history_change",persistence:"localStorage",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...e$1.session_recording},before_send:l=>{if(typeof window>"u")return null;let a=window.location.hostname;if(a==="localhost"||a==="127.0.0.1")return l;let d=e.some(c=>a.endsWith(`.${c}`)||a===c);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:a}),d?l:null},...e$1};r.init(i,s),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(i){console.error("Posthog: Failed to initialize",i);}};this.identifyEvent=(i,t)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let e=typeof r._isIdentified=="function"?r._isIdentified():this.has_identified;i&&!e?(this.log("identifyEvent | identifying user",{user_id:i,traits:t}),r.identify(i,{...t,client_id:i}),this.has_identified=!0):this.log("identifyEvent | skipped \u2014 user already identified",{user_id:i});}catch(e){console.error("Posthog: Failed to identify user",e);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),r.reset(),this.has_identified=!1;}catch(i){console.error("Posthog: Failed to reset",i);}};this.backfillPersonProperties=({user_id:i,email:t,country_of_residence:e})=>{if(!(!this.has_initialized||!i))try{let o=r.get_property("$stored_person_properties")??{},s={};o.client_id||(s.client_id=i),t&&o.is_internal===void 0&&(s.is_internal=g(t)),e&&!o.country_of_residence&&(s.country_of_residence=e),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:i,updates:s}),r.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:i,country_of_residence:e});}catch(o){console.error("Posthog: Failed to backfill person properties",o);}};this.capture=(i,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:i,properties:t}),r.capture(i,t);}catch(e){console.error("Posthog: Failed to capture event",e);}};this.options=i,this.debug=t,this.init();}};n.getPosthogInstance=(i,t=false)=>(n._instance||(n._instance=new n(i,t)),n._instance);var P=n;export{P as Posthog};//# sourceMappingURL=index.mjs.map
2
+ var l=class l{constructor(t,i=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=f("[PostHog]",()=>this.debug);this.cleanupStalePosthogCookies=t=>{if(typeof document>"u"||typeof window>"u")return;let i=`ph_${t}_posthog`,o=document.cookie.split(";").map(e=>e.trim().split("=")[0]??"").filter(e=>/^ph_.+_posthog$/.test(e)&&e!==i);if(o.length===0)return;let s=window.location.hostname,n=s.split("."),c=n.length>=2?`.${n.slice(-2).join(".")}`:s;o.forEach(e=>{[c,s,""].forEach(a=>{let y=a?`; Domain=${a}`:"";document.cookie=`${e}=; path=/${y}; max-age=0; SameSite=Lax`;});let d=!document.cookie.split(";").some(a=>a.trim().startsWith(`${e}=`));this.log(`cleanupStalePosthogCookies | ${d?"removed":"failed to remove"} stale cookie: ${e}`);});};this.init=()=>{try{let{apiKey:t,api_host:i,config:o={}}=this.options;if(!t){console.warn("Posthog: No API key provided");return}this.cleanupStalePosthogCookies(t);let s=i||d();this.log("init | loading PostHog SDK",{api_host:s});let n={api_host:s,ui_host:c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...o.session_recording},before_send:c=>{if(typeof window>"u")return null;let e$1=window.location.hostname;if(e$1==="localhost"||e$1==="127.0.0.1")return c;let d=e.some(a=>e$1.endsWith(`.${a}`)||e$1===a);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:e$1}),d?c:null},...o};r.init(t,n),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(t){console.error("Posthog: Failed to initialize",t);}};this.identifyEvent=(t,i)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let o=typeof r._isIdentified=="function"?r._isIdentified():this.has_identified;t&&!o?(this.log("identifyEvent | identifying user",{user_id:t,traits:i}),r.identify(t,{...i,client_id:t}),this.has_identified=!0):this.log("identifyEvent | skipped \u2014 user already identified",{user_id:t});}catch(o){console.error("Posthog: Failed to identify user",o);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),r.reset(),this.has_identified=!1;}catch(t){console.error("Posthog: Failed to reset",t);}};this.backfillPersonProperties=({user_id:t,email:i,country_of_residence:o})=>{if(!(!this.has_initialized||!t))try{let s=r.get_property("$stored_person_properties")??{},n={};s.client_id||(n.client_id=t),i&&s.is_internal===void 0&&(n.is_internal=g(i)),o&&!s.country_of_residence&&(n.country_of_residence=o),Object.keys(n).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:t,updates:n}),r.setPersonProperties(n)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:t,country_of_residence:o});}catch(s){console.error("Posthog: Failed to backfill person properties",s);}};this.capture=(t,i)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:t,properties:i}),r.capture(t,i);}catch(o){console.error("Posthog: Failed to capture event",o);}};this.options=t,this.debug=i,this.init();}};l.getPosthogInstance=(t,i=false)=>(l._instance||(l._instance=new l(t,i)),l._instance);var P=l;export{P as Posthog};//# sourceMappingURL=index.mjs.map
3
3
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","apiKey","api_host","config","resolvedApiHost","getPosthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","domain","posthog","error","user_id","traits","isIdentified","email","country_of_residence","storedProperties","updates","isInternalEmail","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,C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AAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CAtLI,IAAA,CAAK,OAAA,CAAUhB,CAAAA,CACf,IAAA,CAAK,MAAQC,CAAAA,CACb,IAAA,CAAK,OACT,CAoLJ,EAhMaF,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,IAAM4B,CAAAA,CAAN5B","file":"index.mjs","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport type { TCoreAttributes } from '../types'\nimport { allowedDomains, getPosthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Initialize PostHog with configuration\n * Configures PostHog instance with provided options\n */\n init = (): void => {\n try {\n const { apiKey, api_host, config = {} } = this.options\n\n if (!apiKey) {\n console.warn('Posthog: No API key provided')\n return\n }\n\n const resolvedApiHost = api_host || getPosthogApiHost()\n this.log('init | loading PostHog SDK', { api_host: resolvedApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: resolvedApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n persistence: 'localStorage',\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 this.log('identifyEvent | identifying user', { user_id, traits })\n posthog.identify(user_id, {\n ...traits,\n client_id: user_id,\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param params.user_id - The user ID to use as client_id\n * @param params.email - The user's email, used to determine is_internal\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n country_of_residence?: string\n }): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties: Record<string, any> = posthog.get_property('$stored_person_properties') ?? {}\n const updates: Record<string, any> = {}\n\n if (!storedProperties.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n if (country_of_residence && !storedProperties.country_of_residence) {\n updates.country_of_residence = country_of_residence\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', {\n user_id,\n country_of_residence,\n })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any> & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","currentApiKey","currentCookieName","staleCookies","c","name","hostname","domainParts","rootDomain","domain","domainAttr","deleted","apiKey","api_host","config","resolvedApiHost","getPosthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","posthog","error","user_id","traits","isIdentified","email","country_of_residence","storedProperties","updates","isInternalEmail","event_name","properties","Posthog"],"mappings":";AAqBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,qBAAkB,KAAA,CAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,IAAA,CAAQ,KAAA,CAAQ,KAAA,CAChB,IAAA,CAAQ,GAAA,CAAMC,EAAa,WAAA,CAAa,IAAM,IAAA,CAAK,KAAK,CAAA,CA0BxD,IAAA,CAAQ,0BAAA,CAA8BC,CAAAA,EAAgC,CAClE,GAAI,OAAO,QAAA,CAAa,GAAA,EAAe,OAAO,MAAA,CAAW,GAAA,CAAa,OAEtE,IAAMC,CAAAA,CAAoB,CAAA,GAAA,EAAMD,CAAa,CAAA,QAAA,CAAA,CACvCE,CAAAA,CAAe,QAAA,CAAS,MAAA,CACzB,MAAM,GAAG,CAAA,CACT,GAAA,CAAIC,CAAAA,EAAKA,CAAAA,CAAE,IAAA,EAAK,CAAE,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,EAAK,EAAE,CAAA,CACrC,MAAA,CAAOC,CAAAA,EAAQ,iBAAA,CAAkB,KAAKA,CAAI,CAAA,EAAKA,CAAAA,GAASH,CAAiB,CAAA,CAE9E,GAAIC,CAAAA,CAAa,MAAA,GAAW,CAAA,CAAG,OAE/B,IAAMG,CAAAA,CAAW,MAAA,CAAO,QAAA,CAAS,QAAA,CAC3BC,CAAAA,CAAcD,EAAS,KAAA,CAAM,GAAG,CAAA,CAGhCE,CAAAA,CAAaD,CAAAA,CAAY,MAAA,EAAU,CAAA,CAAI,CAAA,CAAA,EAAIA,EAAY,KAAA,CAAM,EAAE,CAA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CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,KAxBVsC,CAAAA,CAANtC","file":"index.mjs","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport type { TCoreAttributes } from '../types'\nimport { allowedDomains, getPosthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Remove stale PostHog cookies that don't belong to the current project key.\n * PostHog sets cookies named `ph_{apiKey}_posthog` — if multiple project keys\n * have been used in the same browser, old cookies pile up and should be cleaned.\n */\n private cleanupStalePosthogCookies = (currentApiKey: string): void => {\n if (typeof document === 'undefined' || typeof window === 'undefined') return\n\n const currentCookieName = `ph_${currentApiKey}_posthog`\n const staleCookies = document.cookie\n .split(';')\n .map(c => c.trim().split('=')[0] ?? '')\n .filter(name => /^ph_.+_posthog$/.test(name) && name !== currentCookieName)\n\n if (staleCookies.length === 0) return\n\n const hostname = window.location.hostname\n const domainParts = hostname.split('.')\n // TLD+2 assumption: works for deriv.com → .deriv.com but would produce\n // .co.uk for app.deriv.co.uk. Acceptable for current Deriv domains.\n const rootDomain = domainParts.length >= 2 ? `.${domainParts.slice(-2).join('.')}` : hostname\n\n staleCookies.forEach(name => {\n // Try deleting with root domain, subdomain, and no domain\n ;[rootDomain, hostname, ''].forEach(domain => {\n const domainAttr = domain ? `; Domain=${domain}` : ''\n document.cookie = `${name}=; path=/${domainAttr}; max-age=0; SameSite=Lax`\n })\n const deleted = !document.cookie.split(';').some(c => c.trim().startsWith(`${name}=`))\n this.log(`cleanupStalePosthogCookies | ${deleted ? 'removed' : 'failed to remove'} stale cookie: ${name}`)\n })\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.cleanupStalePosthogCookies(apiKey)\n\n const resolvedApiHost = api_host || getPosthogApiHost()\n this.log('init | loading PostHog SDK', { api_host: resolvedApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: resolvedApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n session_recording: {\n recordCrossOriginIframes: true,\n minimumDurationMilliseconds: 30000,\n ...config.session_recording,\n },\n before_send: event => {\n if (typeof window === 'undefined') return null\n\n const currentHost = window.location.hostname\n if (currentHost === 'localhost' || currentHost === '127.0.0.1') return event\n\n const isAllowed = allowedDomains.some(\n domain => currentHost.endsWith(`.${domain}`) || currentHost === domain\n )\n if (!isAllowed) this.log('init | before_send blocked event from disallowed host', { currentHost })\n return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n this.log('init | PostHog SDK loaded successfully')\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog.\n * Skipped if the user is already identified — use backfillPersonProperties to backfill\n * client_id for users identified in previous sessions.\n *\n * @param user_id - The user ID to identify\n * @param traits - User properties (language, country_of_residence, etc.)\n */\n identifyEvent = (user_id: string, traits: TPosthogIdentifyTraits): void => {\n if (!this.has_initialized) {\n console.warn('Posthog: Cannot identify - not initialized')\n return\n }\n\n try {\n const isIdentified =\n typeof posthog._isIdentified === 'function' ? posthog._isIdentified() : this.has_identified\n\n if (user_id && !isIdentified) {\n this.log('identifyEvent | identifying user', { user_id, traits })\n posthog.identify(user_id, {\n ...traits,\n client_id: user_id,\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param params.user_id - The user ID to use as client_id\n * @param params.email - The user's email, used to determine is_internal\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n country_of_residence?: string\n }): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties: Record<string, any> = posthog.get_property('$stored_person_properties') ?? {}\n const updates: Record<string, any> = {}\n\n if (!storedProperties.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n if (country_of_residence && !storedProperties.country_of_residence) {\n updates.country_of_residence = country_of_residence\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', {\n user_id,\n country_of_residence,\n })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any> & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n}\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkGVFVS6VE_js=require('../../chunk-GVFVS6VE.js');require('../../chunk-T4BXL6JM.js');Object.defineProperty(exports,"RudderStack",{enumerable:true,get:function(){return chunkGVFVS6VE_js.a}});//# sourceMappingURL=index.js.map
1
+ 'use strict';var chunkYZ34YKBW_js=require('../../chunk-YZ34YKBW.js');require('../../chunk-T4BXL6JM.js');Object.defineProperty(exports,"RudderStack",{enumerable:true,get:function(){return chunkYZ34YKBW_js.a}});//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- export{a as RudderStack}from'../../chunk-BGCEXYPC.mjs';import'../../chunk-TE3DYZVQ.mjs';//# sourceMappingURL=index.mjs.map
1
+ export{a as RudderStack}from'../../chunk-GTT7DF4Y.mjs';import'../../chunk-TE3DYZVQ.mjs';//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deriv-com/analytics",
3
- "version": "1.39.5",
3
+ "version": "1.39.7",
4
4
  "description": "Comprehensive analytics package for Deriv applications. Provides unified event tracking, A/B testing, and user analytics through RudderStack, PostHog and GrowthBook integrations with built-in caching and offline support.",
5
5
  "keywords": [
6
6
  "rudderstack",
@@ -46,7 +46,7 @@
46
46
  }
47
47
  },
48
48
  "scripts": {
49
- "test": "./node_modules/.bin/jest",
49
+ "test": "vitest run",
50
50
  "build": "tsup",
51
51
  "prepare": "npm run build && husky install",
52
52
  "prepublishOnly": "npm test"
@@ -62,31 +62,28 @@
62
62
  "devDependencies": {
63
63
  "@semantic-release/changelog": "^6.0.3",
64
64
  "@semantic-release/git": "^10.0.1",
65
- "@semantic-release/github": "^12.0.2",
66
- "@semantic-release/npm": "^13.1.3",
65
+ "@semantic-release/github": "^12.0.6",
66
+ "@semantic-release/npm": "^13.1.5",
67
67
  "@semantic-release/release-notes-generator": "^14.1.0",
68
- "@types/jest": "^30.0.0",
69
68
  "@types/js-cookie": "^3.0.6",
70
- "@types/node": "^25.0.10",
69
+ "@types/node": "^25.5.0",
71
70
  "husky": "^9.1.7",
72
- "jest": "^30.2.0",
73
- "jest-environment-jsdom": "^30.2.0",
74
- "jest-location-mock": "^2.0.0",
75
- "lint-staged": "^16.2.7",
71
+ "jsdom": "^26.1.0",
72
+ "lint-staged": "^16.4.0",
76
73
  "prettier": "^3.8.1",
77
- "semantic-release": "^25.0.2",
78
- "ts-jest": "^29.4.6",
74
+ "semantic-release": "^25.0.3",
79
75
  "tslib": "^2.8.1",
80
76
  "tsup": "^8.5.1",
81
- "typescript": "^5.9.3"
77
+ "typescript": "^5.9.3",
78
+ "vitest": "^3.1.1"
82
79
  },
83
80
  "dependencies": {
84
- "@rudderstack/analytics-js": "^3.14.0",
81
+ "@rudderstack/analytics-js": "^3.31.0",
85
82
  "js-cookie": "^3.0.5",
86
- "posthog-js": "1.358.0"
83
+ "posthog-js": "^1.364.0"
87
84
  },
88
85
  "optionalDependencies": {
89
- "@growthbook/growthbook": "^1.4.1"
86
+ "@growthbook/growthbook": "^1.6.5"
90
87
  },
91
88
  "engines": {
92
89
  "node": ">=24.13.0",
@@ -1,3 +0,0 @@
1
- import {f,b}from'./chunk-TE3DYZVQ.mjs';import {RudderAnalytics}from'@rudderstack/analytics-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var k=2*365*24*60*60,o=class o{constructor(e,t,i=false){this.analytics=new RudderAnalytics;this.has_identified=false;this.has_initialized=false;this.current_page="";this.rudderstack_anonymous_cookie_key="rudder_anonymous_id";this.debug=false;this.log=f("[RudderStack]",()=>this.debug);this.getAnonymousId=()=>document.cookie.match("(^|;)\\s*"+this.rudderstack_anonymous_cookie_key+"\\s*=\\s*([^;]+)")?.pop();this.setCookieIfNotExists=()=>{if(!this.getAnonymousId())try{let t=window.location.hostname,n=["webflow.io"].some(s=>t.endsWith(s))?t:t.split(".").slice(-2).join("."),d;if(crypto?.randomUUID)d=crypto.randomUUID();else if(crypto?.getRandomValues){let s=new Uint8Array(16);crypto.getRandomValues(s),s[6]=s[6]&15|64,s[8]=s[8]&63|128;let r=Array.from(s,y=>y.toString(16).padStart(2,"0")).join("");d=`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`;}else throw new Error("Crypto API not available for secure random UUID generation");let h=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${this.rudderstack_anonymous_cookie_key}=${d}; path=/; Domain=${n}; max-age=${k}; SameSite=Lax${h}`;}catch(t){console.warn("RudderStack: Failed to set anonymous ID cookie",t);}};this.getUserId=()=>this.analytics.getUserId();this.init=e=>{if(!e){console.warn("RudderStack: Initialization skipped - no key provided");return}this.log("init | loading SDK",{dataplane:b});try{this.setCookieIfNotExists(),this.analytics.load(e,b,{externalAnonymousIdCookieName:this.rudderstack_anonymous_cookie_key,storage:{type:"localStorage"},lockIntegrationsVersion:!0,onLoaded:()=>{this.has_initialized=!0,this.has_identified=!!this.getUserId(),this.log("init | SDK loaded successfully",{userId:this.getUserId(),anonymousId:this.getAnonymousId()}),this.onLoadedCallback?.();}});}catch(t){console.error("RudderStack: Failed to initialize",t);}};this.identifyEvent=(e,t)=>{if(!this.has_initialized){console.warn("RudderStack: Cannot identify - not initialized");return}let i=this.getUserId();if(!i||i!==e)try{this.log("identifyEvent | identifying user",{user_id:e,traits:t}),this.analytics.identify(e,t||{}),this.has_identified=!0;}catch(a){console.error("RudderStack: Failed to identify user",a);}else this.log("identifyEvent | user already identified",{user_id:e}),this.has_identified=true;};this.pageView=(e,t="Deriv App",i,a)=>{if(!(!this.has_initialized||e===this.current_page))try{let n={...i&&{user_id:i},...a};this.log("pageView | tracking page view",{platform:t,current_page:e,properties:n}),this.analytics.page(t,e,n),this.current_page=e;}catch(n){console.error("RudderStack: Failed to track page view",n);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting RudderStack session"),this.analytics.reset(),this.has_identified=!1;}catch(e){console.error("RudderStack: Failed to reset",e);}};this.track=(e,t)=>{if(this.has_initialized)try{this.log("track | sending event to RudderStack",{event:e,payload:t}),this.analytics.track(e,t);}catch(i){console.warn("RudderStack: Failed to track event",i);}};this.onLoadedCallback=t,this.debug=i,this.init(e);}};o.getRudderStackInstance=(e,t,i=false)=>(o._instance||(o._instance=new o(e,t,i)),o._instance);var u=o;export{u as a};//# sourceMappingURL=chunk-BGCEXYPC.mjs.map
3
- //# sourceMappingURL=chunk-BGCEXYPC.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/providers/rudderstack.ts"],"names":["COOKIE_MAX_AGE_SECONDS","_RudderStack","RUDDERSTACK_KEY","onLoaded","debug","RudderAnalytics","createLogger","hostname","domain_name","domain","uuid","bytes","hex","byte","secureFlag","error","rudderstackDataplane","user_id","payload","currentUserId","current_page","platform","properties","pageProperties","event","err","RudderStack"],"mappings":";AAMA,IAAMA,CAAAA,CAAyB,CAAA,CAAI,GAAA,CAAM,EAAA,CAAK,EAAA,CAAK,EAAA,CAMtCC,CAAAA,CAAN,MAAMA,CAAY,CAWrB,WAAA,CAAYC,CAAAA,CAAyBC,CAAAA,CAAuBC,CAAAA,CAAQ,KAAA,CAAO,CAV3E,IAAA,CAAA,SAAA,CAAY,IAAIC,eAAAA,CAChB,I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KAAA,CAAAM,CAAAA,CAAO,QAAAN,CAAQ,CAAC,CAAA,CAGnE,IAAA,CAAK,SAAA,CAAU,KAAA,CAAMM,CAAAA,CAAiBN,CAAc,EACxD,CAAA,MAASO,CAAAA,CAAK,CACV,OAAA,CAAQ,IAAA,CAAK,oCAAA,CAAsCA,CAAG,EAC1D,CACJ,CAAA,CA7MI,IAAA,CAAK,gBAAA,CAAmBtB,CAAAA,CACxB,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,CAAKF,CAAe,EAC7B,CA2MJ,CAAA,CA1NaD,CAAAA,CAwBK,sBAAA,CAAyB,CACnCC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAQ,KAAA,IAEHH,CAAAA,CAAY,SAAA,GACbA,CAAAA,CAAY,SAAA,CAAY,IAAIA,CAAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAUC,CAAK,CAAA,CAAA,CAErEH,CAAAA,CAAY,SAAA,CAAA,KAhCdyB,CAAAA,CAANzB","file":"chunk-BGCEXYPC.mjs","sourcesContent":["import { RudderAnalytics } from '@rudderstack/analytics-js'\nimport type { TCoreAttributes, TAllEvents } from '../types'\nimport { rudderstackDataplane } from '../utils/urls'\nimport { createLogger } from '../utils/helpers'\n\n// Constants\nconst COOKIE_MAX_AGE_SECONDS = 2 * 365 * 24 * 60 * 60 // 2 years\n\n/**\n * RudderStack analytics wrapper with singleton pattern.\n * Handles user tracking, page views, and event analytics.\n */\nexport class RudderStack {\n analytics = new RudderAnalytics()\n has_identified = false\n has_initialized = false\n current_page = ''\n rudderstack_anonymous_cookie_key = 'rudder_anonymous_id'\n private static _instance: RudderStack\n private onLoadedCallback?: () => void\n private debug = false\n private log = createLogger('[RudderStack]', () => this.debug)\n\n constructor(RUDDERSTACK_KEY: string, onLoaded?: () => void, debug = false) {\n this.onLoadedCallback = onLoaded\n this.debug = debug\n this.init(RUDDERSTACK_KEY)\n }\n\n /**\n * Get or create the singleton instance of RudderStack\n * @param RUDDERSTACK_KEY - RudderStack write key\n * @param onLoaded - Optional callback when RudderStack is loaded\n * @param debug - Enable debug logging\n * @returns The RudderStack singleton instance\n */\n public static getRudderStackInstance = (\n RUDDERSTACK_KEY: string,\n onLoaded?: () => void,\n debug = false\n ): RudderStack => {\n if (!RudderStack._instance) {\n RudderStack._instance = new RudderStack(RUDDERSTACK_KEY, onLoaded, debug)\n }\n return RudderStack._instance\n }\n\n /**\n * Get the anonymous ID from cookies\n * @returns The anonymous ID or undefined if not found\n */\n getAnonymousId = (): string | undefined => {\n return document.cookie.match('(^|;)\\\\s*' + this.rudderstack_anonymous_cookie_key + '\\\\s*=\\\\s*([^;]+)')?.pop()\n }\n\n /**\n * Set anonymous ID cookie if it doesn't exist\n * Creates a secure cookie with proper domain and security attributes\n */\n setCookieIfNotExists = (): void => {\n const anonymous_id = this.getAnonymousId()\n\n if (!anonymous_id) {\n try {\n const hostname = window.location.hostname\n const external_domains = ['webflow.io']\n const is_external_domain = external_domains.some(domain => hostname.endsWith(domain))\n const domain_name = is_external_domain ? hostname : hostname.split('.').slice(-2).join('.')\n\n // Generate cryptographically secure UUID\n let uuid: string\n if (crypto?.randomUUID) {\n uuid = crypto.randomUUID()\n } else if (crypto?.getRandomValues) {\n // Fallback: Generate UUID v4 using crypto.getRandomValues\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n // Set version (4) and variant bits\n bytes[6] = (bytes[6]! & 0x0f) | 0x40\n bytes[8] = (bytes[8]! & 0x3f) | 0x80\n // Convert to UUID string format\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')\n uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n } else {\n // Crypto API not available - this should not happen in modern browsers\n throw new Error('Crypto API not available for secure random UUID generation')\n }\n\n const isSecure = window.location.protocol === 'https:'\n const secureFlag = isSecure ? '; Secure' : ''\n\n document.cookie = `${this.rudderstack_anonymous_cookie_key}=${uuid}; path=/; Domain=${domain_name}; max-age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax${secureFlag}`\n } catch (error) {\n console.warn('RudderStack: Failed to set anonymous ID cookie', error)\n }\n }\n }\n\n /**\n * Get the current user ID\n * @returns The user ID, null, or undefined if not identified\n */\n getUserId = () => this.analytics.getUserId()\n\n /**\n * Initialize RudderStack with the provided key\n * @param RUDDERSTACK_KEY - RudderStack write key\n */\n init = (RUDDERSTACK_KEY: string): void => {\n if (!RUDDERSTACK_KEY) {\n console.warn('RudderStack: Initialization skipped - no key provided')\n return\n }\n\n this.log('init | loading SDK', { dataplane: rudderstackDataplane })\n\n try {\n this.setCookieIfNotExists()\n\n this.analytics.load(RUDDERSTACK_KEY, rudderstackDataplane, {\n externalAnonymousIdCookieName: this.rudderstack_anonymous_cookie_key,\n storage: { type: 'localStorage' },\n // Performance optimizations\n lockIntegrationsVersion: true,\n onLoaded: () => {\n this.has_initialized = true\n this.has_identified = !!this.getUserId()\n this.log('init | SDK loaded successfully', {\n userId: this.getUserId(),\n anonymousId: this.getAnonymousId(),\n })\n this.onLoadedCallback?.()\n },\n })\n } catch (error) {\n console.error('RudderStack: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with RudderStack\n * Only identifies if user hasn't been identified yet\n * @param user_id - The user ID to identify\n * @param payload - Optional user traits (e.g., language, custom properties)\n */\n identifyEvent = (user_id: string, payload?: Record<string, any>): void => {\n if (!this.has_initialized) {\n console.warn('RudderStack: Cannot identify - not initialized')\n return\n }\n\n const currentUserId = this.getUserId()\n if (!currentUserId || currentUserId !== user_id) {\n try {\n this.log('identifyEvent | identifying user', { user_id, traits: payload })\n this.analytics.identify(user_id, payload || {})\n this.has_identified = true\n } catch (error) {\n console.error('RudderStack: Failed to identify user', error)\n }\n } else {\n this.log('identifyEvent | user already identified', { user_id })\n this.has_identified = true\n }\n }\n\n /**\n * Track a page view event\n * @param current_page - The page name/path\n * @param platform - The platform name (default: 'Deriv App')\n * @param user_id - The user ID\n * @param properties - Additional page properties\n */\n pageView = (\n current_page: string,\n platform = 'Deriv App',\n user_id: string,\n properties?: Record<string, unknown>\n ): void => {\n if (!this.has_initialized || current_page === this.current_page) return\n\n try {\n const pageProperties = {\n ...(user_id && { user_id }),\n ...properties,\n }\n\n this.log('pageView | tracking page view', { platform, current_page, properties: pageProperties })\n // Type assertion needed due to RudderStack's type definitions\n this.analytics.page(platform, current_page, pageProperties as any)\n this.current_page = current_page\n } catch (error) {\n console.error('RudderStack: Failed to track page view', error)\n }\n }\n\n /**\n * Reset the RudderStack instance\n * Clears user identification and resets tracking state\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting RudderStack session')\n this.analytics.reset()\n this.has_identified = false\n } catch (error) {\n console.error('RudderStack: Failed to reset', error)\n }\n }\n\n /**\n * Track a custom event with payload\n * Payload is pre-cleaned by analytics.ts using cleanObject before being passed here\n * @param event - The event name\n * @param payload - The event payload with core attributes\n */\n track = <T extends keyof TAllEvents>(event: T, payload: TAllEvents[T] & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('track | sending event to RudderStack', { event, payload })\n // Type assertion needed to match RudderStack's ApiObject type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.analytics.track(event as string, payload as any)\n } catch (err) {\n console.warn('RudderStack: Failed to track event', err)\n }\n }\n}\n"]}
@@ -1,3 +0,0 @@
1
- 'use strict';var chunkT4BXL6JM_js=require('./chunk-T4BXL6JM.js'),analyticsJs=require('@rudderstack/analytics-js');/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var k=2*365*24*60*60,o=class o{constructor(e,t,i=false){this.analytics=new analyticsJs.RudderAnalytics;this.has_identified=false;this.has_initialized=false;this.current_page="";this.rudderstack_anonymous_cookie_key="rudder_anonymous_id";this.debug=false;this.log=chunkT4BXL6JM_js.f("[RudderStack]",()=>this.debug);this.getAnonymousId=()=>document.cookie.match("(^|;)\\s*"+this.rudderstack_anonymous_cookie_key+"\\s*=\\s*([^;]+)")?.pop();this.setCookieIfNotExists=()=>{if(!this.getAnonymousId())try{let t=window.location.hostname,n=["webflow.io"].some(s=>t.endsWith(s))?t:t.split(".").slice(-2).join("."),d;if(crypto?.randomUUID)d=crypto.randomUUID();else if(crypto?.getRandomValues){let s=new Uint8Array(16);crypto.getRandomValues(s),s[6]=s[6]&15|64,s[8]=s[8]&63|128;let r=Array.from(s,y=>y.toString(16).padStart(2,"0")).join("");d=`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`;}else throw new Error("Crypto API not available for secure random UUID generation");let h=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${this.rudderstack_anonymous_cookie_key}=${d}; path=/; Domain=${n}; max-age=${k}; SameSite=Lax${h}`;}catch(t){console.warn("RudderStack: Failed to set anonymous ID cookie",t);}};this.getUserId=()=>this.analytics.getUserId();this.init=e=>{if(!e){console.warn("RudderStack: Initialization skipped - no key provided");return}this.log("init | loading SDK",{dataplane:chunkT4BXL6JM_js.b});try{this.setCookieIfNotExists(),this.analytics.load(e,chunkT4BXL6JM_js.b,{externalAnonymousIdCookieName:this.rudderstack_anonymous_cookie_key,storage:{type:"localStorage"},lockIntegrationsVersion:!0,onLoaded:()=>{this.has_initialized=!0,this.has_identified=!!this.getUserId(),this.log("init | SDK loaded successfully",{userId:this.getUserId(),anonymousId:this.getAnonymousId()}),this.onLoadedCallback?.();}});}catch(t){console.error("RudderStack: Failed to initialize",t);}};this.identifyEvent=(e,t)=>{if(!this.has_initialized){console.warn("RudderStack: Cannot identify - not initialized");return}let i=this.getUserId();if(!i||i!==e)try{this.log("identifyEvent | identifying user",{user_id:e,traits:t}),this.analytics.identify(e,t||{}),this.has_identified=!0;}catch(a){console.error("RudderStack: Failed to identify user",a);}else this.log("identifyEvent | user already identified",{user_id:e}),this.has_identified=true;};this.pageView=(e,t="Deriv App",i,a)=>{if(!(!this.has_initialized||e===this.current_page))try{let n={...i&&{user_id:i},...a};this.log("pageView | tracking page view",{platform:t,current_page:e,properties:n}),this.analytics.page(t,e,n),this.current_page=e;}catch(n){console.error("RudderStack: Failed to track page view",n);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting RudderStack session"),this.analytics.reset(),this.has_identified=!1;}catch(e){console.error("RudderStack: Failed to reset",e);}};this.track=(e,t)=>{if(this.has_initialized)try{this.log("track | sending event to RudderStack",{event:e,payload:t}),this.analytics.track(e,t);}catch(i){console.warn("RudderStack: Failed to track event",i);}};this.onLoadedCallback=t,this.debug=i,this.init(e);}};o.getRudderStackInstance=(e,t,i=false)=>(o._instance||(o._instance=new o(e,t,i)),o._instance);var u=o;exports.a=u;//# sourceMappingURL=chunk-GVFVS6VE.js.map
3
- //# sourceMappingURL=chunk-GVFVS6VE.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/providers/rudderstack.ts"],"names":["COOKIE_MAX_AGE_SECONDS","_RudderStack","RUDDERSTACK_KEY","onLoaded","debug","RudderAnalytics","createLogger","hostname","domain_name","domain","uuid","bytes","hex","byte","secureFlag","error","rudderstackDataplane","user_id","payload","currentUserId","current_page","platform","properties","pageProperties","event","err","RudderStack"],"mappings":";AAMA,IAAMA,CAAAA,CAAyB,CAAA,CAAI,GAAA,CAAM,EAAA,CAAK,EAAA,CAAK,EAAA,CAMtCC,CAAAA,CAAN,MAAMA,CAAY,CAWrB,WAAA,CAAYC,CAAAA,CAAyBC,CAAAA,CAAuBC,CAAAA,CAAQ,KAAA,CAAO,CAV3E,IAAA,CAAA,SAAA,CAAY,IAAIC,2BAAAA,CAChB,IAAA,CAAA,cAAA,CAAiB,KAAA,CACjB,IAAA,CAAA,eAAA,CAAkB,KAAA,CAClB,IAAA,CAAA,YAAA,CAAe,GACf,IAAA,CAAA,gCAAA,CAAmC,qBAAA,CAGnC,IAAA,CAAQ,KAAA,CAAQ,KAAA,CAChB,IAAA,CAAQ,GAAA,CAAMC,kBAAAA,CAAa,e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,CA7MI,IAAA,CAAK,gBAAA,CAAmBtB,CAAAA,CACxB,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,CAAKF,CAAe,EAC7B,CA2MJ,CAAA,CA1NaD,CAAAA,CAwBK,sBAAA,CAAyB,CACnCC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAQ,KAAA,IAEHH,CAAAA,CAAY,SAAA,GACbA,CAAAA,CAAY,SAAA,CAAY,IAAIA,CAAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAUC,CAAK,CAAA,CAAA,CAErEH,CAAAA,CAAY,SAAA,CAAA,KAhCdyB,CAAAA,CAANzB","file":"chunk-GVFVS6VE.js","sourcesContent":["import { RudderAnalytics } from '@rudderstack/analytics-js'\nimport type { TCoreAttributes, TAllEvents } from '../types'\nimport { rudderstackDataplane } from '../utils/urls'\nimport { createLogger } from '../utils/helpers'\n\n// Constants\nconst COOKIE_MAX_AGE_SECONDS = 2 * 365 * 24 * 60 * 60 // 2 years\n\n/**\n * RudderStack analytics wrapper with singleton pattern.\n * Handles user tracking, page views, and event analytics.\n */\nexport class RudderStack {\n analytics = new RudderAnalytics()\n has_identified = false\n has_initialized = false\n current_page = ''\n rudderstack_anonymous_cookie_key = 'rudder_anonymous_id'\n private static _instance: RudderStack\n private onLoadedCallback?: () => void\n private debug = false\n private log = createLogger('[RudderStack]', () => this.debug)\n\n constructor(RUDDERSTACK_KEY: string, onLoaded?: () => void, debug = false) {\n this.onLoadedCallback = onLoaded\n this.debug = debug\n this.init(RUDDERSTACK_KEY)\n }\n\n /**\n * Get or create the singleton instance of RudderStack\n * @param RUDDERSTACK_KEY - RudderStack write key\n * @param onLoaded - Optional callback when RudderStack is loaded\n * @param debug - Enable debug logging\n * @returns The RudderStack singleton instance\n */\n public static getRudderStackInstance = (\n RUDDERSTACK_KEY: string,\n onLoaded?: () => void,\n debug = false\n ): RudderStack => {\n if (!RudderStack._instance) {\n RudderStack._instance = new RudderStack(RUDDERSTACK_KEY, onLoaded, debug)\n }\n return RudderStack._instance\n }\n\n /**\n * Get the anonymous ID from cookies\n * @returns The anonymous ID or undefined if not found\n */\n getAnonymousId = (): string | undefined => {\n return document.cookie.match('(^|;)\\\\s*' + this.rudderstack_anonymous_cookie_key + '\\\\s*=\\\\s*([^;]+)')?.pop()\n }\n\n /**\n * Set anonymous ID cookie if it doesn't exist\n * Creates a secure cookie with proper domain and security attributes\n */\n setCookieIfNotExists = (): void => {\n const anonymous_id = this.getAnonymousId()\n\n if (!anonymous_id) {\n try {\n const hostname = window.location.hostname\n const external_domains = ['webflow.io']\n const is_external_domain = external_domains.some(domain => hostname.endsWith(domain))\n const domain_name = is_external_domain ? hostname : hostname.split('.').slice(-2).join('.')\n\n // Generate cryptographically secure UUID\n let uuid: string\n if (crypto?.randomUUID) {\n uuid = crypto.randomUUID()\n } else if (crypto?.getRandomValues) {\n // Fallback: Generate UUID v4 using crypto.getRandomValues\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n // Set version (4) and variant bits\n bytes[6] = (bytes[6]! & 0x0f) | 0x40\n bytes[8] = (bytes[8]! & 0x3f) | 0x80\n // Convert to UUID string format\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')\n uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n } else {\n // Crypto API not available - this should not happen in modern browsers\n throw new Error('Crypto API not available for secure random UUID generation')\n }\n\n const isSecure = window.location.protocol === 'https:'\n const secureFlag = isSecure ? '; Secure' : ''\n\n document.cookie = `${this.rudderstack_anonymous_cookie_key}=${uuid}; path=/; Domain=${domain_name}; max-age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax${secureFlag}`\n } catch (error) {\n console.warn('RudderStack: Failed to set anonymous ID cookie', error)\n }\n }\n }\n\n /**\n * Get the current user ID\n * @returns The user ID, null, or undefined if not identified\n */\n getUserId = () => this.analytics.getUserId()\n\n /**\n * Initialize RudderStack with the provided key\n * @param RUDDERSTACK_KEY - RudderStack write key\n */\n init = (RUDDERSTACK_KEY: string): void => {\n if (!RUDDERSTACK_KEY) {\n console.warn('RudderStack: Initialization skipped - no key provided')\n return\n }\n\n this.log('init | loading SDK', { dataplane: rudderstackDataplane })\n\n try {\n this.setCookieIfNotExists()\n\n this.analytics.load(RUDDERSTACK_KEY, rudderstackDataplane, {\n externalAnonymousIdCookieName: this.rudderstack_anonymous_cookie_key,\n storage: { type: 'localStorage' },\n // Performance optimizations\n lockIntegrationsVersion: true,\n onLoaded: () => {\n this.has_initialized = true\n this.has_identified = !!this.getUserId()\n this.log('init | SDK loaded successfully', {\n userId: this.getUserId(),\n anonymousId: this.getAnonymousId(),\n })\n this.onLoadedCallback?.()\n },\n })\n } catch (error) {\n console.error('RudderStack: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with RudderStack\n * Only identifies if user hasn't been identified yet\n * @param user_id - The user ID to identify\n * @param payload - Optional user traits (e.g., language, custom properties)\n */\n identifyEvent = (user_id: string, payload?: Record<string, any>): void => {\n if (!this.has_initialized) {\n console.warn('RudderStack: Cannot identify - not initialized')\n return\n }\n\n const currentUserId = this.getUserId()\n if (!currentUserId || currentUserId !== user_id) {\n try {\n this.log('identifyEvent | identifying user', { user_id, traits: payload })\n this.analytics.identify(user_id, payload || {})\n this.has_identified = true\n } catch (error) {\n console.error('RudderStack: Failed to identify user', error)\n }\n } else {\n this.log('identifyEvent | user already identified', { user_id })\n this.has_identified = true\n }\n }\n\n /**\n * Track a page view event\n * @param current_page - The page name/path\n * @param platform - The platform name (default: 'Deriv App')\n * @param user_id - The user ID\n * @param properties - Additional page properties\n */\n pageView = (\n current_page: string,\n platform = 'Deriv App',\n user_id: string,\n properties?: Record<string, unknown>\n ): void => {\n if (!this.has_initialized || current_page === this.current_page) return\n\n try {\n const pageProperties = {\n ...(user_id && { user_id }),\n ...properties,\n }\n\n this.log('pageView | tracking page view', { platform, current_page, properties: pageProperties })\n // Type assertion needed due to RudderStack's type definitions\n this.analytics.page(platform, current_page, pageProperties as any)\n this.current_page = current_page\n } catch (error) {\n console.error('RudderStack: Failed to track page view', error)\n }\n }\n\n /**\n * Reset the RudderStack instance\n * Clears user identification and resets tracking state\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting RudderStack session')\n this.analytics.reset()\n this.has_identified = false\n } catch (error) {\n console.error('RudderStack: Failed to reset', error)\n }\n }\n\n /**\n * Track a custom event with payload\n * Payload is pre-cleaned by analytics.ts using cleanObject before being passed here\n * @param event - The event name\n * @param payload - The event payload with core attributes\n */\n track = <T extends keyof TAllEvents>(event: T, payload: TAllEvents[T] & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('track | sending event to RudderStack', { event, payload })\n // Type assertion needed to match RudderStack's ApiObject type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.analytics.track(event as string, payload as any)\n } catch (err) {\n console.warn('RudderStack: Failed to track event', err)\n }\n }\n}\n"]}