(
url: string,
accessToken: string,
opts: { timeoutMs?: number } = {},
)
| 197 | } |
| 198 | |
| 199 | export async function fetchManagedUsage( |
| 200 | url: string, |
| 201 | accessToken: string, |
| 202 | opts: { timeoutMs?: number } = {}, |
| 203 | ): Promise<FetchManagedUsageResult | FetchManagedUsageError> { |
| 204 | const controller = new AbortController(); |
| 205 | const timer = setTimeout(() => { |
| 206 | controller.abort(); |
| 207 | }, opts.timeoutMs ?? 8000); |
| 208 | try { |
| 209 | const res = await fetch(url, { |
| 210 | headers: { |
| 211 | Authorization: `Bearer ${accessToken}`, |
| 212 | Accept: 'application/json', |
| 213 | }, |
| 214 | signal: controller.signal, |
| 215 | }); |
| 216 | if (!res.ok) { |
| 217 | const status = res.status; |
| 218 | const hint = |
| 219 | status === 401 |
| 220 | ? 'Authorization failed. Please check your API key (try /login).' |
| 221 | : status === 404 |
| 222 | ? 'Usage endpoint not available. Try Kimi For Coding.' |
| 223 | : `Failed to fetch usage: HTTP ${String(status)}`; |
| 224 | return { kind: 'error', status, message: await readApiErrorMessage(res, hint) }; |
| 225 | } |
| 226 | const json: unknown = await res.json(); |
| 227 | return { kind: 'ok', parsed: parseManagedUsagePayload(json) }; |
| 228 | } catch (error) { |
| 229 | if (error instanceof Error && error.name === 'AbortError') { |
| 230 | return { kind: 'error', message: 'Failed to fetch usage: request timed out.' }; |
| 231 | } |
| 232 | const msg = error instanceof Error ? error.message : String(error); |
| 233 | return { kind: 'error', message: `Failed to fetch usage: ${msg}` }; |
| 234 | } finally { |
| 235 | clearTimeout(timer); |
| 236 | } |
| 237 | } |
no test coverage detected