import cookies from 'next-cookies' ; import Router from 'next/router' ; import { ParsedUrlQuery } from 'querystring' ; import { v4 as uuidv4 } from 'uuid' ; declare global { interface Window { analytics : any ; } } type Page = { path : string ; pathname : string ; name : string ; query : ParsedUrlQuery ; } ; type ConversionType = 'pageview' | 'event' ; interface Conversion { type : ConversionType ; source ? : string ; page : Page ; properties : { [ key ] : unknown ; } ; } type Session = { id : string ; timeout : number ; } ; const sessionIdLocalStorageKey = 'sessionId' ; const lastTrackedLocalStorageKey = 'lastTracked' ; const sessionTimeout = 1000 * 60 * 30 ; function getSessionId ( ) { const lsSessionId = localStorage . getItem ( sessionIdLocalStorageKey ) ; const lsLastTracked = localStorage . getItem ( lastTrackedLocalStorageKey ) ; if ( lsLastTracked ) { const now = Date . now ( ) ; const diff = now - parseInt ( lsLastTracked , 10 ) ; if ( diff >= sessionTimeout ) { return resetSessionId ( ) ; } } if ( lsSessionId ) { return lsSessionId ; } return resetSessionId ( ) ; } function resetSessionId ( ) { const sessionId = uuidv4 ( ) ; localStorage . setItem ( sessionIdLocalStorageKey , sessionId ) ; return sessionId ; } function removeCacheValuesFromUrlQuery ( query ) { const { memoizedPrismic , ... restOfQuery } = query ; return restOfQuery ; } let pageName ; function trackPageview ( name , properties ) { const { source , ... query } = removeCacheValuesFromUrlQuery ( Router . query ) ; pageName = name ; const conversion = { type : 'pageview' , source : source ?. toString ( ) || 'unknown' , page : { path : Router . asPath , pathname : Router . pathname , name , query , } , properties , } ; track ( conversion ) ; } type EventName = 'download' ; function trackEvent ( name , properties ) { const { ... query } = removeCacheValuesFromUrlQuery ( Router . query ) ; track ( { type : 'event' , page : { path : Router . asPath , pathname : Router . pathname , name : pageName , query , } , properties : { event : name , ... properties } , } ) ; } function track ( conversion ) { const debug = Boolean ( cookies ( { } ) . analytics_debug ) ; const sessionId = getSessionId ( ) ; const session = { id : sessionId , timeout : sessionTimeout , } ; localStorage . setItem ( lastTrackedLocalStorageKey , Date . now ( ) . toString ( ) ) ; if ( debug ) { console . info ( { session , ... conversion , } ) ; } window . analytics . track ( 'conversion' , { session , ... conversion , } ) ; } export { trackPageview , trackEvent } ;