import { globalState } from '../../app/global-state'; import { DomainHelper } from './domain-helper'; // Cookie manipulation abstraction export class CookieProvider { /** * Sets cookie value * * @param name Name of the cookie * @param value Cookie value * @param expiration When the cookie should expire, set as a past date in order to delete the cookie */ static set( name: string, value: string, expiration?: Temporal.PlainDateTime, ) { if (!globalState.windowExists) { return; } let domain = DomainHelper.getCookieDomain(); if (domain.length > 0) { domain = `;domain=.${domain}`; } let realExpiration; if (expiration != null) { const instant = expiration.toZonedDateTime('UTC').toInstant(); // eslint-disable-next-line no-restricted-syntax realExpiration = new Date(instant.epochMilliseconds).toUTCString(); } else { realExpiration = ''; } document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)};expires=${realExpiration}${domain};path=/`; } /** * Obtains cookie value * * @param name Name of the cookie */ static read(name: string): string { if (!globalState.windowExists) { return null; } name = `${name}=`; const ca = document.cookie.split(';'); for (let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.includes(name)) { return c.substring(name.length, c.length); } } return null; } /** * Removes cookie * * @param name Name of the cookie */ static remove(name: string) { CookieProvider.set( name, '', Temporal.PlainDateTime.from('1990-01-01'), ); } }