Files
gitea-native/src/core/api/client.ts
T
JustZoe101 587bf732b5 feat: release asset upload, transfer, Actions secrets/variables/artifacts, admin, teams/projects, file search, reactions, attachments, package version delete
- client: multipart postForm; expo-document-picker + react-native-webview deps
- release assets: upload (DocumentPicker) and delete; run artifacts list
- repository transfer; Actions secrets + variables management screen
- admin (users/orgs/repos) screen gated on is_admin
- org teams, repo projects (read-only); find-file via recursive git tree
- issue reactions toggle and attachments list; package version delete
- endpoint tests (126 total)
2026-10-09 18:40:08 +02:00

390 lines
13 KiB
TypeScript

/**
* Typed HTTP client for the Gitea REST API.
*
* Responsibilities:
* - Build URLs (base + path + query) without ever putting the token in a URL.
* - Attach `Authorization: token <PAT>` from an injected secret provider.
* - Normalize every failure into {@link ApiError} (status-based kinds, timeouts,
* aborts, rate limits) so callers never string-match error messages.
* - Support cancellation (AbortSignal) and per-request timeouts.
* - Parse pagination metadata (`X-Total-Count` + page/limit heuristic).
*
* The client is intentionally transport-only: endpoint knowledge lives in
* `endpoints.ts`, server-state caching in feature hooks.
*/
import { ApiError, toApiError } from './errors';
import { apiBaseUrl } from './instance-url';
export type QueryValue =
| string
| number
| boolean
| null
| undefined
| readonly (string | number)[];
export type QueryParams = Record<string, QueryValue>;
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
export interface RequestOptions {
method?: HttpMethod;
query?: QueryParams;
body?: unknown;
signal?: AbortSignal;
timeoutMs?: number;
}
export interface PageMetaRaw {
total: number | null;
}
export interface RawResponse<T> {
data: T;
status: number;
total: number | null;
/** True when the server indicated more pages (total unknown uses a length heuristic). */
hasMore: boolean;
}
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
export interface GiteaClientOptions {
/** Instance base URL (no `/api/v1` suffix). */
baseUrl: string;
/** Personal access token. Omitted for unauthenticated probes (e.g. /version). */
token?: string;
timeoutMs?: number;
fetchImpl?: FetchLike;
}
export function buildQuery(params: QueryParams): string {
const search = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value === undefined || value === null) continue;
if (Array.isArray(value)) {
if (value.length > 0) search.append(key, value.join(','));
continue;
}
search.append(key, String(value));
}
const qs = search.toString();
return qs ? `?${qs}` : '';
}
export class GiteaClient {
readonly baseUrl: string;
readonly apiRoot: string;
private readonly token: string | undefined;
private readonly timeoutMs: number;
private readonly fetchImpl: FetchLike;
constructor(options: GiteaClientOptions) {
this.baseUrl = options.baseUrl;
this.apiRoot = apiBaseUrl(options.baseUrl);
this.token = options.token;
this.timeoutMs = options.timeoutMs ?? 15_000;
this.fetchImpl = options.fetchImpl ?? (fetch as FetchLike);
}
/** True when this client carries credentials. */
get isAuthenticated(): boolean {
return typeof this.token === 'string' && this.token.length > 0;
}
async get<T>(path: string, options: Omit<RequestOptions, 'method' | 'body'> = {}): Promise<T> {
const raw = await this.raw<T>(path, { ...options, method: 'GET' });
return raw.data;
}
async post<T>(path: string, body?: unknown, options: RequestOptions = {}): Promise<T> {
const raw = await this.raw<T>(path, { ...options, method: 'POST', body });
return raw.data;
}
async put<T>(path: string, body?: unknown, options: RequestOptions = {}): Promise<T> {
const raw = await this.raw<T>(path, { ...options, method: 'PUT', body });
return raw.data;
}
async patch<T>(path: string, body?: unknown, options: RequestOptions = {}): Promise<T> {
const raw = await this.raw<T>(path, { ...options, method: 'PATCH', body });
return raw.data;
}
async delete<T>(path: string, options: RequestOptions = {}): Promise<T> {
const raw = await this.raw<T>(path, { ...options, method: 'DELETE' });
return raw.data;
}
/**
* Fetches a plain-text response (e.g. a pull request `.diff`).
*
* Shares the timeout/abort/error-normalization contract of {@link raw}, but
* deliberately does not parse JSON. A non-2xx response is still mapped to an
* {@link ApiError} that never contains the URL or the token.
*/
async getText(path: string, options: Omit<RequestOptions, 'method' | 'body'> = {}): Promise<string> {
const url = `${this.apiRoot}${path}${buildQuery(options.query ?? {})}`;
const headers: Record<string, string> = { Accept: 'text/plain' };
if (this.token) headers.Authorization = `token ${this.token}`;
const controller = new AbortController();
let timedOut = false;
const timeoutMs = options.timeoutMs ?? this.timeoutMs;
const timer = setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs);
const onCallerAbort = () => controller.abort();
if (options.signal) {
if (options.signal.aborted) {
clearTimeout(timer);
throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' });
}
options.signal.addEventListener('abort', onCallerAbort);
}
let response: Response;
try {
response = await this.fetchImpl(url, { method: 'GET', headers, signal: controller.signal });
} catch (error) {
if (timedOut) {
throw new ApiError({
kind: 'timeout',
status: 0,
message: 'The server took too long to respond.',
});
}
if (options.signal?.aborted) {
throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' });
}
throw toApiError(error);
} finally {
clearTimeout(timer);
options.signal?.removeEventListener('abort', onCallerAbort);
}
const text = await response.text();
if (!response.ok) {
const kind = ApiError.kindForStatus(response.status);
throw new ApiError({
kind,
status: response.status,
message: messageForStatus(kind, response.status, null),
});
}
return text;
}
/**
* Uploads a multipart/form-data body (e.g. a release asset) and parses the
* JSON response. The multipart boundary is set by the platform, so we never
* set `Content-Type` ourselves. Errors are normalized like {@link raw}.
*/
async postForm<T>(
path: string,
form: FormData,
options: Omit<RequestOptions, 'method' | 'body'> = {},
): Promise<T> {
const url = `${this.apiRoot}${path}${buildQuery(options.query ?? {})}`;
const headers: Record<string, string> = { Accept: 'application/json' };
if (this.token) headers.Authorization = `token ${this.token}`;
const controller = new AbortController();
let timedOut = false;
const timeoutMs = options.timeoutMs ?? this.timeoutMs ?? 120_000;
const timer = setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs);
const onCallerAbort = () => controller.abort();
if (options.signal) {
if (options.signal.aborted) {
clearTimeout(timer);
throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' });
}
options.signal.addEventListener('abort', onCallerAbort);
}
let response: Response;
try {
response = await this.fetchImpl(url, {
method: 'POST',
headers,
body: form as unknown as BodyInit,
signal: controller.signal,
});
} catch (error) {
if (timedOut) {
throw new ApiError({ kind: 'timeout', status: 0, message: 'The upload took too long.' });
}
if (options.signal?.aborted) {
throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' });
}
throw toApiError(error);
} finally {
clearTimeout(timer);
options.signal?.removeEventListener('abort', onCallerAbort);
}
const text = await response.text();
let parsed: unknown = undefined;
if (text.length > 0) {
try {
parsed = JSON.parse(text);
} catch {
parsed = undefined;
}
}
if (!response.ok) {
const serverMessage =
parsed && typeof parsed === 'object' && 'message' in parsed
? String((parsed as { message: unknown }).message)
: null;
const kind = ApiError.kindForStatus(response.status);
throw new ApiError({
kind,
status: response.status,
serverMessage,
message: messageForStatus(kind, response.status, serverMessage),
});
}
return parsed as T;
}
/**
* Performs a request and returns data plus pagination metadata.
* `hasMore` uses `X-Total-Count` when present, otherwise a length heuristic
* against the requested page size (Gitea does not consistently emit totals).
*/
async raw<T>(path: string, options: RequestOptions = {}): Promise<RawResponse<T>> {
const method = options.method ?? 'GET';
const url = `${this.apiRoot}${path}${buildQuery(options.query ?? {})}`;
const headers: Record<string, string> = { Accept: 'application/json' };
if (this.token) headers.Authorization = `token ${this.token}`;
let body: string | undefined;
if (options.body !== undefined) {
headers['Content-Type'] = 'application/json';
body = JSON.stringify(options.body);
}
const controller = new AbortController();
let timedOut = false;
const timeoutMs = options.timeoutMs ?? this.timeoutMs;
const timer = setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs);
const onCallerAbort = () => controller.abort();
if (options.signal) {
if (options.signal.aborted) {
clearTimeout(timer);
throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' });
}
options.signal.addEventListener('abort', onCallerAbort);
}
let response: Response;
try {
response = await this.fetchImpl(url, {
method,
headers,
body,
signal: controller.signal,
});
} catch (error) {
if (timedOut) {
throw new ApiError({
kind: 'timeout',
status: 0,
message: 'The server took too long to respond.',
});
}
if (options.signal?.aborted) {
throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' });
}
// Transport-level failure (DNS, TLS, offline). toApiError never echoes the URL/token.
throw toApiError(error);
} finally {
clearTimeout(timer);
options.signal?.removeEventListener('abort', onCallerAbort);
}
const totalRaw = response.headers.get('X-Total-Count');
const total = totalRaw !== null && totalRaw !== '' && !Number.isNaN(Number(totalRaw))
? Number(totalRaw)
: null;
const text = await response.text();
let parsed: unknown = undefined;
if (text.length > 0) {
try {
parsed = JSON.parse(text);
} catch {
if (response.ok) {
throw new ApiError({
kind: 'invalid-response',
status: response.status,
message: 'The server returned a response the app could not read.',
});
}
}
}
if (!response.ok) {
const serverMessage =
parsed && typeof parsed === 'object' && 'message' in parsed
? String((parsed as { message: unknown }).message)
: text.length > 0 && text.length < 300
? text
: null;
const retryAfterHeader = response.headers.get('Retry-After');
const retryAfterSeconds =
response.status === 429 && retryAfterHeader && !Number.isNaN(Number(retryAfterHeader))
? Number(retryAfterHeader)
: null;
const kind = ApiError.kindForStatus(response.status);
throw new ApiError({
kind,
status: response.status,
serverMessage,
retryAfterSeconds,
message: messageForStatus(kind, response.status, serverMessage),
});
}
const requestedLimit =
typeof options.query?.limit === 'number' ? options.query.limit : null;
const requestedPage = typeof options.query?.page === 'number' ? options.query.page : 1;
const items = Array.isArray(parsed) ? (parsed as unknown[]).length : null;
const hasMore =
requestedLimit === null
? false
: total !== null
? requestedPage * requestedLimit < total
: items !== null && items >= requestedLimit;
return { data: parsed as T, status: response.status, total, hasMore };
}
}
function messageForStatus(kind: ApiError['kind'], status: number, serverMessage: string | null): string {
if (serverMessage) return serverMessage;
switch (kind) {
case 'unauthorized':
return 'This Personal Access Token is no longer valid. It may have expired or been revoked.';
case 'forbidden':
return 'You do not have permission to perform this action.';
case 'not-found':
return 'Not found on this instance.';
case 'rate-limit':
return 'The instance is rate limiting requests. Try again in a moment.';
case 'server':
return `The instance returned an error (HTTP ${status}).`;
default:
return `Request failed (HTTP ${status}).`;
}
}