let token = sessionStorage.getItem('dc_token') || ''; export function setToken(t) { token = t || ''; if (t) sessionStorage.setItem('dc_token', t); else sessionStorage.removeItem('dc_token'); } export function getToken() { return token; } async function request(path, opts = {}) { const res = await fetch('/api' + path, { ...opts, headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(opts.headers || {}), }, }); if (res.status === 401) setToken(''); const data = await res.json().catch(() => null); if (!res.ok) throw new Error(data?.error || res.statusText); return data; } export const api = { get: (p) => request(p), post: (p, body) => request(p, { method: 'POST', body: JSON.stringify(body ?? {}) }), put: (p, body) => request(p, { method: 'PUT', body: JSON.stringify(body ?? {}) }), del: (p) => request(p, { method: 'DELETE' }), };