staging-tester / ocean-landing-serve / src/ lib/ live/ http.ts

export class ApiFailure extends Error {
	constructor(
		readonly status: number,
		message: string,
		readonly body: unknown = null
	) {
		super(message);
		this.name = 'ApiFailure';
	}
}

// Plain fetch, never the cached `api` client: identity and settings must never be answered from IndexedDB.
export async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
	const res = await fetch(path, {
		method,
		credentials: 'include',
		headers: { accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
		body: body === undefined ? undefined : JSON.stringify(body)
	});
	if (res.status === 204) return undefined as T;
	const text = await res.text();
	const json: unknown = text ? JSON.parse(text) : null;
	if (!res.ok) {
		const message = typeof json === 'object' && json !== null && 'error' in json ? String(json.error) : `${method} ${path} failed (${res.status})`;
		throw new ApiFailure(res.status, message, json);
	}
	return json as T;
}