import { isCrawler } from './helpers' import { UserConfig, TracktorConfig, Storage, Event } from './interfaces' import { VISITOR_ID, SESSION_STAMP, DEVICE_ID, getCookieDomain, generateValueFor, getExpirationFor, } from './storage' import EventBuffer from './eventBuffer' export class Tracktor { public userConfig: UserConfig private isCrawler: Boolean private storage: Storage private static eventBuffer: EventBuffer public static initializeEventBuffer(config: TracktorConfig) { if (!Tracktor.eventBuffer) { Tracktor.eventBuffer = new EventBuffer(config) } } constructor(config: UserConfig, storage: Storage) { if (!Tracktor.eventBuffer) { throw new Error( `The event buffer has not been configurated. Look for the initializeEventBuffer method in the documentation` ) } this.storage = storage this.userConfig = config this.userConfig.visitorId = this.getTracktorConfig(VISITOR_ID, config.visitorId) this.userConfig.sessionStamp = Number( this.getTracktorConfig(SESSION_STAMP, config.sessionStamp) ) this.userConfig.deviceId = this.getTracktorConfig(DEVICE_ID, config.deviceId) this.isCrawler = isCrawler(this.userConfig.userAgent) if (typeof window !== 'undefined') { window.addEventListener('beforeunload', () => { this.flush() }) } } private getTracktorConfig(key, value) { let storageValue const expires = getExpirationFor(key) let options: { domain: string; expires?: Date } = { domain: getCookieDomain(this.userConfig.hostname), expires, } if (value) { storageValue = value } else if (this.storage.get(key)) { storageValue = this.storage.get(key) } else { storageValue = generateValueFor(key) } this.storage.set(key, storageValue, options) return storageValue } /** * Update userId in the config, after a login/logout/signup for instance. */ public updateUserId(userId: string) { this.userConfig = { ...this.userConfig, userId } } public push({ name, version }: Partial, payload: object) { if (!this.isCrawler) { Tracktor.eventBuffer.push(name, version, payload, this.userConfig) } } public flush() { Tracktor.eventBuffer.flush(this.userConfig) } } export default Tracktor