function getXsrfToken(): string { const match = document.cookie .split('; ') .find((row) => row.startsWith('XSRF-TOKEN=')); return match ? decodeURIComponent(match.split('=')[1] ?? '') : ''; } export async function apiFetch(url: string, options: RequestInit = {}): Promise { const response = await fetch(url, { ...options, headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-XSRF-TOKEN': getXsrfToken(), 'X-Requested-With': 'XMLHttpRequest', ...options.headers, }, credentials: 'same-origin', }); if (!response.ok) { const error = await response.json().catch(() => ({})) as { message?: string; errors?: Record; }; const firstValidationError = error.errors ? Object.values(error.errors).flat()[0] : undefined; throw new Error(firstValidationError ?? error.message ?? 'Permintaan gagal diproses.'); } return response.json() as Promise; }