import { parse } from '../parse'; import { serialize } from '../serialize'; import { operationFailed } from '../errors'; import type { Backend, Cookie, DeleteOptions, NormalizedAttributes } from '../types'; /** The slice of Document this backend needs, injectable so tests can observe writes. */ export interface CookieTarget { cookie: string; } function promiseResult(operation: () => T): Promise { return Promise.resolve().then(operation); } /** * Builds a Backend backed by document.cookie. Cannot report a cookie's path * or domain, and cannot see HttpOnly cookies, because neither is exposed to * script through this API. */ export function createDocumentCookieBackend(target: CookieTarget): Backend { const readAll = (): Cookie[] => { let cookieHeader: string; try { cookieHeader = target.cookie; } catch (cause) { throw operationFailed('read', cause); } return parse(cookieHeader).map((pair) => ({ name: pair.name, value: pair.value })); }; return { get(name: string): Promise { return promiseResult(() => readAll().find((cookie) => cookie.name === name)); }, getAll(): Promise { return promiseResult(readAll); }, set(name: string, value: string, attributes: NormalizedAttributes): Promise { return promiseResult(() => { const cookie = serialize(name, value, attributes); try { target.cookie = cookie; } catch (cause) { throw operationFailed('set', cause); } }); }, delete(name: string, options: DeleteOptions): Promise { return promiseResult(() => { const attributes: NormalizedAttributes = { ...options, maxAge: 0, expires: 0 }; // CHIPS requires a Partitioned cookie to be Secure, so a browser discards a // write carrying Partitioned without it. Deletion works by overwriting with // an expired cookie, so a discarded write leaves the cookie in place. if (options.partitioned === true) attributes.secure = true; const cookie = serialize(name, '', attributes); try { target.cookie = cookie; } catch (cause) { throw operationFailed('delete', cause); } }); }, }; }