import { apiResponses } from '../generated/api-types.ts'
import type { paths } from '../generated/api-types.ts'
type Method = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options'
type Operation<M extends Method, P extends keyof paths> = M extends keyof paths[P]
? NonNullable<paths[P][M]> : never
type Endpoint<M extends Method> = {
[P in keyof paths]: [Operation<M, P>] extends [never] ? never : P
}[keyof paths]
type JsonContent<T> = T extends { content: { 'application/json': infer Body } } ? Body : undefined
type Responses<O> = O extends { responses: infer R } ? R : never
type SuccessCode<R> = { [S in keyof R]: `${S & (number | string)}` extends `2${string}` ? S : never }[keyof R]
type Success<O> = JsonContent<Responses<O>[SuccessCode<Responses<O>>]>
type Parameters<O> = O extends { parameters: infer P }
? Pick<P, Extract<keyof P, 'path' | 'query'>> : { path?: never; query?: never }
type RequiredKeys<T> = { [K in keyof T]-?: object extends Pick<T, K> ? never : K }[keyof T]
type BodyOptions<O> = O extends { requestBody: infer R } ? { body: JsonContent<R> }
: O extends { requestBody?: infer R } ? [NonNullable<R>] extends [never] ? { body?: never }
: { body?: JsonContent<NonNullable<R>> } : { body?: never }
export type RequestOptions<O> = Omit<RequestInit, 'method' | 'body' | 'credentials' | 'redirect'> & BodyOptions<O>
& ([RequiredKeys<Parameters<O>>] extends [never] ? { params?: Parameters<O> } : { params: Parameters<O> })
type Arguments<O> = [RequiredKeys<RequestOptions<O>>] extends [never]
? [options?: RequestOptions<O>] : [options: RequestOptions<O>]
type DocumentedFailure<O> = {
[S in Exclude<keyof Responses<O>, SuccessCode<Responses<O>>>]: {
ok: false; kind: 'documented'; status: S; body: JsonContent<Responses<O>[S]>; error: ApiError
}
}[Exclude<keyof Responses<O>, SuccessCode<Responses<O>>>]
/** HTTP outcomes are typed; transport failures and aborts still reject the promise. */
export type ApiResult<O> = { ok: true; data: Success<O> } | DocumentedFailure<O>
| { ok: false; kind: 'unexpected'; status: number; body: unknown; error: ApiError }
export type EndpointError<M extends Method, P extends Endpoint<M>> = DocumentedFailure<Operation<M, P>>
/** A safe backend message, HTTP status, optional policy code and validation errors. */
export class ApiError extends Error {
readonly status: number
readonly code?: string
readonly errors?: Record<string, string[]>
constructor(status: number, message: string, errors?: Record<string, string[]>, code?: string) {
super(message)
this.name = 'ApiError'
this.status = status
this.code = code
this.errors = errors
}
}
function fieldErrors(value: unknown): Record<string, string[]> | undefined {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
if (!Object.values(value).every(messages =>
Array.isArray(messages) && messages.every(message => typeof message === 'string'),
)) return undefined
return value as Record<string, string[]>
}
let csrfTokenProvider: (() => Promise<string>) | undefined
/** Installed by conventional auth. Cookies stay browser-owned and HttpOnly. */
export function setCsrfTokenProvider(provider: () => Promise<string>): void { csrfTokenProvider = provider }
type RuntimeOptions = Omit<RequestInit, 'method' | 'body' | 'credentials' | 'redirect'> & {
body?: unknown; params?: { path?: Record<string, unknown>; query?: Record<string, unknown> }
}
function urlFor(template: string, params: RuntimeOptions['params']): string {
if (!template.startsWith('/') || template.startsWith('//') || /[\\?#\u0000-\u0020]/.test(template)) {
throw new Error('API paths must be absolute same-origin paths without a query or fragment')
}
const path = template.replace(/\{([^}]+)\}/g, (_, key: string) => {
const value = params?.path?.[key]
if (value === undefined || value === null || value === '.' || value === '..') {
throw new Error(`Missing or invalid path parameter: ${key}`)
}
return encodeURIComponent(String(value))
})
const query = new URLSearchParams()
for (const [key, value] of Object.entries(params?.query ?? {})) {
if (value !== undefined && value !== null) {
for (const item of Array.isArray(value) ? value : [value]) query.append(key, String(item))
}
}
return query.size ? `${path}?${query}` : path
}
async function perform(method: Method, path: string, options: RuntimeOptions = {}) {
const { params, body, ...init } = options
const headers = new Headers(init.headers)
if (body !== undefined) headers.set('Content-Type', 'application/json')
if (csrfTokenProvider && !['get', 'head', 'options'].includes(method)) {
headers.set('X-CSRF-Token', await csrfTokenProvider())
}
const response = await fetch(urlFor(path, params), {
...init, method: method.toUpperCase(), headers,
body: body === undefined ? undefined : JSON.stringify(body), credentials: 'same-origin', redirect: 'error',
})
const text = response.status === 204 || method === 'head' ? '' : await response.text()
let data: unknown
if (text.trim()) {
try { data = JSON.parse(text) } catch {
if (response.ok) throw new ApiError(response.status, 'Invalid JSON response')
}
}
if (response.ok) return { ok: true as const, data }
const envelope = typeof data === 'object' && data !== null ? data as Record<string, unknown> : undefined
const publicError = response.status < 500
const error = new ApiError(response.status,
!publicError ? 'Service temporarily unavailable. Please try again.'
: typeof envelope?.message === 'string' && envelope.message.trim() ? envelope.message : `Request failed: ${response.status}`,
publicError ? fieldErrors(envelope?.errors) : undefined,
publicError && typeof envelope?.code === 'string' ? envelope.code : undefined,
)
const codes = (apiResponses as Record<string, Partial<Record<Method, readonly number[]>>>)[path]?.[method]
return { ok: false as const, kind: codes?.includes(response.status) ? 'documented' as const : 'unexpected' as const,
status: response.status, body: data, error }
}
type Call<M extends Method> = <P extends Endpoint<M>>(path: P,
...args: Arguments<Operation<M, NoInfer<P>>>) => Promise<Success<Operation<M, P>>>
type SafeCall<M extends Method> = <P extends Endpoint<M>>(path: P,
...args: Arguments<Operation<M, NoInfer<P>>>) => Promise<ApiResult<Operation<M, P>>>
function call<M extends Method>(method: M): Call<M> {
return (async (path: string, options?: RuntimeOptions) => {
const result = await perform(method, path, options)
if (!result.ok) throw result.error
return result.data
}) as Call<M>
}
function safeCall<M extends Method>(method: M): SafeCall<M> {
// This adapter is the single unchecked network boundary. Like Fetch, generated
// types describe the server contract; they do not validate incoming JSON.
return ((path: string, options?: RuntimeOptions) => perform(method, path, options)) as SafeCall<M>
}
/** Method, path, parameters, body and response all derive from Rust's OpenAPI. */
export const api = {
get: call('get'), post: call('post'), put: call('put'), patch: call('patch'),
delete: call('delete'), head: call('head'), options: call('options'),
safe: {
get: safeCall('get'), post: safeCall('post'), put: safeCall('put'), patch: safeCall('patch'),
delete: safeCall('delete'), head: safeCall('head'), options: safeCall('options'),
},
}