@deriv-com/analytics 1.39.8 → 1.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- export { P as Posthog } from '../../posthog-Zmf5OhfF.mjs';
1
+ export { P as Posthog } from '../../posthog-BqcxWQRm.mjs';
2
2
  import 'posthog-js';
@@ -1,2 +1,2 @@
1
- export { P as Posthog } from '../../posthog-Zmf5OhfF.js';
1
+ export { P as Posthog } from '../../posthog-BqcxWQRm.js';
2
2
  import 'posthog-js';
@@ -1,3 +1,3 @@
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 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
1
+ 'use strict';var chunkT4BXL6JM_js=require('../../chunk-T4BXL6JM.js'),a=require('posthog-js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var a__default=/*#__PURE__*/_interopDefault(a);/* @deriv-com/analytics - NPM Package - Built with tsup */
2
+ var c=class c{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 r=window.location.hostname,n=r.split("."),s=n.length>=2?`.${n.slice(-2).join(".")}`:r;o.forEach(e=>{[s,r,""].forEach(l=>{let y=l?`; Domain=${l}`:"";document.cookie=`${e}=; path=/${y}; max-age=0; SameSite=Lax`;});let d=!document.cookie.split(";").some(l=>l.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 r=i||chunkT4BXL6JM_js.d();this.log("init | loading PostHog SDK",{api_host:r});let n={api_host:r,ui_host:chunkT4BXL6JM_js.c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...o.session_recording},before_send:s=>{if(typeof window>"u")return null;let e=window.location.hostname;if(e==="localhost"||e==="127.0.0.1")return s;let d=chunkT4BXL6JM_js.e.some(l=>e.endsWith(`.${l}`)||e===l);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:e}),d?s:null},...o};a__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 a__default.default._isIdentified=="function"?a__default.default._isIdentified():this.has_identified;t&&!o?(this.log("identifyEvent | identifying user",{user_id:t,traits:i}),a__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"),a__default.default.reset(),this.has_identified=!1;}catch(t){console.error("Posthog: Failed to reset",t);}};this.backfillPersonProperties=({user_id:t,email:i,language:o,country_of_residence:r})=>{if(!(!this.has_initialized||!t))try{let n=a__default.default.get_property("$stored_person_properties")??{},s={};n.client_id||(s.client_id=t),i&&n.is_internal===void 0&&(s.is_internal=chunkT4BXL6JM_js.g(i)),o&&!n.language&&(s.language=o),r&&!n.country_of_residence&&(s.country_of_residence=r),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:t,updates:s}),a__default.default.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:t,country_of_residence:r});}catch(n){console.error("Posthog: Failed to backfill person properties",n);}};this.capture=(t,i)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:t,properties:i}),a__default.default.capture(t,i);}catch(o){console.error("Posthog: Failed to capture event",o);}};this.options=t,this.debug=i,this.init();}};c.getPosthogInstance=(t,i=false)=>(c._instance||(c._instance=new c(t,i)),c._instance);var P=c;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","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":";AAoBO,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,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,CAAA,CAAE,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,CAAKD,CAAAA,CAErFH,EAAa,OAAA,CAAQE,CAAAA,EAAQ,CAExB,CAACG,CAAAA,C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":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\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>): 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","language","country_of_residence","storedProperties","updates","isInternalEmail","event_name","properties","Posthog"],"mappings":";AAoBO,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,EAAMD,CAAa,CAAA,QAAA,CAAA,CACvCE,CAAAA,CAAe,QAAA,CAAS,MAAA,CACzB,KAAA,CAAM,GAAG,CAAA,CACT,GAAA,CAAIC,CAAAA,EAAKA,CAAAA,CAAE,IAAA,EAAK,CAAE,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA,EAAK,EAAE,CAAA,CACrC,MA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AC,CAAW,CAAC,CAAA,CACzEZ,kBAAAA,CAAQ,OAAA,CAAQW,CAAAA,CAAYC,CAAU,EAC1C,CAAA,MAASX,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CA9NI,IAAA,CAAK,QAAU1B,CAAAA,CACf,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,GACT,CA4NJ,EAxOaF,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,KAxBVuC,CAAAA,CAANvC","file":"index.js","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\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.language - The user's language (BCP 47 tag, e.g. \"en-GB\")\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n language,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n language?: 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 (language && !storedProperties.language) {\n updates.language = language\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>): 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,d,e,c,g}from'../../chunk-TE3DYZVQ.mjs';import r from'posthog-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
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
1
+ import {f,d,e,c as c$1,g}from'../../chunk-TE3DYZVQ.mjs';import a from'posthog-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
+ var c=class c{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 r=window.location.hostname,n=r.split("."),s=n.length>=2?`.${n.slice(-2).join(".")}`:r;o.forEach(e=>{[s,r,""].forEach(l=>{let y=l?`; Domain=${l}`:"";document.cookie=`${e}=; path=/${y}; max-age=0; SameSite=Lax`;});let d=!document.cookie.split(";").some(l=>l.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 r=i||d();this.log("init | loading PostHog SDK",{api_host:r});let n={api_host:r,ui_host:c$1,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...o.session_recording},before_send:s=>{if(typeof window>"u")return null;let e$1=window.location.hostname;if(e$1==="localhost"||e$1==="127.0.0.1")return s;let d=e.some(l=>e$1.endsWith(`.${l}`)||e$1===l);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:e$1}),d?s:null},...o};a.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 a._isIdentified=="function"?a._isIdentified():this.has_identified;t&&!o?(this.log("identifyEvent | identifying user",{user_id:t,traits:i}),a.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"),a.reset(),this.has_identified=!1;}catch(t){console.error("Posthog: Failed to reset",t);}};this.backfillPersonProperties=({user_id:t,email:i,language:o,country_of_residence:r})=>{if(!(!this.has_initialized||!t))try{let n=a.get_property("$stored_person_properties")??{},s={};n.client_id||(s.client_id=t),i&&n.is_internal===void 0&&(s.is_internal=g(i)),o&&!n.language&&(s.language=o),r&&!n.country_of_residence&&(s.country_of_residence=r),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:t,updates:s}),a.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:t,country_of_residence:r});}catch(n){console.error("Posthog: Failed to backfill person properties",n);}};this.capture=(t,i)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:t,properties:i}),a.capture(t,i);}catch(o){console.error("Posthog: Failed to capture event",o);}};this.options=t,this.debug=i,this.init();}};c.getPosthogInstance=(t,i=false)=>(c._instance||(c._instance=new c(t,i)),c._instance);var P=c;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","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":";AAoBO,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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AA,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.mjs","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\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>): 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","language","country_of_residence","storedProperties","updates","isInternalEmail","event_name","properties","Posthog"],"mappings":";AAoBO,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,C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CACJ,CAAA,CASA,aAAU,CAACU,CAAAA,CAAoBC,CAAAA,GAA2C,CACtE,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,GAAA,CAAI,oCAAA,CAAsC,CAAE,UAAA,CAAAD,CAAAA,CAAY,UAAA,CAAAC,CAAW,CAAC,CAAA,CACzEZ,CAAAA,CAAQ,OAAA,CAAQW,CAAAA,CAAYC,CAAU,EAC1C,CAAA,MAASX,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CA9NI,IAAA,CAAK,QAAU1B,CAAAA,CACf,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,GACT,CA4NJ,EAxOaF,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,KAxBVuC,CAAAA,CAANvC","file":"index.mjs","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\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.language - The user's language (BCP 47 tag, e.g. \"en-GB\")\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n language,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n language?: 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 (language && !storedProperties.language) {\n updates.language = language\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>): 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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deriv-com/analytics",
3
- "version": "1.39.8",
3
+ "version": "1.40.0",
4
4
  "description": "Comprehensive analytics package for Deriv applications. Provides unified event tracking, A/B testing, and user analytics through RudderStack, PostHog and GrowthBook integrations with built-in caching and offline support.",
5
5
  "keywords": [
6
6
  "rudderstack",