UNPKG

seitu

Version:
49 lines (48 loc) • 1.63 kB
//#region src/utils/cookie/index.ts /** 400 days, the cap browsers apply to `Max-Age`/`Expires`. */ const DEFAULT_MAX_AGE = 3456e4; /** * Returns the raw value of `key` from a `Cookie` header or `document.cookie`, * or `null` when the cookie is missing. * * @example * ```ts twoslash * import { parseCookie } from 'seitu/utils' * * parseCookie('a=1; theme=dark', 'theme') // 'dark' * parseCookie('a=1', 'theme') // null * ``` */ function parseCookie(header, key) { const prefix = `${key}=`; for (const part of header.split(";")) { const trimmed = part.trim(); if (trimmed.startsWith(prefix)) return trimmed.slice(prefix.length); } return null; } /** * Builds a `document.cookie`/`Set-Cookie` string. Defaults: `Path=/`, * `SameSite=Lax`, `Max-Age` of 400 days unless `expires` is set. * * @example * ```ts twoslash * import { serializeCookie } from 'seitu/utils' * * serializeCookie('theme', 'dark', { maxAge: 60 }) * // 'theme=dark; Path=/; Max-Age=60; SameSite=Lax' * ``` */ function serializeCookie(key, raw, attributes = {}) { const { path = "/", domain, expires, maxAge = expires ? void 0 : DEFAULT_MAX_AGE, sameSite = "lax", secure, partitioned } = attributes; const parts = [`${key}=${raw}`, `Path=${path}`]; if (domain) parts.push(`Domain=${domain}`); if (maxAge !== void 0) parts.push(`Max-Age=${maxAge}`); if (expires) parts.push(`Expires=${expires.toUTCString()}`); parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`); if (secure) parts.push("Secure"); if (partitioned) parts.push("Partitioned"); return parts.join("; "); } //#endregion export { parseCookie, serializeCookie };