@deriv-com/analytics 1.39.3 → 1.39.5
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.
- package/dist/browser/analytics.bundle.global.js +12 -12
- package/dist/browser/analytics.bundle.global.js.map +1 -1
- package/dist/browser/analytics.esm.mjs +1 -1
- package/dist/browser/analytics.esm.mjs.map +1 -1
- package/dist/chunk-5PFWZVJN.mjs +3 -0
- package/dist/chunk-5PFWZVJN.mjs.map +1 -0
- package/dist/chunk-BGCEXYPC.mjs +3 -0
- package/dist/chunk-BGCEXYPC.mjs.map +1 -0
- package/dist/chunk-F3U33XPR.mjs +9 -0
- package/dist/chunk-F3U33XPR.mjs.map +1 -0
- package/dist/chunk-GVFVS6VE.js +3 -0
- package/dist/chunk-GVFVS6VE.js.map +1 -0
- package/dist/chunk-NCHU4435.js +3 -0
- package/dist/chunk-NCHU4435.js.map +1 -0
- package/dist/{chunk-FY3NPDUL.mjs → chunk-OMGH3V7W.mjs} +2 -2
- package/dist/chunk-T4BXL6JM.js +4 -0
- package/dist/chunk-T4BXL6JM.js.map +1 -0
- package/dist/chunk-TE3DYZVQ.mjs +4 -0
- package/dist/chunk-TE3DYZVQ.mjs.map +1 -0
- package/dist/{growthbook-IRLKT4KH.mjs → growthbook-FZV644NE.mjs} +2 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/metafile-iife.json +1 -1
- package/dist/posthog-ZW7SFGPQ.mjs +6 -0
- package/dist/posthog-ZW7SFGPQ.mjs.map +1 -0
- package/dist/providers/growthbook/index.js +2 -2
- package/dist/providers/growthbook/index.mjs +2 -2
- package/dist/providers/posthog/index.js +2 -2
- package/dist/providers/posthog/index.js.map +1 -1
- package/dist/providers/posthog/index.mjs +2 -2
- package/dist/providers/posthog/index.mjs.map +1 -1
- package/dist/providers/rudderstack/index.js +1 -1
- package/dist/providers/rudderstack/index.mjs +1 -1
- package/dist/utils/analytics-cache/index.d.mts +4 -12
- package/dist/utils/analytics-cache/index.d.ts +4 -12
- package/dist/utils/analytics-cache/index.js +1 -1
- package/dist/utils/analytics-cache/index.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-44P2MMGV.mjs +0 -3
- package/dist/chunk-44P2MMGV.mjs.map +0 -1
- package/dist/chunk-DWOZQCV4.mjs +0 -3
- package/dist/chunk-DWOZQCV4.mjs.map +0 -1
- package/dist/chunk-GGU2UVKH.mjs +0 -4
- package/dist/chunk-GGU2UVKH.mjs.map +0 -1
- package/dist/chunk-GZBZB5MW.js +0 -3
- package/dist/chunk-GZBZB5MW.js.map +0 -1
- package/dist/chunk-J3V5QNIH.js +0 -4
- package/dist/chunk-J3V5QNIH.js.map +0 -1
- package/dist/chunk-UG2YL4OB.mjs +0 -9
- package/dist/chunk-UG2YL4OB.mjs.map +0 -1
- package/dist/chunk-Y3QT7NAG.js +0 -3
- package/dist/chunk-Y3QT7NAG.js.map +0 -1
- package/dist/posthog-PBG3EMGB.mjs +0 -6
- package/dist/posthog-PBG3EMGB.mjs.map +0 -1
- /package/dist/{chunk-FY3NPDUL.mjs.map → chunk-OMGH3V7W.mjs.map} +0 -0
- /package/dist/{growthbook-IRLKT4KH.mjs.map → growthbook-FZV644NE.mjs.map} +0 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
var i=class i{constructor(t,e,o={},n=false){this.analytics=new analyticsJs.RudderAnalytics;this.isLoaded=false;this.status=void 0;this.debug=false;this.log=
|
|
1
|
+
'use strict';var chunkT4BXL6JM_js=require('../../chunk-T4BXL6JM.js'),growthbook=require('@growthbook/growthbook'),analyticsJs=require('@rudderstack/analytics-js');/* @deriv-com/analytics - NPM Package - Built with tsup */
|
|
2
|
+
var i=class i{constructor(t,e,o={},n=false){this.analytics=new analyticsJs.RudderAnalytics;this.isLoaded=false;this.status=void 0;this.debug=false;this.log=chunkT4BXL6JM_js.f("[GrowthBook]",()=>this.debug);this.setAttributes=({id:t,country:e,user_language:o,device_language:n,device_type:s,utm_source:r,utm_medium:a,utm_campaign:d,is_authorised:h,url:u,domain:w,utm_content:l,residence_country:f,loggedIn:c,network_type:g,network_downlink:k,user_id:b,anonymous_id:p,account_mode:G})=>{let v={...this.GrowthBook.getAttributes(),id:t,...b!==void 0&&{user_id:b},...p!==void 0&&{anonymous_id:p},...e!==void 0&&{country:e},...f!==void 0&&{residence_country:f},...o!==void 0&&{user_language:o},...n!==void 0&&{device_language:n},...s!==void 0&&{device_type:s},...r!==void 0&&{utm_source:r},...a!==void 0&&{utm_medium:a},...d!==void 0&&{utm_campaign:d},...h!==void 0&&{is_authorised:h},...u!==void 0&&{url:u},...w!==void 0&&{domain:w},...l!==void 0&&{utm_content:l},...c!==void 0&&{loggedIn:c},...g!==void 0&&{network_type:g},...k!==void 0&&{network_downlink:k},...G!==void 0&&{account_mode:G}};this.log("setAttributes | updating GrowthBook attributes",v),this.GrowthBook.setAttributes(v);};this.getFeatureValue=(t,e)=>{let o=this.GrowthBook.getFeatureValue(t,e);return this.log("getFeatureValue",{key:t,value:o,defaultValue:e}),o};this.getStatus=async()=>(await this.waitForIsLoaded(),{isLoaded:this.isLoaded,status:this.status});this.getFeatureState=t=>{let e=this.GrowthBook.evalFeature(t);return this.log("getFeatureState",{id:t,result:e}),e};this.setUrl=t=>{this.log("setUrl",{href:t}),this.GrowthBook.setURL(t);};this.isOn=t=>{let e=this.GrowthBook.isOn(t);return this.log("isOn",{key:t,result:e}),e};this.init=async()=>{this.log("init | initializing GrowthBook SDK");let t=await this.GrowthBook.init({timeout:2e3,streaming:true}).catch(()=>{});this.status=t,this.isLoaded=true,this.log("init | GrowthBook SDK loaded",{status:t});};this.destroy=()=>{this.GrowthBook.destroy(),this.isLoaded=false,this.status=void 0;};this.debug=n;let s=typeof window<"u"?window.location.hostname.includes("localhost"):false;this.GrowthBook=new growthbook.GrowthBook({apiHost:chunkT4BXL6JM_js.a,clientKey:t,decryptionKey:e,antiFlicker:false,navigateDelay:0,antiFlickerTimeout:3500,subscribeToChanges:true,enableDevMode:s,trackingCallback:(r,a)=>{this.log("trackingCallback | experiment viewed",{experiment_id:r.key,variation_id:a.variationId}),typeof window<"u"&&window.dataLayer&&window.dataLayer.push({event:"experiment_viewed",event_category:"experiment",rudder_anonymous_id:this.analytics.getAnonymousId(),experiment_id:r.key,variation_id:a.variationId}),this.analytics.track("experiment_viewed",{experimentId:r.key,variationId:a.variationId});},...o}),this.init();}reapplyExperiment(t){let e=t??(typeof window<"u"?window.location.href:"");this.GrowthBook.setURL(e);}waitForIsLoaded(t=1e4){return new Promise((e,o)=>{let n=Date.now(),s=setInterval(()=>{this.isLoaded?(clearInterval(s),e()):Date.now()-n>=t&&(clearInterval(s),o(new Error("GrowthBook initialization timeout")));},100);})}};i.getGrowthBookInstance=(t,e,o,n=false)=>i._instance?(typeof window<"u"&&console.warn&&console.warn("GrowthBook instance already exists. Ignoring new initialization parameters."),i._instance):(i._instance=new i(t,e??"",o,n),i._instance),i.resetInstance=()=>{i._instance&&(i._instance.destroy(),i._instance=void 0);};var m=i;exports.Growthbook=m;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
var i=class i{constructor(t,e,o={},n=false){this.analytics=new RudderAnalytics;this.isLoaded=false;this.status=void 0;this.debug=false;this.log=
|
|
1
|
+
import {f,a}from'../../chunk-TE3DYZVQ.mjs';import {GrowthBook}from'@growthbook/growthbook';import {RudderAnalytics}from'@rudderstack/analytics-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
|
|
2
|
+
var i=class i{constructor(t,e,o={},n=false){this.analytics=new RudderAnalytics;this.isLoaded=false;this.status=void 0;this.debug=false;this.log=f("[GrowthBook]",()=>this.debug);this.setAttributes=({id:t,country:e,user_language:o,device_language:n,device_type:s,utm_source:r,utm_medium:a,utm_campaign:d,is_authorised:h,url:u,domain:w,utm_content:l,residence_country:f,loggedIn:c,network_type:g,network_downlink:k,user_id:b,anonymous_id:p,account_mode:G})=>{let v={...this.GrowthBook.getAttributes(),id:t,...b!==void 0&&{user_id:b},...p!==void 0&&{anonymous_id:p},...e!==void 0&&{country:e},...f!==void 0&&{residence_country:f},...o!==void 0&&{user_language:o},...n!==void 0&&{device_language:n},...s!==void 0&&{device_type:s},...r!==void 0&&{utm_source:r},...a!==void 0&&{utm_medium:a},...d!==void 0&&{utm_campaign:d},...h!==void 0&&{is_authorised:h},...u!==void 0&&{url:u},...w!==void 0&&{domain:w},...l!==void 0&&{utm_content:l},...c!==void 0&&{loggedIn:c},...g!==void 0&&{network_type:g},...k!==void 0&&{network_downlink:k},...G!==void 0&&{account_mode:G}};this.log("setAttributes | updating GrowthBook attributes",v),this.GrowthBook.setAttributes(v);};this.getFeatureValue=(t,e)=>{let o=this.GrowthBook.getFeatureValue(t,e);return this.log("getFeatureValue",{key:t,value:o,defaultValue:e}),o};this.getStatus=async()=>(await this.waitForIsLoaded(),{isLoaded:this.isLoaded,status:this.status});this.getFeatureState=t=>{let e=this.GrowthBook.evalFeature(t);return this.log("getFeatureState",{id:t,result:e}),e};this.setUrl=t=>{this.log("setUrl",{href:t}),this.GrowthBook.setURL(t);};this.isOn=t=>{let e=this.GrowthBook.isOn(t);return this.log("isOn",{key:t,result:e}),e};this.init=async()=>{this.log("init | initializing GrowthBook SDK");let t=await this.GrowthBook.init({timeout:2e3,streaming:true}).catch(()=>{});this.status=t,this.isLoaded=true,this.log("init | GrowthBook SDK loaded",{status:t});};this.destroy=()=>{this.GrowthBook.destroy(),this.isLoaded=false,this.status=void 0;};this.debug=n;let s=typeof window<"u"?window.location.hostname.includes("localhost"):false;this.GrowthBook=new GrowthBook({apiHost:a,clientKey:t,decryptionKey:e,antiFlicker:false,navigateDelay:0,antiFlickerTimeout:3500,subscribeToChanges:true,enableDevMode:s,trackingCallback:(r,a)=>{this.log("trackingCallback | experiment viewed",{experiment_id:r.key,variation_id:a.variationId}),typeof window<"u"&&window.dataLayer&&window.dataLayer.push({event:"experiment_viewed",event_category:"experiment",rudder_anonymous_id:this.analytics.getAnonymousId(),experiment_id:r.key,variation_id:a.variationId}),this.analytics.track("experiment_viewed",{experimentId:r.key,variationId:a.variationId});},...o}),this.init();}reapplyExperiment(t){let e=t??(typeof window<"u"?window.location.href:"");this.GrowthBook.setURL(e);}waitForIsLoaded(t=1e4){return new Promise((e,o)=>{let n=Date.now(),s=setInterval(()=>{this.isLoaded?(clearInterval(s),e()):Date.now()-n>=t&&(clearInterval(s),o(new Error("GrowthBook initialization timeout")));},100);})}};i.getGrowthBookInstance=(t,e,o,n=false)=>i._instance?(typeof window<"u"&&console.warn&&console.warn("GrowthBook instance already exists. Ignoring new initialization parameters."),i._instance):(i._instance=new i(t,e??"",o,n),i._instance),i.resetInstance=()=>{i._instance&&(i._instance.destroy(),i._instance=void 0);};var m=i;export{m as Growthbook};//# sourceMappingURL=index.mjs.map
|
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
var n=class n{constructor(i,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=
|
|
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
|
|
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,KAAK,OAAA,CAE/C,GAAI,CAACF,CAAAA,CAAQ,CACT,OAAA,CAAQ,KAAK,8BAA8B,CAAA,CAC3C,MACJ,CAEA,IAAMG,EAAkBF,CAAAA,EAAYG,kBAAAA,EAAkB,CACtD,IAAA,CAAK,GAAA,CAAI,4BAAA,CAA8B,CAAE,QAAA,CAAUD,CAAgB,CAAC,CAAA,CAEpE,IAAME,EAAgC,CAClC,QAAA,CAAUF,CAAAA,CACV,OAAA,CAASG,kBAAAA,CACT,WAAA,CAAa,GACb,gBAAA,CAAkB,gBAAA,CAClB,kBAAmB,CACf,wBAAA,CAA0B,GAC1B,2BAAA,CAA6B,GAAA,CAC7B,GAAGJ,CAAAA,CAAO,iBACd,CAAA,C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E,OAAA,CAAAN,CAAAA,CAAS,OAAA,CAAAM,CAAQ,CAAC,CAAA,CACzFR,mBAAQ,mBAAA,CAAoBQ,CAAO,GAEnC,IAAA,CAAK,GAAA,CAAI,0EAAA,CAAuE,CAC5E,OAAA,CAAAN,CAAAA,CACA,qBAAAI,CACJ,CAAC,EAET,CAAA,MAASL,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,+CAAA,CAAiDA,CAAK,EACxE,CACJ,EASA,IAAA,CAAA,OAAA,CAAU,CAACS,CAAAA,CAAoBC,CAAAA,GAAsE,CACjG,GAAK,KAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,GAAA,CAAI,oCAAA,CAAsC,CAAE,UAAA,CAAAD,CAAAA,CAAY,WAAAC,CAAW,CAAC,EACzEX,kBAAAA,CAAQ,OAAA,CAAQU,CAAAA,CAAYC,CAAU,EAC1C,CAAA,MAASV,EAAO,CACZ,OAAA,CAAQ,MAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CArLI,IAAA,CAAK,OAAA,CAAUhB,CAAAA,CACf,IAAA,CAAK,MAAQC,CAAAA,CACb,IAAA,CAAK,OACT,CAmLJ,EA/LaF,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 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","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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AAAA,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,3 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
var n=class n{constructor(i,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=
|
|
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
|
|
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,CAAQ,GAAA,CAAMC,CAAAA,CAAa,WAAA,CAAa,IAAM,KAAK,KAAK,CAAA,CAyBxD,UAAO,IAAY,CACf,GAAI,CACA,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAAC,EAAU,MAAA,CAAAC,GAAAA,CAAS,EAAG,CAAA,CAAI,KAAK,OAAA,CAE/C,GAAI,CAACF,CAAAA,CAAQ,CACT,OAAA,CAAQ,KAAK,8BAA8B,CAAA,CAC3C,MACJ,CAEA,IAAMG,EAAkBF,CAAAA,EAAYG,CAAAA,EAAkB,CACtD,IAAA,CAAK,GAAA,CAAI,4BAAA,CAA8B,CAAE,QAAA,CAAUD,CAAgB,CAAC,CAAA,CAEpE,IAAME,EAAgC,CAClC,QAAA,CAAUF,CAAAA,CACV,OAAA,CAASG,CAAAA,CACT,WAAA,CAAa,GACb,gBAAA,CAAkB,gBAAA,CAClB,kBAAmB,CACf,wBAAA,CAA0B,GAC1B,2BAAA,CAA6B,GAAA,CAC7B,GAAGJ,GAAAA,CAAO,iBACd,CAAA,CACA,YAAaK,CAAAA,E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OAAA,CAAAM,CAAQ,CAAC,CAAA,CACzFR,EAAQ,mBAAA,CAAoBQ,CAAO,GAEnC,IAAA,CAAK,GAAA,CAAI,0EAAA,CAAuE,CAC5E,OAAA,CAAAN,CAAAA,CACA,qBAAAI,CACJ,CAAC,EAET,CAAA,MAASL,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,+CAAA,CAAiDA,CAAK,EACxE,CACJ,EASA,IAAA,CAAA,OAAA,CAAU,CAACS,CAAAA,CAAoBC,CAAAA,GAAsE,CACjG,GAAK,KAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,GAAA,CAAI,oCAAA,CAAsC,CAAE,UAAA,CAAAD,CAAAA,CAAY,WAAAC,CAAW,CAAC,EACzEX,CAAAA,CAAQ,OAAA,CAAQU,CAAAA,CAAYC,CAAU,EAC1C,CAAA,MAASV,EAAO,CACZ,OAAA,CAAQ,MAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CArLI,IAAA,CAAK,OAAA,CAAUhB,CAAAA,CACf,IAAA,CAAK,MAAQC,CAAAA,CACb,IAAA,CAAK,OACT,CAmLJ,EA/LaF,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 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","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,CAAAA,CAAa,WAAA,CAAa,IAAM,KAAK,KAAK,CAAA,CAyBxD,UAAO,IAAY,CACf,GAAI,CACA,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAAC,EAAU,MAAA,CAAAC,GAAAA,CAAS,EAAG,CAAA,CAAI,IAAA,CAAK,QAE/C,GAAI,CAACF,CAAAA,CAAQ,CACT,OAAA,CAAQ,IAAA,CAAK,8BAA8B,CAAA,CAC3C,MACJ,CAEA,IAAMG,CA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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,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
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
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as RudderStack}from'../../chunk-
|
|
1
|
+
export{a as RudderStack}from'../../chunk-BGCEXYPC.mjs';import'../../chunk-TE3DYZVQ.mjs';//# sourceMappingURL=index.mjs.map
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -70,11 +70,9 @@ declare class AnalyticsCacheManager {
|
|
|
70
70
|
*/
|
|
71
71
|
isReady(): boolean;
|
|
72
72
|
/**
|
|
73
|
-
* Parse
|
|
74
|
-
* Uses an early-exit linear scan instead of building a full map,
|
|
75
|
-
* which is significantly faster when there are many cookies.
|
|
73
|
+
* Parse a localStorage entry by key.
|
|
76
74
|
*/
|
|
77
|
-
private
|
|
75
|
+
private parseFromLocalStorage;
|
|
78
76
|
/**
|
|
79
77
|
* Check if pageview has been sent
|
|
80
78
|
*/
|
|
@@ -84,15 +82,9 @@ declare class AnalyticsCacheManager {
|
|
|
84
82
|
*/
|
|
85
83
|
set(event: CachedEvent): void;
|
|
86
84
|
/**
|
|
87
|
-
* Push data to
|
|
85
|
+
* Push data to localStorage cache
|
|
88
86
|
*/
|
|
89
|
-
push(
|
|
90
|
-
/**
|
|
91
|
-
* Get the allowed domain for cookies
|
|
92
|
-
* For localhost/single-part domains: use as-is
|
|
93
|
-
* For multi-part domains: use top-level domain (e.g., .deriv.com)
|
|
94
|
-
*/
|
|
95
|
-
private getAllowedDomain;
|
|
87
|
+
push(key: string, data: any): void;
|
|
96
88
|
/**
|
|
97
89
|
* Process event to hash email and add client info
|
|
98
90
|
*/
|
|
@@ -70,11 +70,9 @@ declare class AnalyticsCacheManager {
|
|
|
70
70
|
*/
|
|
71
71
|
isReady(): boolean;
|
|
72
72
|
/**
|
|
73
|
-
* Parse
|
|
74
|
-
* Uses an early-exit linear scan instead of building a full map,
|
|
75
|
-
* which is significantly faster when there are many cookies.
|
|
73
|
+
* Parse a localStorage entry by key.
|
|
76
74
|
*/
|
|
77
|
-
private
|
|
75
|
+
private parseFromLocalStorage;
|
|
78
76
|
/**
|
|
79
77
|
* Check if pageview has been sent
|
|
80
78
|
*/
|
|
@@ -84,15 +82,9 @@ declare class AnalyticsCacheManager {
|
|
|
84
82
|
*/
|
|
85
83
|
set(event: CachedEvent): void;
|
|
86
84
|
/**
|
|
87
|
-
* Push data to
|
|
85
|
+
* Push data to localStorage cache
|
|
88
86
|
*/
|
|
89
|
-
push(
|
|
90
|
-
/**
|
|
91
|
-
* Get the allowed domain for cookies
|
|
92
|
-
* For localhost/single-part domains: use as-is
|
|
93
|
-
* For multi-part domains: use top-level domain (e.g., .deriv.com)
|
|
94
|
-
*/
|
|
95
|
-
private getAllowedDomain;
|
|
87
|
+
push(key: string, data: any): void;
|
|
96
88
|
/**
|
|
97
89
|
* Process event to hash email and add client info
|
|
98
90
|
*/
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkNCHU4435_js=require('../../chunk-NCHU4435.js');require('../../chunk-T4BXL6JM.js');Object.defineProperty(exports,"cacheTrackEvents",{enumerable:true,get:function(){return chunkNCHU4435_js.a}});//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as cacheTrackEvents}from'../../chunk-
|
|
1
|
+
export{a as cacheTrackEvents}from'../../chunk-5PFWZVJN.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.
|
|
3
|
+
"version": "1.39.5",
|
|
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",
|
|
@@ -83,7 +83,7 @@
|
|
|
83
83
|
"dependencies": {
|
|
84
84
|
"@rudderstack/analytics-js": "^3.14.0",
|
|
85
85
|
"js-cookie": "^3.0.5",
|
|
86
|
-
"posthog-js": "
|
|
86
|
+
"posthog-js": "1.358.0"
|
|
87
87
|
},
|
|
88
88
|
"optionalDependencies": {
|
|
89
89
|
"@growthbook/growthbook": "^1.4.1"
|
package/dist/chunk-44P2MMGV.mjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import {g,b}from'./chunk-GGU2UVKH.mjs';import {RudderAnalytics}from'@rudderstack/analytics-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
|
|
2
|
-
var k=2*365*24*60*60,n=class n{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=g("[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,o=["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=${o}; 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,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 o={...i&&{user_id:i},...a};this.log("pageView | tracking page view",{platform:t,current_page:e,properties:o}),this.analytics.page(t,e,o),this.current_page=e;}catch(o){console.error("RudderStack: Failed to track page view",o);}};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);}};n.getRudderStackInstance=(e,t,i=false)=>(n._instance||(n._instance=new n(e,t,i)),n._instance);var u=n;export{u as a};//# sourceMappingURL=chunk-44P2MMGV.mjs.map
|
|
3
|
-
//# sourceMappingURL=chunk-44P2MMGV.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,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ACvD,CACJ,CAAA,CAQA,WAAQ,CAA6BS,CAAAA,CAAUN,CAAAA,GAA4D,CACvG,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,GAAA,CAAI,sCAAA,CAAwC,CAAE,KAAA,CAAAM,CAAAA,CAAO,OAAA,CAAAN,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,CA5MI,IAAA,CAAK,gBAAA,CAAmBtB,CAAAA,CACxB,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,CAAKF,CAAe,EAC7B,CA0MJ,CAAA,CAzNaD,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-44P2MMGV.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 // 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"]}
|
package/dist/chunk-DWOZQCV4.mjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import {g}from'./chunk-GGU2UVKH.mjs';/* @deriv-com/analytics - NPM Package - Built with tsup */
|
|
2
|
-
var p=class{constructor(){this.interval=null;this.responses=[];this.isTrackingResponses=false;this.delegatedSelectors=new Set;this.debug=false;this.log=g("[CacheManager]",()=>this.debug);this.addEventhandler=this.addEventHandler.bind(this);}setDebug(e){this.debug=e;}hash(e,n=32){let t=a=>{let r=2166136261;for(let c=0;c<a.length;c++)r^=a.charCodeAt(c),r=r*16777619>>>0;return r.toString(16)},i=a=>btoa(a),s=t(e),o=i(s);for(;o.length<n;)o+=i(t(o));return o.substring(0,n)}getCookies(e){let t=`; ${document.cookie}`.split(`; ${e}=`);if(t.length===2){let i=decodeURIComponent(t.pop().split(";").shift());try{return JSON.parse(i)}catch{return i}}return null}trackPageUnload(){typeof window>"u"||window.addEventListener("beforeunload",()=>{this.isPageViewSent()||this.push("cached_analytics_page_views",{name:window.location.origin+window.location.pathname});});}trackResponses(){if(typeof window>"u"||typeof XMLHttpRequest>"u")return;let e=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(t,i){return this._url=i,this._method=t,e.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){return this.addEventListener("load",function(){let i=null;if(typeof t=="string")try{i=JSON.parse(t);}catch{i=t;}let s={url:this._url,method:this._method,status:this.status,headers:this.getAllResponseHeaders(),data:this.responseText,payload:i};f.responses.push(s);}),n.apply(this,arguments)},this.isTrackingResponses=true;}getAnalyticsInstance(){return typeof window>"u"?null:window.AnalyticsInstance??window.DerivAnalytics?.Analytics??window.Analytics?.Analytics}isReady(){if(typeof window>"u")return false;let e=this.getAnalyticsInstance();return e?!!e.getInstances?.()?.tracking:false}parseCookies(e){if(typeof document>"u")return null;let n=document.cookie.split("; ");for(let t of n){let i=t.indexOf("=");if(i!==-1&&decodeURIComponent(t.slice(0,i))===e){let s=t.slice(i+1);try{return JSON.parse(decodeURIComponent(s))}catch{return decodeURIComponent(s)}}}return null}isPageViewSent(){return !!this.responses.find(e=>e.payload?.type==="page"&&e.payload?.anonymousId)}set(e){this.log("set | caching event to cookie",e),this.push("cached_analytics_events",e);}push(e,n){if(typeof document>"u")return;let t=[],i=this.parseCookies(e);i&&Array.isArray(i)&&(t=i),t.push(n);let s=this.getAllowedDomain(),o=365*24*60*60,a=`${e}=${encodeURIComponent(JSON.stringify(t))}; path=/; Domain=${s}; max-age=${o}; SameSite=Lax`;document.cookie=a;}getAllowedDomain(){if(typeof window>"u")return "";let e=window.location.hostname;if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return e;let n=e.split(".");return n.length===1?e:`.${n.slice(-2).join(".")}`}processEvent(e){let n=this.getCookies("client_information");if(n){let{email:t=null}=n;t&&(e.properties.email_hash=this.hash(t));}if(e?.properties?.email){let t=e.properties.email;delete e.properties.email,e.properties.email_hash=this.hash(t);}return e}track(e,n=false){if(typeof window>"u")return;let t=this.processEvent(e),i=this.getAnalyticsInstance();this.isReady()&&!n?(this.log("track | analytics ready \u2014 calling trackEvent",{event:t.name,properties:t.properties}),i.trackEvent(t.name,t.properties)):(this.log("track | analytics not ready or cache=true \u2014 storing event",{event:t.name,cache:n}),this.set(t));}pageView(){typeof window>"u"||(this.log("pageView | starting page view polling"),this.isTrackingResponses||(this.trackResponses(),this.trackPageUnload()),this.interval=setInterval(()=>{let e=window.Analytics;typeof e<"u"&&typeof e.Analytics?.pageView=="function"&&this.isReady()&&(this.log("pageView | analytics ready \u2014 sending page view",{href:window.location.href}),e.Analytics.pageView(window.location.href,"Trader's hub")),this.isPageViewSent()&&(this.log("pageView | page view confirmed sent \u2014 clearing interval"),this.interval&&clearInterval(this.interval));},1e3));}listen(e,{name:n="",properties:t={}},i=false,s=null){let o=r=>{r.dataset?.clickEventTracking||(r.addEventListener("click",c=>{let l={name:n,properties:t,cache:i};if(typeof s=="function"){let d=s(c);l={...d,cache:d.cache??i};}this.track(l,l.cache??false);}),r.dataset.clickEventTracking="true");};(e instanceof NodeList?Array.from(e):[e]).forEach(o);}addEventHandler(e){return typeof window>"u"?this:(e.forEach(({element:n,event:t={name:"",properties:{}},cache:i=false,callback:s=null})=>{if(typeof n=="string"){let o=n;if(!this.delegatedSelectors.has(o)){let a=r=>{let c=r.target;if(!c)return;let l=c.closest(o);if(l&&!l.dataset?.clickEventTracking){let d={name:t.name,properties:t.properties,cache:i};if(typeof s=="function"){let h=s(r);d={...h,cache:h.cache??i};}l.dataset.clickEventTracking="true",this.track(d,d.cache??false);}};document.addEventListener("click",a),this.delegatedSelectors.add(o);}}else (n instanceof NodeList?Array.from(n):[n]).forEach(a=>{a&&!a.dataset?.clickEventTracking&&this.listen(a,t,i,s);});}),this)}loadEvent(e){return this.log("loadEvent | firing load events",e.map(n=>n.event.name)),e.forEach(({event:n})=>{let{name:t,properties:i}=n;this.track({name:t,properties:i});}),this}pageLoadEvent(e){if(typeof window>"u")return this;let n=window.location.pathname.slice(1);return this.log("pageLoadEvent | checking page load events",{pathname:n}),e.forEach(({pages:t=[],excludedPages:i=[],event:s,callback:o=null})=>{let a=false;if(t.length?t.includes(n)&&(a=true):i.length&&i.includes(n)||(a=true),a){let r=o?o():s;this.log("pageLoadEvent | dispatching event for page",{pathname:n,event:r.name}),this.loadEvent([{event:r}]);}else this.log("pageLoadEvent | skipped event for page",{pathname:n,event:s.name,pages:t,excludedPages:i});}),this}clearInterval(){this.interval&&(clearInterval(this.interval),this.interval=null);}cleanup(){this.clearInterval(),this.responses=[],this.isTrackingResponses=false;}},f=new p;typeof window<"u"&&(window.cacheTrackEvents=f);export{f as a};//# sourceMappingURL=chunk-DWOZQCV4.mjs.map
|
|
3
|
-
//# sourceMappingURL=chunk-DWOZQCV4.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/analytics-cache.ts"],"names":["AnalyticsCacheManager","createLogger","debug","inputString","desiredLength","fnv1aHash","string","hash","i","base64Encode","combined","name","parts","cookieValue","originalXhrOpen","originalXhrSend","method","url","body","parsedPayload","responseData","cacheTrackEvents","instance","cookieName","cookies","cookie","eqIdx","raw","event","data","storedCookies","cacheCookie","domain","maxAge","cookieString","hostname","clientInfo","email","originalEvent","cache","Analytics","element","properties","callback","addClickListener","el","e","call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AAK,GAAA,CAAI,4CAAA,CAA8C,CAAE,QAAA,CAAA0B,CAAAA,CAAU,KAAA,CAAOI,CAAAA,CAAU,IAAK,CAAC,CAAA,CAC1F,IAAA,CAAK,SAAA,CAAU,CAAC,CAAE,KAAA,CAAOA,CAAU,CAAC,CAAC,EACzC,CAAA,KACI,IAAA,CAAK,GAAA,CAAI,wCAAA,CAA0C,CAC/C,QAAA,CAAAJ,CAAAA,CACA,MAAO1B,CAAAA,CAAM,IAAA,CACb,KAAA,CAAA2B,CAAAA,CACA,aAAA,CAAAC,CACJ,CAAC,EAET,CAAC,CAAA,CAEM,IACX,CAKA,aAAA,EAAsB,CACd,IAAA,CAAK,QAAA,GACL,aAAA,CAAc,KAAK,QAAQ,CAAA,CAC3B,IAAA,CAAK,QAAA,CAAW,IAAA,EAExB,CAKA,OAAA,EAAgB,CACZ,KAAK,aAAA,EAAc,CACnB,IAAA,CAAK,SAAA,CAAY,EAAC,CAClB,IAAA,CAAK,mBAAA,CAAsB,MAC/B,CACJ,CAAA,CAGanC,CAAAA,CAAmB,IAAIrB,EAGhC,OAAO,MAAA,CAAW,GAAA,GAChB,OAAe,gBAAA,CAAmBqB,CAAAA,CAAAA","file":"chunk-DWOZQCV4.mjs","sourcesContent":["/**\n * Analytics Cache Manager - Version 1.1.0\n * Enhanced TypeScript implementation with better type safety and SSR support\n */\nimport { createLogger } from './helpers'\n\ntype CachedEvent = {\n name: string\n properties: Record<string, any>\n}\n\ntype ResponseData = {\n url: string\n method: string\n status: number\n headers: string\n data: string\n payload: any\n}\n\ntype EventListenerConfig = {\n element: Element | NodeList | string\n event: {\n name: string\n properties: Record<string, any>\n }\n cache?: boolean\n callback?: (e: Event) => { name: string; properties: Record<string, any>; cache?: boolean }\n}\n\ntype LoadEventConfig = {\n event: {\n name: string\n properties: Record<string, any>\n }\n}\n\ntype PageLoadEventConfig = {\n pages?: string[]\n excludedPages?: string[]\n event: {\n name: string\n properties: Record<string, any>\n }\n callback?: () => { name: string; properties: Record<string, any> }\n}\n\nclass AnalyticsCacheManager {\n private interval: NodeJS.Timeout | null = null\n private responses: ResponseData[] = []\n private isTrackingResponses = false\n private delegatedSelectors: Set<string> = new Set()\n private debug = false\n private log = createLogger('[CacheManager]', () => this.debug)\n\n setDebug(debug: boolean): void {\n this.debug = debug\n }\n\n /**\n * FNV-1a hash algorithm for creating consistent hashes\n */\n private hash(inputString: string, desiredLength = 32): string {\n const fnv1aHash = (string: string): string => {\n let hash = 0x811c9dc5\n for (let i = 0; i < string.length; i++) {\n hash ^= string.charCodeAt(i)\n hash = (hash * 0x01000193) >>> 0\n }\n return hash.toString(16)\n }\n\n const base64Encode = (string: string): string => btoa(string)\n\n let hash = fnv1aHash(inputString)\n let combined = base64Encode(hash)\n\n while (combined.length < desiredLength) {\n combined += base64Encode(fnv1aHash(combined))\n }\n\n return combined.substring(0, desiredLength)\n }\n\n /**\n * Get cookie value by name\n */\n getCookies(name: string): any {\n const value = `; ${document.cookie}`\n const parts = value.split(`; ${name}=`)\n if (parts.length === 2) {\n const cookieValue = decodeURIComponent(parts.pop()!.split(';').shift()!)\n\n try {\n return JSON.parse(cookieValue)\n } catch (e) {\n return cookieValue\n }\n }\n return null\n }\n\n /**\n * Track page unload events to cache pageviews before leaving\n */\n trackPageUnload(): void {\n if (typeof window === 'undefined') return\n\n window.addEventListener('beforeunload', () => {\n if (!this.isPageViewSent()) {\n this.push('cached_analytics_page_views', {\n name: window.location.origin + window.location.pathname,\n })\n }\n })\n }\n\n /**\n * Track XMLHttpRequest responses to monitor analytics calls\n */\n trackResponses(): void {\n if (typeof window === 'undefined' || typeof XMLHttpRequest === 'undefined') return\n\n const originalXhrOpen = XMLHttpRequest.prototype.open\n const originalXhrSend = XMLHttpRequest.prototype.send\n\n XMLHttpRequest.prototype.open = function (method: string, url: string | URL) {\n ;(this as any)._url = url\n ;(this as any)._method = method\n return originalXhrOpen.apply(this, arguments as any)\n }\n\n XMLHttpRequest.prototype.send = function (body?: Document | XMLHttpRequestBodyInit | null) {\n this.addEventListener('load', function () {\n let parsedPayload = null\n\n if (typeof body === 'string') {\n try {\n parsedPayload = JSON.parse(body)\n } catch (e) {\n parsedPayload = body\n }\n }\n\n const responseData: ResponseData = {\n url: (this as any)._url,\n method: (this as any)._method,\n status: this.status,\n headers: this.getAllResponseHeaders(),\n data: this.responseText,\n payload: parsedPayload,\n }\n cacheTrackEvents.responses.push(responseData)\n })\n\n return originalXhrSend.apply(this, arguments as any)\n }\n\n this.isTrackingResponses = true\n }\n\n /**\n * Resolve the analytics instance from the window object.\n * Supports three usage patterns:\n * - NPM import: analytics.ts sets window.AnalyticsInstance directly\n * - IIFE bundle: tsup sets window.DerivAnalytics = { Analytics, cacheTrackEvents }\n * - Legacy: consumers that explicitly set window.Analytics = window.DerivAnalytics\n */\n private getAnalyticsInstance(): any {\n if (typeof window === 'undefined') return null\n return (\n (window as any).AnalyticsInstance ??\n (window as any).DerivAnalytics?.Analytics ??\n (window as any).Analytics?.Analytics\n )\n }\n\n /**\n * Check if Analytics instance is ready\n */\n isReady(): boolean {\n if (typeof window === 'undefined') return false\n const instance = this.getAnalyticsInstance()\n if (!instance) return false\n return !!instance.getInstances?.()?.tracking\n }\n\n /**\n * Parse cookies to find a specific cookie by name.\n * Uses an early-exit linear scan instead of building a full map,\n * which is significantly faster when there are many cookies.\n */\n private parseCookies(cookieName: string): any {\n if (typeof document === 'undefined') return null\n\n const cookies = document.cookie.split('; ')\n for (const cookie of cookies) {\n const eqIdx = cookie.indexOf('=')\n if (eqIdx === -1) continue\n if (decodeURIComponent(cookie.slice(0, eqIdx)) === cookieName) {\n const raw = cookie.slice(eqIdx + 1)\n try {\n return JSON.parse(decodeURIComponent(raw))\n } catch {\n return decodeURIComponent(raw)\n }\n }\n }\n return null\n }\n\n /**\n * Check if pageview has been sent\n */\n isPageViewSent(): boolean {\n return !!this.responses.find(e => e.payload?.type === 'page' && e.payload?.anonymousId)\n }\n\n /**\n * Set a cached event\n */\n set(event: CachedEvent): void {\n this.log('set | caching event to cookie', event)\n this.push('cached_analytics_events', event)\n }\n\n /**\n * Push data to cookie cache\n */\n push(cookieName: string, data: any): void {\n if (typeof document === 'undefined') return\n\n let storedCookies: any[] = []\n const cacheCookie = this.parseCookies(cookieName)\n if (cacheCookie && Array.isArray(cacheCookie)) {\n storedCookies = cacheCookie\n }\n\n storedCookies.push(data)\n\n const domain = this.getAllowedDomain()\n const maxAge = 365 * 24 * 60 * 60 // 1 year\n const cookieString = `${cookieName}=${encodeURIComponent(JSON.stringify(storedCookies))}; path=/; Domain=${domain}; max-age=${maxAge}; SameSite=Lax`\n\n document.cookie = cookieString\n }\n\n /**\n * Get the allowed domain for cookies\n * For localhost/single-part domains: use as-is\n * For multi-part domains: use top-level domain (e.g., .deriv.com)\n */\n private getAllowedDomain(): string {\n if (typeof window === 'undefined') return ''\n\n const hostname = window.location.hostname\n\n // Handle IP addresses and localhost\n if (hostname === 'localhost' || /^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(hostname)) {\n return hostname\n }\n\n const parts = hostname.split('.')\n\n // Single part domain (e.g., \"localhost\")\n if (parts.length === 1) {\n return hostname\n }\n\n // Use top-level domain for proper subdomain sharing\n return `.${parts.slice(-2).join('.')}`\n }\n\n /**\n * Process event to hash email and add client info\n */\n processEvent(event: CachedEvent): CachedEvent {\n const clientInfo = this.getCookies('client_information')\n\n if (clientInfo) {\n const { email = null } = clientInfo\n\n if (email) {\n event.properties.email_hash = this.hash(email)\n }\n }\n\n if (event?.properties?.email) {\n const email = event.properties.email\n delete event.properties.email\n event.properties.email_hash = this.hash(email)\n }\n\n return event\n }\n\n /**\n * Track an event (either immediately or cache it)\n */\n track(originalEvent: CachedEvent, cache = false): void {\n if (typeof window === 'undefined') return\n\n const event = this.processEvent(originalEvent)\n const instance = this.getAnalyticsInstance()\n\n if (this.isReady() && !cache) {\n this.log('track | analytics ready — calling trackEvent', {\n event: event.name,\n properties: event.properties,\n })\n instance.trackEvent(event.name, event.properties)\n } else {\n this.log('track | analytics not ready or cache=true — storing event', { event: event.name, cache })\n this.set(event)\n }\n }\n\n /**\n * Track pageview with auto-retry until sent\n */\n pageView(): void {\n if (typeof window === 'undefined') return\n\n this.log('pageView | starting page view polling')\n\n if (!this.isTrackingResponses) {\n this.trackResponses()\n this.trackPageUnload()\n }\n\n this.interval = setInterval(() => {\n const Analytics = (window as any).Analytics\n\n if (\n typeof Analytics !== 'undefined' &&\n typeof Analytics.Analytics?.pageView === 'function' &&\n this.isReady()\n ) {\n this.log('pageView | analytics ready — sending page view', { href: window.location.href })\n Analytics.Analytics.pageView(window.location.href, \"Trader's hub\")\n }\n\n if (this.isPageViewSent()) {\n this.log('pageView | page view confirmed sent — clearing interval')\n if (this.interval) clearInterval(this.interval)\n }\n }, 1000)\n }\n\n /**\n * Add click event listener to element(s)\n */\n listen(\n element: Element | NodeList,\n { name = '', properties = {} }: { name: string; properties: Record<string, any> },\n cache = false,\n callback: ((e: Event) => { name: string; properties: Record<string, any>; cache?: boolean }) | null = null\n ): void {\n const addClickListener = (el: Element) => {\n if (!(el as any).dataset?.clickEventTracking) {\n el.addEventListener('click', (e: Event) => {\n let event = {\n name,\n properties,\n cache,\n }\n\n if (typeof callback === 'function') {\n const callbackResult = callback(e)\n event = {\n ...callbackResult,\n cache: callbackResult.cache ?? cache,\n }\n }\n\n this.track(event, event.cache ?? false)\n })\n ;(el as any).dataset.clickEventTracking = 'true'\n }\n }\n\n const elements = element instanceof NodeList ? Array.from(element as NodeListOf<Element>) : [element]\n elements.forEach(addClickListener)\n }\n\n /**\n * Add event handlers to multiple elements with auto-retry\n * Alias for backward compatibility with typo\n */\n addEventHandler(items: EventListenerConfig[]): this {\n if (typeof window === 'undefined') return this\n\n items.forEach(({ element, event = { name: '', properties: {} }, cache = false, callback = null }) => {\n // If a selector string is provided, use event delegation on document\n if (typeof element === 'string') {\n const selector = element\n\n if (!this.delegatedSelectors.has(selector)) {\n const delegatedHandler = (e: Event) => {\n const target = e.target as Element | null\n if (!target) return\n\n const matched = target.closest(selector)\n if (matched && !(matched as any).dataset?.clickEventTracking) {\n let evt: any = {\n name: event.name,\n properties: event.properties,\n cache,\n }\n\n if (typeof callback === 'function') {\n const callbackResult = callback(e)\n evt = {\n ...callbackResult,\n cache: callbackResult.cache ?? cache,\n }\n }\n\n ;(matched as any).dataset.clickEventTracking = 'true'\n this.track(evt, evt.cache ?? false)\n }\n }\n\n document.addEventListener('click', delegatedHandler)\n this.delegatedSelectors.add(selector)\n }\n } else {\n // Element or NodeList: attach directly to existing elements\n const elements = element instanceof NodeList ? Array.from(element) : [element]\n\n elements.forEach(el => {\n if (el && !(el as any).dataset?.clickEventTracking) {\n this.listen(el as Element, event, cache, callback)\n }\n })\n }\n })\n\n return this\n }\n\n /**\n * Backward compatibility alias (with typo from original)\n */\n addEventhandler = this.addEventHandler.bind(this)\n\n /**\n * Load events immediately\n */\n loadEvent(items: LoadEventConfig[]): this {\n this.log(\n 'loadEvent | firing load events',\n items.map(i => i.event.name)\n )\n items.forEach(({ event }) => {\n const { name, properties } = event\n this.track({\n name,\n properties,\n })\n })\n\n return this\n }\n\n /**\n * Load events on specific pages\n */\n pageLoadEvent(items: PageLoadEventConfig[]): this {\n if (typeof window === 'undefined') return this\n\n const pathname = window.location.pathname.slice(1)\n this.log('pageLoadEvent | checking page load events', { pathname })\n\n items.forEach(({ pages = [], excludedPages = [], event, callback = null }) => {\n let dispatch = false\n if (pages.length) {\n if (pages.includes(pathname)) {\n dispatch = true\n }\n } else if (excludedPages.length) {\n if (!excludedPages.includes(pathname)) {\n dispatch = true\n }\n } else {\n dispatch = true\n }\n\n if (dispatch) {\n const eventData = callback ? callback() : event\n this.log('pageLoadEvent | dispatching event for page', { pathname, event: eventData.name })\n this.loadEvent([{ event: eventData }])\n } else {\n this.log('pageLoadEvent | skipped event for page', {\n pathname,\n event: event.name,\n pages,\n excludedPages,\n })\n }\n })\n\n return this\n }\n\n /**\n * Clear the interval and cleanup\n */\n clearInterval(): void {\n if (this.interval) {\n clearInterval(this.interval)\n this.interval = null\n }\n }\n\n /**\n * Cleanup method for removing event listeners and intervals\n */\n cleanup(): void {\n this.clearInterval()\n this.responses = []\n this.isTrackingResponses = false\n }\n}\n\n// Create singleton instance\nexport const cacheTrackEvents = new AnalyticsCacheManager()\n\n// Export to global scope for backward compatibility\nif (typeof window !== 'undefined') {\n ;(window as any).cacheTrackEvents = cacheTrackEvents\n}\n"]}
|
package/dist/chunk-GGU2UVKH.mjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import m from'js-cookie';/* @deriv-com/analytics - NPM Package - Built with tsup */
|
|
2
|
-
var c="https://deriv.com/cdn-cgi/trace",f="https://cdn.growthbook.io",y="https://deriv-dataplane.rudderstack.com",a="https://ph.deriv.com",g="https://us.posthog.com",h=()=>{if(typeof window>"u")return a;let t=window.location.hostname;return t.includes(".deriv.me")?"https://ph.deriv.me":t.includes(".deriv.be")?"https://ph.deriv.be":a},p=["deriv.com","deriv.be","deriv.me","deriv.team","deriv.ae"],l=["deriv.com","derivcrypto.com","besquare.my","besquare.com.my","ewallet.exchange","champion-fx.com","opalstraits.com","binary.com","binary.marketing","championgbs.com","4x.my","re-work.dev","regentmarkets.com","4x.com","binary.me","deriv.team","firstsource.io","firstsource.tech","deriv.hr","vmgbpo.net","mailisk.net","mailosaur.net","mobileapps.mailisk.net","w3e180zd.mailosaur.net"],v=()=>{if(typeof window>"u")return ".deriv.com";let t=window.location.hostname;if(t==="localhost")return "";let e=p.find(o=>t.includes(o));return e?`.${e}`:".deriv.com"};var k=(t,e)=>(...o)=>{e()&&console.log(`[ANALYTIC]${t}`,...o);},b=t=>{let e=t.split("@")[1]?.toLowerCase();return e?l.includes(e):false},O=t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t),i=null,D=async()=>{if(i)return i;let t=JSON.parse(m.get("website_status")||"{}")?.clients_country;return i=(async()=>{try{let e=await fetch(c).catch(()=>null);if(!e)return t||"";let o=await e.text().catch(()=>"");return o?Object.fromEntries(o.split(`
|
|
3
|
-
`).map(r=>r.split("=",2))).loc?.toLowerCase()||t||"":t||""}catch{return t||""}})(),i},d=t=>{if(t==null||typeof t!="object")return t;if(Array.isArray(t)){let n=[];for(let r=0;r<t.length;r++){let s=d(t[r]);s!=null&&n.push(s);}return n.length?n:void 0}let e={},o=false;for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let r=d(t[n]);r==null||r===""||typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0||Array.isArray(r)&&r.length===0||(e[n]=r,o=true);}return o?e:void 0},u=(t,e)=>{for(let o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;let n=t[o];n&&typeof n=="object"&&!Array.isArray(n)?u(n,e):e[o]=n;}},R=t=>{if(t==null||typeof t!="object"||Array.isArray(t))return t;let e={};return u(t,e),e};export{f as a,y as b,g as c,h as d,p as e,v as f,k as g,b as h,O as i,D as j,d as k,R as l};//# sourceMappingURL=chunk-GGU2UVKH.mjs.map
|
|
4
|
-
//# sourceMappingURL=chunk-GGU2UVKH.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/urls.ts","../src/utils/helpers.ts"],"names":["cloudflareTrace","growthbookApi","rudderstackDataplane","posthogApiHost","posthogUiHost","getPosthogApiHost","hostname","allowedDomains","internalEmailDomains","getAllowedDomain","matched","d","createLogger","prefix","isDebugEnabled","args","isInternalEmail","email","domain","isUUID","str","countryPromise","getCountry","cookieCountry","Cookies","response","text","v","cleanObject","obj","out","i","cleaned","hasKeys","key","_flattenInto","target","value","flattenObject"],"mappings":";AAAO,IAAMA,CAAAA,CAAkB,kCAClBC,CAAAA,CAAgB,2BAAA,CAChBC,EAAuB,yCAAA,CACvBC,CAAAA,CAAiB,sBAAA,CACjBC,CAAAA,CAAgB,wBAAA,CAEhBC,CAAAA,CAAoB,IAAc,CAC3C,GAAI,OAAO,MAAA,CAAW,GA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,CAAOD,CAAM,CAAA,CAE1BA,CAAAA,CAAOF,CAAG,CAAA,CAAIG,EAEtB,CACJ,EAEaC,CAAAA,CAAiBT,CAAAA,EAAkC,CAC5D,GAAIA,CAAAA,EAAO,MAAQ,OAAOA,CAAAA,EAAQ,QAAA,EAAY,KAAA,CAAM,OAAA,CAAQA,CAAG,EAC3D,OAAOA,CAAAA,CAEX,IAAMO,CAAAA,CAA8B,EAAC,CACrC,OAAAD,CAAAA,CAAaN,CAAAA,CAAKO,CAAM,CAAA,CACjBA,CACX","file":"chunk-GGU2UVKH.mjs","sourcesContent":["export const cloudflareTrace = 'https://deriv.com/cdn-cgi/trace'\nexport const growthbookApi = 'https://cdn.growthbook.io'\nexport const rudderstackDataplane = 'https://deriv-dataplane.rudderstack.com'\nexport const posthogApiHost = 'https://ph.deriv.com'\nexport const posthogUiHost = 'https://us.posthog.com'\n\nexport const getPosthogApiHost = (): string => {\n if (typeof window === 'undefined') return posthogApiHost\n const hostname = window.location.hostname\n if (hostname.includes('.deriv.me')) return 'https://ph.deriv.me'\n if (hostname.includes('.deriv.be')) return 'https://ph.deriv.be'\n return posthogApiHost\n}\n\nexport const allowedDomains = ['deriv.com', 'deriv.be', 'deriv.me', 'deriv.team', 'deriv.ae'] as const\n\nexport const internalEmailDomains = [\n 'deriv.com',\n 'derivcrypto.com',\n 'besquare.my',\n 'besquare.com.my',\n 'ewallet.exchange',\n 'champion-fx.com',\n 'opalstraits.com',\n 'binary.com',\n 'binary.marketing',\n 'championgbs.com',\n '4x.my',\n 're-work.dev',\n 'regentmarkets.com',\n '4x.com',\n 'binary.me',\n 'deriv.team',\n 'firstsource.io',\n 'firstsource.tech',\n 'deriv.hr',\n 'vmgbpo.net',\n 'mailisk.net',\n 'mailosaur.net',\n 'mobileapps.mailisk.net',\n 'w3e180zd.mailosaur.net',\n] as const\n\nexport const getAllowedDomain = (): string => {\n if (typeof window === 'undefined') return '.deriv.com'\n const hostname = window.location.hostname\n\n if (hostname === 'localhost') return ''\n\n const matched = allowedDomains.find(d => hostname.includes(d))\n return matched ? `.${matched}` : '.deriv.com'\n}\n","import Cookies from 'js-cookie'\nimport { cloudflareTrace, internalEmailDomains } from './urls'\n\n/**\n * Creates a prefixed logger that only outputs when debug mode is enabled.\n * Pass a getter function so the logger always reads the latest debug state.\n *\n * @param prefix - Optional provider name appended after [ANALYTIC], e.g. '[RudderStack]'\n * @param isDebugEnabled - A function that returns the current debug flag value\n * @returns A log function with the same signature as console.log\n *\n * @example\n * // In a class\n * private log = createLogger('[RudderStack]', () => this.debug)\n *\n * // In a closure\n * const log = createLogger('', () => _debug)\n */\nexport const createLogger =\n (prefix: string, isDebugEnabled: () => boolean) =>\n (...args: any[]): void => {\n if (isDebugEnabled()) console.log(`[ANALYTIC]${prefix}`, ...args)\n }\n\nexport const isInternalEmail = (email: string): boolean => {\n const domain = email.split('@')[1]?.toLowerCase()\n if (!domain) return false\n return (internalEmailDomains as readonly string[]).includes(domain)\n}\n\nexport const isUUID = (str: string): boolean => {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n return uuidRegex.test(str)\n}\n\ntype TraceData = {\n loc?: string\n}\n\nlet countryPromise: Promise<string> | null = null\n\n/**\n * Fetches the country information based on Cloudflare's trace data or a fallback from cookies.\n * This function attempts to retrieve the country location by first fetching trace data from Cloudflare\n * and then falling back to the location stored in the cookies if the fetch fails.\n *\n * @returns {Promise<string>} A Promise that resolves to a string representing the country code in lowercase.\n * Returns an empty string if no country data is available or if an error occurs.\n *\n * @example\n * // Returns the country code in lowercase based on Cloudflare's trace data or cookies.\n * getCountry().then(country => console.log(country));\n */\nexport const getCountry = async (): Promise<string> => {\n if (countryPromise) return countryPromise\n\n const cookieCountry = JSON.parse(Cookies.get('website_status') || '{}')?.clients_country\n\n countryPromise = (async () => {\n try {\n const response = await fetch(cloudflareTrace).catch(() => null)\n if (!response) return cookieCountry || ''\n\n const text = await response.text().catch(() => '')\n if (!text) return cookieCountry || ''\n\n const data: TraceData = Object.fromEntries(text.split('\\n').map(v => v.split('=', 2)))\n return data.loc?.toLowerCase() || cookieCountry || ''\n } catch {\n return cookieCountry || ''\n }\n })()\n\n return countryPromise\n}\n\n/**\n * Recursively cleans an object by removing undefined, null, empty strings, empty objects, and empty arrays\n * Used to sanitize event properties before sending to analytics providers\n *\n * @param obj - The object to clean\n * @returns The cleaned object, or undefined if the result would be empty\n */\nexport const cleanObject = (obj: any): any => {\n if (obj == null || typeof obj !== 'object') return obj\n\n if (Array.isArray(obj)) {\n const out: any[] = []\n for (let i = 0; i < obj.length; i++) {\n const v = cleanObject(obj[i])\n if (v !== undefined && v !== null) out.push(v)\n }\n return out.length ? out : undefined\n }\n\n const cleaned: Record<string, any> = {}\n let hasKeys = false\n for (const key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue\n const v = cleanObject(obj[key])\n if (\n v === undefined ||\n v === null ||\n v === '' ||\n (typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === 0) ||\n (Array.isArray(v) && v.length === 0)\n )\n continue\n cleaned[key] = v\n hasKeys = true\n }\n return hasKeys ? cleaned : undefined\n}\n\n/**\n * Flattens a nested object structure into a single-level object\n * Lifts all nested properties to the top level without prefixing\n *\n * @param obj - The object to flatten\n * @returns A flattened object with all nested properties at the top level\n *\n * @example\n * flattenObject({ action: 'click', event_metadata: { version: 2, user_language: 'en' } })\n * // Returns: { action: 'click', version: 2, user_language: 'en' }\n *\n * flattenObject({ form_name: 'signup', cta_information: { cta_name: 'signup', section_name: 'header' } })\n * // Returns: { form_name: 'signup', cta_name: 'signup', section_name: 'header' }\n */\nconst _flattenInto = (obj: Record<string, any>, target: Record<string, any>): void => {\n for (const key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue\n const value = obj[key]\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n _flattenInto(value, target)\n } else {\n target[key] = value\n }\n }\n}\n\nexport const flattenObject = (obj: any): Record<string, any> => {\n if (obj == null || typeof obj !== 'object' || Array.isArray(obj)) {\n return obj\n }\n const target: Record<string, any> = {}\n _flattenInto(obj, target)\n return target\n}\n"]}
|
package/dist/chunk-GZBZB5MW.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkJ3V5QNIH_js=require('./chunk-J3V5QNIH.js');/* @deriv-com/analytics - NPM Package - Built with tsup */
|
|
2
|
-
var p=class{constructor(){this.interval=null;this.responses=[];this.isTrackingResponses=false;this.delegatedSelectors=new Set;this.debug=false;this.log=chunkJ3V5QNIH_js.g("[CacheManager]",()=>this.debug);this.addEventhandler=this.addEventHandler.bind(this);}setDebug(e){this.debug=e;}hash(e,n=32){let t=a=>{let r=2166136261;for(let c=0;c<a.length;c++)r^=a.charCodeAt(c),r=r*16777619>>>0;return r.toString(16)},i=a=>btoa(a),s=t(e),o=i(s);for(;o.length<n;)o+=i(t(o));return o.substring(0,n)}getCookies(e){let t=`; ${document.cookie}`.split(`; ${e}=`);if(t.length===2){let i=decodeURIComponent(t.pop().split(";").shift());try{return JSON.parse(i)}catch{return i}}return null}trackPageUnload(){typeof window>"u"||window.addEventListener("beforeunload",()=>{this.isPageViewSent()||this.push("cached_analytics_page_views",{name:window.location.origin+window.location.pathname});});}trackResponses(){if(typeof window>"u"||typeof XMLHttpRequest>"u")return;let e=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(t,i){return this._url=i,this._method=t,e.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){return this.addEventListener("load",function(){let i=null;if(typeof t=="string")try{i=JSON.parse(t);}catch{i=t;}let s={url:this._url,method:this._method,status:this.status,headers:this.getAllResponseHeaders(),data:this.responseText,payload:i};f.responses.push(s);}),n.apply(this,arguments)},this.isTrackingResponses=true;}getAnalyticsInstance(){return typeof window>"u"?null:window.AnalyticsInstance??window.DerivAnalytics?.Analytics??window.Analytics?.Analytics}isReady(){if(typeof window>"u")return false;let e=this.getAnalyticsInstance();return e?!!e.getInstances?.()?.tracking:false}parseCookies(e){if(typeof document>"u")return null;let n=document.cookie.split("; ");for(let t of n){let i=t.indexOf("=");if(i!==-1&&decodeURIComponent(t.slice(0,i))===e){let s=t.slice(i+1);try{return JSON.parse(decodeURIComponent(s))}catch{return decodeURIComponent(s)}}}return null}isPageViewSent(){return !!this.responses.find(e=>e.payload?.type==="page"&&e.payload?.anonymousId)}set(e){this.log("set | caching event to cookie",e),this.push("cached_analytics_events",e);}push(e,n){if(typeof document>"u")return;let t=[],i=this.parseCookies(e);i&&Array.isArray(i)&&(t=i),t.push(n);let s=this.getAllowedDomain(),o=365*24*60*60,a=`${e}=${encodeURIComponent(JSON.stringify(t))}; path=/; Domain=${s}; max-age=${o}; SameSite=Lax`;document.cookie=a;}getAllowedDomain(){if(typeof window>"u")return "";let e=window.location.hostname;if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return e;let n=e.split(".");return n.length===1?e:`.${n.slice(-2).join(".")}`}processEvent(e){let n=this.getCookies("client_information");if(n){let{email:t=null}=n;t&&(e.properties.email_hash=this.hash(t));}if(e?.properties?.email){let t=e.properties.email;delete e.properties.email,e.properties.email_hash=this.hash(t);}return e}track(e,n=false){if(typeof window>"u")return;let t=this.processEvent(e),i=this.getAnalyticsInstance();this.isReady()&&!n?(this.log("track | analytics ready \u2014 calling trackEvent",{event:t.name,properties:t.properties}),i.trackEvent(t.name,t.properties)):(this.log("track | analytics not ready or cache=true \u2014 storing event",{event:t.name,cache:n}),this.set(t));}pageView(){typeof window>"u"||(this.log("pageView | starting page view polling"),this.isTrackingResponses||(this.trackResponses(),this.trackPageUnload()),this.interval=setInterval(()=>{let e=window.Analytics;typeof e<"u"&&typeof e.Analytics?.pageView=="function"&&this.isReady()&&(this.log("pageView | analytics ready \u2014 sending page view",{href:window.location.href}),e.Analytics.pageView(window.location.href,"Trader's hub")),this.isPageViewSent()&&(this.log("pageView | page view confirmed sent \u2014 clearing interval"),this.interval&&clearInterval(this.interval));},1e3));}listen(e,{name:n="",properties:t={}},i=false,s=null){let o=r=>{r.dataset?.clickEventTracking||(r.addEventListener("click",c=>{let l={name:n,properties:t,cache:i};if(typeof s=="function"){let d=s(c);l={...d,cache:d.cache??i};}this.track(l,l.cache??false);}),r.dataset.clickEventTracking="true");};(e instanceof NodeList?Array.from(e):[e]).forEach(o);}addEventHandler(e){return typeof window>"u"?this:(e.forEach(({element:n,event:t={name:"",properties:{}},cache:i=false,callback:s=null})=>{if(typeof n=="string"){let o=n;if(!this.delegatedSelectors.has(o)){let a=r=>{let c=r.target;if(!c)return;let l=c.closest(o);if(l&&!l.dataset?.clickEventTracking){let d={name:t.name,properties:t.properties,cache:i};if(typeof s=="function"){let h=s(r);d={...h,cache:h.cache??i};}l.dataset.clickEventTracking="true",this.track(d,d.cache??false);}};document.addEventListener("click",a),this.delegatedSelectors.add(o);}}else (n instanceof NodeList?Array.from(n):[n]).forEach(a=>{a&&!a.dataset?.clickEventTracking&&this.listen(a,t,i,s);});}),this)}loadEvent(e){return this.log("loadEvent | firing load events",e.map(n=>n.event.name)),e.forEach(({event:n})=>{let{name:t,properties:i}=n;this.track({name:t,properties:i});}),this}pageLoadEvent(e){if(typeof window>"u")return this;let n=window.location.pathname.slice(1);return this.log("pageLoadEvent | checking page load events",{pathname:n}),e.forEach(({pages:t=[],excludedPages:i=[],event:s,callback:o=null})=>{let a=false;if(t.length?t.includes(n)&&(a=true):i.length&&i.includes(n)||(a=true),a){let r=o?o():s;this.log("pageLoadEvent | dispatching event for page",{pathname:n,event:r.name}),this.loadEvent([{event:r}]);}else this.log("pageLoadEvent | skipped event for page",{pathname:n,event:s.name,pages:t,excludedPages:i});}),this}clearInterval(){this.interval&&(clearInterval(this.interval),this.interval=null);}cleanup(){this.clearInterval(),this.responses=[],this.isTrackingResponses=false;}},f=new p;typeof window<"u"&&(window.cacheTrackEvents=f);exports.a=f;//# sourceMappingURL=chunk-GZBZB5MW.js.map
|
|
3
|
-
//# sourceMappingURL=chunk-GZBZB5MW.js.map
|