import { SignalInstance } from '../types/signal.types'; import { supportsLocalStorage } from './cache.helper'; import { v4 as uuid } from 'uuid'; import { getDateString } from './date.helper'; import { CLIENT_CACHE_KEY } from '../constants/constants'; type CachedClientObj = { clientId: string; clientCreated: string; }; const getCachedClientInfo = () => { const clientCache = localStorage.getItem(CLIENT_CACHE_KEY); if (clientCache) { try { return JSON.parse(clientCache) as CachedClientObj; } catch (e) { // do nothing } } return null; }; export const getClientInfo = (instance: SignalInstance) => { if (instance.deviceId || !instance.clientUserAgent) { return { clientId: undefined, clientCreated: null, }; } if (!supportsLocalStorage()) { throw new Error('Local storage is not supported. Cannot create client id'); } const cachedClientObj = getCachedClientInfo(); if (cachedClientObj && cachedClientObj.clientId && cachedClientObj.clientCreated) { return { clientId: cachedClientObj.clientId, clientCreated: cachedClientObj.clientCreated, }; } const newClientInfo = { clientId: uuid(), clientCreated: getDateString(), }; localStorage.setItem(CLIENT_CACHE_KEY, JSON.stringify(newClientInfo)); return newClientInfo; };