@deriv-com/analytics 1.39.1 → 1.39.3
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 +6 -6
- 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-DWOZQCV4.mjs +3 -0
- package/dist/chunk-DWOZQCV4.mjs.map +1 -0
- package/dist/chunk-GZBZB5MW.js +3 -0
- package/dist/chunk-GZBZB5MW.js.map +1 -0
- 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-2YOT34O2.mjs → posthog-PBG3EMGB.mjs} +4 -4
- package/dist/{posthog-2YOT34O2.mjs.map → posthog-PBG3EMGB.mjs.map} +1 -1
- package/dist/providers/posthog/index.js +1 -1
- package/dist/providers/posthog/index.js.map +1 -1
- package/dist/providers/posthog/index.mjs +1 -1
- package/dist/providers/posthog/index.mjs.map +1 -1
- package/dist/utils/analytics-cache/index.js +1 -1
- package/dist/utils/analytics-cache/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-LIPHY7JK.mjs +0 -3
- package/dist/chunk-LIPHY7JK.mjs.map +0 -1
- package/dist/chunk-SQ6Q4Z5S.js +0 -3
- package/dist/chunk-SQ6Q4Z5S.js.map +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
'use strict';var chunkJ3V5QNIH_js=require('../../chunk-J3V5QNIH.js'),r=require('posthog-js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var r__default=/*#__PURE__*/_interopDefault(r);/* @deriv-com/analytics - NPM Package - Built with tsup */
|
|
2
|
-
var n=class n{constructor(i,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=chunkJ3V5QNIH_js.g("[PostHog]",()=>this.debug);this.init=()=>{try{let{apiKey:i,api_host:t,config:e={}}=this.options;if(!i){console.warn("Posthog: No API key provided");return}let o=t||chunkJ3V5QNIH_js.d();this.log("init | loading PostHog SDK",{api_host:o});let s={api_host:o,ui_host:chunkJ3V5QNIH_js.c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...e.session_recording},before_send:
|
|
2
|
+
var n=class n{constructor(i,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=chunkJ3V5QNIH_js.g("[PostHog]",()=>this.debug);this.init=()=>{try{let{apiKey:i,api_host:t,config:e={}}=this.options;if(!i){console.warn("Posthog: No API key provided");return}let o=t||chunkJ3V5QNIH_js.d();this.log("init | loading PostHog SDK",{api_host:o});let s={api_host:o,ui_host:chunkJ3V5QNIH_js.c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...e.session_recording},before_send:l=>{if(typeof window>"u")return null;let a=window.location.hostname;if(a==="localhost"||a==="127.0.0.1")return l;let d=chunkJ3V5QNIH_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=chunkJ3V5QNIH_js.h(t)),e&&!o.country_of_residence&&(s.country_of_residence=e),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:i,updates:s}),r__default.default.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:i,country_of_residence:e});}catch(o){console.error("Posthog: Failed to backfill person properties",o);}};this.capture=(i,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:i,properties:t}),r__default.default.capture(i,t);}catch(e){console.error("Posthog: Failed to capture event",e);}};this.options=i,this.debug=t,this.init();}};n.getPosthogInstance=(i,t=false)=>(n._instance||(n._instance=new n(i,t)),n._instance);var P=n;exports.Posthog=P;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","apiKey","api_host","config","resolvedApiHost","getPosthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","domain","posthog","error","user_id","traits","isIdentified","email","safeTraits","isInternalEmail","country_of_residence","storedProperties","updates","event_name","properties","Posthog"],"mappings":";AAqBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,IAAA,CAAA,eAAA,CAAkB,KAAA,CAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,IAAA,CAAQ,KAAA,CAAQ,MAChB,IAAA,CAAQ,GAAA,CAAMC,kBAAAA,CAAa,WAAA,CAAa,IAAM,IAAA,CAAK,KAAK,CAAA,CAyBxD,IAAA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sC,CAAE,UAAA,CAAAD,CAAAA,CAAY,UAAA,CAAAC,CAAW,CAAC,CAAA,CACzEZ,kBAAAA,CAAQ,OAAA,CAAQW,CAAAA,CAAYC,CAAU,EAC1C,CAAA,MAASX,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CAvLI,IAAA,CAAK,OAAA,CAAUhB,CAAAA,CACf,KAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,GACT,CAqLJ,EAjMaF,CAAAA,CAoBK,kBAAA,CAAqB,CAACC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,IAC7DF,EAAQ,SAAA,GACTA,CAAAA,CAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,CAxBhB,IAAM6B,CAAAA,CAAN7B","file":"index.js","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport type { TCoreAttributes } from '../types'\nimport { allowedDomains, getPosthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Initialize PostHog with configuration\n * Configures PostHog instance with provided options\n */\n init = (): void => {\n try {\n const { apiKey, api_host, config = {} } = this.options\n\n if (!apiKey) {\n console.warn('Posthog: No API key provided')\n return\n }\n\n const resolvedApiHost = api_host || getPosthogApiHost()\n this.log('init | loading PostHog SDK', { api_host: resolvedApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: resolvedApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n session_recording: {\n recordCrossOriginIframes: true,\n minimumDurationMilliseconds: 30000,\n ...config.session_recording,\n },\n before_send: event => {\n if (typeof window === 'undefined') return null\n\n const currentHost = window.location.hostname\n if (currentHost === 'localhost' || currentHost === '127.0.0.1') return event\n\n const isAllowed = allowedDomains.some(\n domain => currentHost.endsWith(`.${domain}`) || currentHost === domain\n )\n if (!isAllowed) this.log('init | before_send blocked event from disallowed host', { currentHost })\n return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n this.log('init | PostHog SDK loaded successfully')\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog.\n * Skipped if the user is already identified — use backfillPersonProperties to backfill\n * client_id for users identified in previous sessions.\n *\n * @param user_id - The user ID to identify\n * @param traits - User properties (language, country_of_residence, etc.)\n */\n identifyEvent = (user_id: string, traits: TPosthogIdentifyTraits): void => {\n if (!this.has_initialized) {\n console.warn('Posthog: Cannot identify - not initialized')\n return\n }\n\n try {\n const isIdentified =\n typeof posthog._isIdentified === 'function' ? posthog._isIdentified() : this.has_identified\n\n if (user_id && !isIdentified) {\n const { email, ...safeTraits } = traits\n this.log('identifyEvent | identifying user', { user_id, safeTraits })\n posthog.identify(user_id, {\n ...safeTraits,\n client_id: user_id,\n ...(email && { is_internal: isInternalEmail(email) }),\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param params.user_id - The user ID to use as client_id\n * @param params.email - The user's email, used to determine is_internal\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n country_of_residence?: string\n }): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties: Record<string, any> = posthog.get_property('$stored_person_properties') ?? {}\n const updates: Record<string, any> = {}\n\n if (!storedProperties.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n if (country_of_residence && !storedProperties.country_of_residence) {\n updates.country_of_residence = country_of_residence\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', {\n user_id,\n country_of_residence,\n })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any> & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n}\n"]}
|
|
1
|
+
{"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,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,0DAAA,CAA4D,CAAE,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,3 +1,3 @@
|
|
|
1
1
|
import {g,d,e,c,h}from'../../chunk-GGU2UVKH.mjs';import r from'posthog-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
|
|
2
|
-
var n=class n{constructor(i,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=g("[PostHog]",()=>this.debug);this.init=()=>{try{let{apiKey:i,api_host:t,config:e$1={}}=this.options;if(!i){console.warn("Posthog: No API key provided");return}let o=t||d();this.log("init | loading PostHog SDK",{api_host:o});let s={api_host:o,ui_host:c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...e$1.session_recording},before_send:
|
|
2
|
+
var n=class n{constructor(i,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=g("[PostHog]",()=>this.debug);this.init=()=>{try{let{apiKey:i,api_host:t,config:e$1={}}=this.options;if(!i){console.warn("Posthog: No API key provided");return}let o=t||d();this.log("init | loading PostHog SDK",{api_host:o});let s={api_host:o,ui_host:c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...e$1.session_recording},before_send: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=h(t)),e&&!o.country_of_residence&&(s.country_of_residence=e),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:i,updates:s}),r.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:i,country_of_residence:e});}catch(o){console.error("Posthog: Failed to backfill person properties",o);}};this.capture=(i,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:i,properties:t}),r.capture(i,t);}catch(e){console.error("Posthog: Failed to capture event",e);}};this.options=i,this.debug=t,this.init();}};n.getPosthogInstance=(i,t=false)=>(n._instance||(n._instance=new n(i,t)),n._instance);var P=n;export{P as Posthog};//# sourceMappingURL=index.mjs.map
|
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","apiKey","api_host","config","resolvedApiHost","getPosthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","domain","posthog","error","user_id","traits","isIdentified","email","safeTraits","isInternalEmail","country_of_residence","storedProperties","updates","event_name","properties","Posthog"],"mappings":";AAqBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,IAAA,CAAA,eAAA,CAAkB,KAAA,CAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,IAAA,CAAQ,KAAA,CAAQ,MAChB,IAAA,CAAQ,GAAA,CAAMC,CAAAA,CAAa,WAAA,CAAa,IAAM,IAAA,CAAK,KAAK,CAAA,CAyBxD,IAAA,CAAA,IAAA,CAAO,IAAY,CACf,GAAI,CACA,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAAC,CAAAA,CAAU,MAAA,CAAAC,IAAS,EAAG,CAAA,CAAI,IAAA,CAAK,OAAA,CAE/C,GAAI,CAACF,CAAAA,CAAQ,CACT,OAAA,CAAQ,IAAA,CAAK,8BAA8B,CAAA,CAC3C,MACJ,CAEA,IAAMG,EAAkBF,CAAAA,EAAYG,CAAAA,GACpC,IAAA,CAAK,GAAA,CAAI,4BAAA,CAA8B,CAAE,QAAA,CAAUD,CAAgB,CAAC,CAAA,CAEpE,IAAME,CAAAA,CAAgC,CAClC,QAAA,CAAUF,CAAAA,CACV,QAASG,CAAAA,CACT,WAAA,CAAa,CAAA,CAAA,CACb,gBAAA,CAAkB,gBAAA,CAClB,iBAAA,CAAmB,CACf,wBAAA,CAA0B,CAAA,CAAA,CAC1B,2BAAA,CAA6B,GAAA,CAC7B,GAAGJ,GAAAA,CAAO,iBACd,CAAA,CACA,WAAA,CAAaK,CAAAA,EAAS,CAClB,GAAI,OAAO,OAAW,GAAA,CAAa,OAAO,IAA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CAAA,CAAE,MAAA,CAAS,CAAA,EAC9B,IAAA,CAAK,GAAA,CAAI,2DAA4D,CAAE,OAAA,CAAAR,CAAAA,CAAS,OAAA,CAAAQ,CAAQ,CAAC,EACzFV,CAAAA,CAAQ,mBAAA,CAAoBU,CAAO,CAAA,EAEnC,IAAA,CAAK,GAAA,CAAI,2EAAuE,CAC5E,OAAA,CAAAR,CAAAA,CACA,oBAAA,CAAAM,CACJ,CAAC,EAET,CAAA,MAASP,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,+CAAA,CAAiDA,CAAK,EACxE,CACJ,CAAA,CASA,IAAA,CAAA,OAAA,CAAU,CAACU,CAAAA,CAAoBC,IAAsE,CACjG,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,KAAK,GAAA,CAAI,oCAAA,CAAsC,CAAE,UAAA,CAAAD,CAAAA,CAAY,UAAA,CAAAC,CAAW,CAAC,CAAA,CACzEZ,CAAAA,CAAQ,OAAA,CAAQW,CAAAA,CAAYC,CAAU,EAC1C,CAAA,MAASX,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CAvLI,IAAA,CAAK,OAAA,CAAUhB,CAAAA,CACf,KAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,GACT,CAqLJ,EAjMaF,CAAAA,CAoBK,kBAAA,CAAqB,CAACC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,IAC7DF,EAAQ,SAAA,GACTA,CAAAA,CAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,CAxBhB,IAAM6B,CAAAA,CAAN7B","file":"index.mjs","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport type { TCoreAttributes } from '../types'\nimport { allowedDomains, getPosthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Initialize PostHog with configuration\n * Configures PostHog instance with provided options\n */\n init = (): void => {\n try {\n const { apiKey, api_host, config = {} } = this.options\n\n if (!apiKey) {\n console.warn('Posthog: No API key provided')\n return\n }\n\n const resolvedApiHost = api_host || getPosthogApiHost()\n this.log('init | loading PostHog SDK', { api_host: resolvedApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: resolvedApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n session_recording: {\n recordCrossOriginIframes: true,\n minimumDurationMilliseconds: 30000,\n ...config.session_recording,\n },\n before_send: event => {\n if (typeof window === 'undefined') return null\n\n const currentHost = window.location.hostname\n if (currentHost === 'localhost' || currentHost === '127.0.0.1') return event\n\n const isAllowed = allowedDomains.some(\n domain => currentHost.endsWith(`.${domain}`) || currentHost === domain\n )\n if (!isAllowed) this.log('init | before_send blocked event from disallowed host', { currentHost })\n return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n this.log('init | PostHog SDK loaded successfully')\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog.\n * Skipped if the user is already identified — use backfillPersonProperties to backfill\n * client_id for users identified in previous sessions.\n *\n * @param user_id - The user ID to identify\n * @param traits - User properties (language, country_of_residence, etc.)\n */\n identifyEvent = (user_id: string, traits: TPosthogIdentifyTraits): void => {\n if (!this.has_initialized) {\n console.warn('Posthog: Cannot identify - not initialized')\n return\n }\n\n try {\n const isIdentified =\n typeof posthog._isIdentified === 'function' ? posthog._isIdentified() : this.has_identified\n\n if (user_id && !isIdentified) {\n const { email, ...safeTraits } = traits\n this.log('identifyEvent | identifying user', { user_id, safeTraits })\n posthog.identify(user_id, {\n ...safeTraits,\n client_id: user_id,\n ...(email && { is_internal: isInternalEmail(email) }),\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param params.user_id - The user ID to use as client_id\n * @param params.email - The user's email, used to determine is_internal\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n country_of_residence?: string\n }): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties: Record<string, any> = posthog.get_property('$stored_person_properties') ?? {}\n const updates: Record<string, any> = {}\n\n if (!storedProperties.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n if (country_of_residence && !storedProperties.country_of_residence) {\n updates.country_of_residence = country_of_residence\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', {\n user_id,\n country_of_residence,\n })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any> & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n}\n"]}
|
|
1
|
+
{"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,CAAA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AAA,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,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkGZBZB5MW_js=require('../../chunk-GZBZB5MW.js');require('../../chunk-J3V5QNIH.js');Object.defineProperty(exports,"cacheTrackEvents",{enumerable:true,get:function(){return chunkGZBZB5MW_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-DWOZQCV4.mjs';import'../../chunk-GGU2UVKH.mjs';//# sourceMappingURL=index.mjs.map
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deriv-com/analytics",
|
|
3
|
-
"version": "1.39.
|
|
3
|
+
"version": "1.39.3",
|
|
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",
|
package/dist/chunk-LIPHY7JK.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.href,properties:{url:window.location.href}});});}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-LIPHY7JK.mjs.map
|
|
3
|
-
//# sourceMappingURL=chunk-LIPHY7JK.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","callbackResult","items","selector","delegatedHandler","target","matched","evt","pathname","pages","excludedPages","dispatch","eventData"],"mappings":";AA+CA,IAAMA,CAAAA,CAAN,KAA4B,CAA5B,WAAA,EAAA,CACI,KAAQ,QAAA,CAAkC,IAAA,CAC1C,IAAA,CAAQ,SAAA,CAA4B,EAAC,CACrC,IAAA,CAAQ,mBAAA,CAAsB,MAC9B,IAAA,CAAQ,kBAAA,CAAkC,IAAI,GAAA,CAC9C,IAAA,CAAQ,KAAA,CAAQ,KAAA,CAChB,IAAA,CAAQ,IAAMC,CAAAA,CAAa,gBAAA,CAAkB,IAAM,IAAA,CAAK,KAAK,CAAA,CA0Y7D,IAAA,CAAA,eAAA,CAAkB,IAAA,CAAK,gBAAgB,IAAA,CAAK,IAAI,EAAA,CAxYhD,QAAA,CAASC,C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,IAAA,EAExB,CAKA,OAAA,EAAgB,CACZ,IAAA,CAAK,aAAA,EAAc,CACnB,IAAA,CAAK,SAAA,CAAY,EAAC,CAClB,IAAA,CAAK,oBAAsB,MAC/B,CACJ,CAAA,CAGanC,CAAAA,CAAmB,IAAIrB,EAGhC,OAAO,MAAA,CAAW,GAAA,GAChB,OAAe,gBAAA,CAAmBqB,CAAAA,CAAAA","file":"chunk-LIPHY7JK.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.href,\n properties: {\n url: window.location.href,\n },\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-SQ6Q4Z5S.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.href,properties:{url:window.location.href}});});}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-SQ6Q4Z5S.js.map
|
|
3
|
-
//# sourceMappingURL=chunk-SQ6Q4Z5S.js.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","callbackResult","items","selector","delegatedHandler","target","matched","evt","pathname","pages","excludedPages","dispatch","eventData"],"mappings":";AA+CA,IAAMA,CAAAA,CAAN,KAA4B,CAA5B,WAAA,EAAA,CACI,KAAQ,QAAA,CAAkC,IAAA,CAC1C,IAAA,CAAQ,SAAA,CAA4B,EAAC,CACrC,IAAA,CAAQ,mBAAA,CAAsB,MAC9B,IAAA,CAAQ,kBAAA,CAAkC,IAAI,GAAA,CAC9C,IAAA,CAAQ,KAAA,CAAQ,KAAA,CAChB,IAAA,CAAQ,IAAMC,kBAAAA,CAAa,gBAAA,CAAkB,IAAM,IAAA,CAAK,KAAK,CAAA,CA0Y7D,IAAA,CAAA,eAAA,CAAkB,IAAA,CAAK,gBAAgB,IAAA,CAAK,IAAI,EAAA,CAxYhD,QAAA,CAASC,CAAAA,CAAsB,CAC3B,IAAA,CAAK,KAAA,CAAQA,EACjB,CAKQ,IAAA,CAAKC,CAAAA,CAAqBC,CAAAA,CAAgB,EAAA,CAAY,CAC1D,IAAMC,CAAAA,CAAaC,GAA2B,CAC1C,IAAIC,CAAAA,CAAO,UAAA,CACX,IAAA,IAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,EAAO,MAAA,CAAQE,CAAAA,EAAAA,CAC/BD,CAAAA,EAAQD,CAAAA,CAAO,UAAA,CAAWE,CAAC,CAAA,CAC3BD,CAAAA,CAAQA,EAAO,QAAA,GAAgB,CAAA,CAEnC,OAAOA,CAAAA,CAAK,QAAA,CAAS,EAAE,CAC3B,CAAA,CAEME,EAAgBH,CAAAA,EAA2B,IAAA,CAAKA,CAAM,CAAA,CAExDC,CAAAA,CAAOF,CAAAA,CAAUF,CAAW,CAAA,CAC5BO,EAAWD,CAAAA,CAAaF,CAAI,CAAA,CAEhC,KAAOG,CAAAA,CAAS,MAAA,CAASN,CAAAA,EACrBM,CAAAA,EAAYD,EAAaJ,CAAAA,CAAUK,CAAQ,CAAC,CAAA,CA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WA,CAAAA,EAAS,CAAIf,EAC1C,IAAA,CAAK,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,EACA,KAAA,CAAO1B,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,cAAc,IAAA,CAAK,QAAQ,CAAA,CAC3B,IAAA,CAAK,QAAA,CAAW,IAAA,EAExB,CAKA,OAAA,EAAgB,CACZ,IAAA,CAAK,aAAA,EAAc,CACnB,IAAA,CAAK,SAAA,CAAY,EAAC,CAClB,IAAA,CAAK,oBAAsB,MAC/B,CACJ,CAAA,CAGanC,CAAAA,CAAmB,IAAIrB,EAGhC,OAAO,MAAA,CAAW,GAAA,GAChB,OAAe,gBAAA,CAAmBqB,CAAAA,CAAAA","file":"chunk-SQ6Q4Z5S.js","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.href,\n properties: {\n url: window.location.href,\n },\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"]}
|