File size: 5,371 Bytes
9dfccd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bb34f8
 
9dfccd9
 
 
 
 
 
 
 
 
 
9bb34f8
 
 
 
9dfccd9
 
 
 
 
 
9bb34f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9dfccd9
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import { env } from '@/config/env'
import { useAuthStore } from '@/stores/authStore'
import { useUIStore } from '@/stores/uiStore'

// ─── Typed API errors ────────────────────────────────────────────────────────

export class ApiError extends Error {
  constructor(
    public readonly status: number,
    message: string,
    public readonly requestId?: string,
  ) {
    super(message)
    this.name = 'ApiError'
  }
}

// ─── Token refresh ───────────────────────────────────────────────────────────

async function refreshToken(): Promise<boolean> {
  try {
    const res = await fetch(`${env.apiBaseUrl}/api/auth/refresh`, {
      method:      'POST',
      credentials: 'include',
    })
    return res.ok
  } catch {
    return false
  }
}

// ─── Error handling ──────────────────────────────────────────────────────────

/** Parse a non-OK response and show the appropriate toast, then throw ApiError. */
async function handleErrorResponse(res: Response): Promise<never> {
  const requestId = res.headers.get('X-Request-ID') ?? undefined
  const addToast  = useUIStore.getState().addToast

  let message: string
  try {
    const json = await res.json()
    message = json.detail ?? json.message ?? res.statusText
  } catch {
    message = res.statusText || `HTTP ${res.status}`
  }

  switch (res.status) {
    case 429: {
      const retryAfter = res.headers.get('Retry-After')
      const suffix = retryAfter ? ` β€” retry in ${retryAfter}s` : ''
      addToast({ type: 'warning', message: `Rate limited${suffix}` })
      break
    }
    case 403:
      // RBAC β€” components handle this via RBACRestrictedBanner; no toast needed
      break
    case 502:
    case 503:
    case 504:
      addToast({ type: 'error', message: 'Backend unavailable β€” try again shortly' })
      break
    case 500:
      addToast({
        type:    'error',
        message: requestId
          ? `Server error [${requestId}] β€” contact support if this persists`
          : 'Server error β€” try again',
      })
      break
    default:
      if (res.status >= 400) {
        addToast({ type: 'error', message })
      }
  }

  throw new ApiError(res.status, message, requestId)
}

// ─── Base fetch ──────────────────────────────────────────────────────────────

export async function apiFetch(
  path: string,
  init: RequestInit = {},
): Promise<Response> {
  const doFetch = () =>
    fetch(`${env.apiBaseUrl}${path}`, {
      ...init,
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
        ...init.headers,
      },
    })

  let res: Response
  try {
    res = await doFetch()
  } catch {
    // Network-level failure (DNS, no connection)
    useUIStore.getState().addToast({ type: 'error', message: 'No connection to server' })
    throw new ApiError(0, 'Network error')
  }

  if (res.status === 401) {
    const refreshed = await refreshToken()
    if (!refreshed) {
      useAuthStore.getState().logout()
      window.location.href = '/login'
      throw new ApiError(401, 'Session expired')
    }
    try {
      res = await doFetch()
    } catch {
      throw new ApiError(0, 'Network error after token refresh')
    }
  }

  if (!res.ok) {
    await handleErrorResponse(res)
  }

  return res
}

// ─── SSE streaming fetch ─────────────────────────────────────────────────────

/** Returns raw Response for streaming β€” does NOT parse body. */
export async function ssePost(
  path: string,
  body: unknown,
  signal: AbortSignal,
): Promise<Response> {
  const doFetch = () =>
    fetch(`${env.apiBaseUrl}${path}`, {
      method:      'POST',
      credentials: 'include',
      signal,
      headers: {
        'Content-Type':  'application/json',
        'Accept':        'text/event-stream',
        'Cache-Control': 'no-cache',
      },
      body: JSON.stringify(body),
    })

  let res: Response
  try {
    res = await doFetch()
  } catch (err) {
    if ((err as Error).name === 'AbortError') throw err
    useUIStore.getState().addToast({ type: 'error', message: 'No connection to server' })
    throw new ApiError(0, 'Network error')
  }

  if (res.status === 401) {
    const refreshed = await refreshToken()
    if (!refreshed) {
      useAuthStore.getState().logout()
      window.location.href = '/login'
      throw new ApiError(401, 'Session expired')
    }
    try {
      res = await doFetch()
    } catch (err) {
      if ((err as Error).name === 'AbortError') throw err
      throw new ApiError(0, 'Network error after token refresh')
    }
  }

  if (!res.ok) {
    const requestId = res.headers.get('X-Request-ID') ?? undefined
    const text = await res.text().catch(() => res.statusText)
    throw new ApiError(res.status, `${res.status}: ${text}`, requestId)
  }

  return res
}