// Gitea API client: as a user (OAuth token) or as peppa-bot (GITEA_TOKEN). import { PeppaError } from "./errors.ts"; export interface GiteaUser { id: number; login: string; full_name?: string; email?: string; avatar_url?: string; } export interface GiteaOrg { id: number; username: string; full_name?: string; } export interface GiteaRepo { id: number; name: string; full_name: string; owner: { login: string }; empty: boolean; private: boolean; default_branch: string; clone_url: string; html_url: string; permissions?: { admin: boolean; push: boolean; pull: boolean }; } export interface OAuthTokens { access_token: string; refresh_token?: string; expires_in?: number; } export class GiteaError extends PeppaError { constructor( readonly status: number, message: string, ) { super(message); } } export class GiteaClient { constructor( readonly baseUrl: string, private readonly token: string, ) {} async request(method: string, path: string, body?: unknown): Promise { const res = await fetch(`${this.baseUrl}/api/v1${path}`, { method, headers: { Authorization: `token ${this.token}`, "Content-Type": "application/json", Accept: "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(15_000), }); if (res.status === 204) return undefined as T; const text = await res.text(); if (!res.ok) { let msg = text; try { msg = (JSON.parse(text) as { message?: string }).message ?? text; } catch {} throw new GiteaError(res.status, `Gitea ${method} ${path}: ${res.status} ${msg}`.slice(0, 400)); } return (text ? JSON.parse(text) : undefined) as T; } me() { return this.request("GET", "/user"); } /** Orgs where the user may create repositories. */ async orgsWithRepoCreate(login: string): Promise { const orgs = await this.request("GET", "/user/orgs?limit=50"); const out: GiteaOrg[] = []; for (const o of orgs) { const p = await this.request<{ can_create_repository: boolean }>("GET", `/users/${encodeURIComponent(login)}/orgs/${encodeURIComponent(o.username)}/permissions`).catch(() => null); if (p?.can_create_repository) out.push(o); } return out; } async getRepo(owner: string, name: string): Promise { try { return await this.request("GET", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`); } catch (e) { if (e instanceof GiteaError && e.status === 404) return null; throw e; } } /** Creates a private repo; `asUser` = in the token owner's own namespace. */ createRepo(owner: string, asUser: boolean, name: string, description: string) { const body = { name, description, private: true, default_branch: "main", auto_init: false }; return this.request("POST", asUser ? "/user/repos" : `/orgs/${encodeURIComponent(owner)}/repos`, body); } addCollaborator(owner: string, repo: string, login: string, permission: "read" | "write" | "admin") { return this.request("PUT", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/collaborators/${encodeURIComponent(login)}`, { permission }); } deleteRepo(owner: string, repo: string) { return this.request("DELETE", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`); } } async function oauthToken(baseUrl: string, body: Record): Promise { const res = await fetch(`${baseUrl}/login/oauth/access_token`, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(15_000), }); const data = (await res.json().catch(() => ({}))) as OAuthTokens & { error?: string; error_description?: string }; if (!res.ok || !data.access_token) throw new GiteaError(res.status, `OAuth: ${data.error_description ?? data.error ?? res.status}`); return data; } export function oauthAuthorizeUrl(baseUrl: string, clientId: string, redirectUri: string, state: string): string { const q = new URLSearchParams({ client_id: clientId, redirect_uri: redirectUri, response_type: "code", state }); return `${baseUrl}/login/oauth/authorize?${q}`; } export function exchangeOAuthCode(baseUrl: string, clientId: string, clientSecret: string, code: string, redirectUri: string) { return oauthToken(baseUrl, { client_id: clientId, client_secret: clientSecret, code, grant_type: "authorization_code", redirect_uri: redirectUri }); } export function refreshOAuthToken(baseUrl: string, clientId: string, clientSecret: string, refreshToken: string) { return oauthToken(baseUrl, { client_id: clientId, client_secret: clientSecret, refresh_token: refreshToken, grant_type: "refresh_token" }); }