import { getDeviceId } from './device'; function getCsrfToken(): string | null { if (typeof document === 'undefined') { return null; } const metaToken = document.querySelector('meta[name="csrf-token"]'); if (metaToken instanceof HTMLMetaElement) { return metaToken.getAttribute('content') || null; } const name = 'XSRF-TOKEN='; const decodedCookie = decodeURIComponent(document.cookie ?? ''); const parts = decodedCookie.split(';'); for (const part of parts) { const trimmed = part.trimStart(); if (!trimmed.startsWith(name)) { continue; } const token = trimmed.substring(name.length); try { return decodeURIComponent(atob(token)); } catch { return token; } } return null; } export function buildCsrfHeaders(deviceId?: string): Record { const token = getCsrfToken(); const resolvedDeviceId = deviceId ?? (typeof window !== 'undefined' ? getDeviceId() : undefined); const headers: Record = { Accept: 'application/json', }; if (resolvedDeviceId) { headers['X-Device-Id'] = resolvedDeviceId; } if (token) { headers['X-CSRF-TOKEN'] = token; headers['X-XSRF-TOKEN'] = token; } return headers; }