import { PersistentStore } from '@wirewheel/cmp/src/modules/PersistentStore' import Cookies from 'js-cookie' const ONE_YEAR_IN_DAYS = 365 const COOKIE_KEY = 'wwupcp' type CookiePersistentStoreParams = { cookieExpirationInDays?: number refreshOnVisit?: boolean } export class CookiePersistentStore extends PersistentStore { private readonly expirationInDays: number private readonly refreshOnVisit: boolean constructor(params?: CookiePersistentStoreParams) { super() this.expirationInDays = params?.cookieExpirationInDays || ONE_YEAR_IN_DAYS this.refreshOnVisit = params?.refreshOnVisit ?? false } protected read(): any { try { return JSON.parse(Cookies.get(COOKIE_KEY) as string) } catch (cause) { return {} } } write(value: any): void { const hostnameParts = location.hostname.split('.').reverse() const parts: string[] = [] const currentValue = this.read() let domain = '' const expirationDate = this.getExpirationDate(currentValue.expirationDate) hostnameParts.forEach((val) => { parts.push(val) domain = [...parts].reverse().join('.') // TODO Ensure it only sets the cookie for one domain Cookies.set(COOKIE_KEY, JSON.stringify({ ...currentValue, ...value, expirationDate }), { domain: domain, SameSite: 'None', secure: true, expires: expirationDate, }) }) } private getExpirationDate(currentExpirationDate: Date) { const DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000 if (currentExpirationDate && !this.refreshOnVisit) { return new Date(currentExpirationDate) } return new Date(new Date().getTime() + this.expirationInDays * DAY_IN_MILLISECONDS) } }