14 Commits
v1.0.2 ... main

Author SHA1 Message Date
29f143d35a v1.5.0 2026-03-02 13:09:44 +00:00
1b685091af feat(gitea): add domain model classes, helpers, and refactor GiteaClient internals; expand README with usage and docs 2026-03-02 13:09:44 +00:00
5e7a84c6c3 v1.4.0 2026-03-02 11:47:12 +00:00
fd26379324 feat(gitea): add Actions API support: list filters, run/job endpoints, dispatch, and richer types 2026-03-02 11:47:12 +00:00
7caa033115 v1.3.0 2026-03-02 09:31:09 +00:00
2517ab863b feat(gitea): add repository branches and tags support: new IGiteaBranch/IGiteaTag interfaces and getRepoBranches/getRepoTags client methods 2026-03-02 09:31:09 +00:00
1f41870be1 v1.2.0 2026-02-28 11:13:36 +00:00
5423039f89 feat(giteaclient): add deleteRepo method to delete a repository via Gitea API 2026-02-28 11:13:36 +00:00
a34b05c55c v1.1.0 2026-02-28 10:23:51 +00:00
ffc644cab4 feat(orgs): add organization and organization-repository APIs: getOrg, getOrgRepos, createOrg, createOrgRepo 2026-02-28 10:23:51 +00:00
4c48a07ef7 v1.0.3 2026-02-24 13:00:16 +00:00
e3b013b906 fix(gitea): no changes detected in the diff; no code or doc updates 2026-02-24 13:00:16 +00:00
89bd770f32 fix(test): await async getEnvVarOnDemand calls in test setup 2026-02-24 12:59:10 +00:00
a703bc4e10 docs(core): add comprehensive readme with full API documentation 2026-02-24 12:57:27 +00:00
16 changed files with 1658 additions and 74 deletions

View File

@@ -1,5 +1,52 @@
# Changelog
## 2026-03-02 - 1.5.0 - feat(gitea)
add domain model classes, helpers, and refactor GiteaClient internals; expand README with usage and docs
- Introduce domain classes: GiteaOrganization, GiteaRepository, GiteaActionRun, GiteaActionRunJob (+steps), GiteaBranch, GiteaTag, GiteaSecret
- Add helper utilities: autoPaginate, computeDuration, resolveGiteaStatus, extractRefFromPath, extractWorkflowIdFromPath, toGiteaApiStatus
- Refactor GiteaClient: consolidate low-level request helpers, add internal request* methods for action-run/job endpoints, requestText/requestBinary support, and PATCH support
- Update raw API interfaces (IGiteaActionRun, IGiteaRepository, IGiteaOrganization, IGiteaUser) to match Gitea 1.25 shapes
- Export new domain classes, helpers and commit info from ts/index.ts
- Revise README: Quick Start, class/method documentation, license and company info
## 2026-03-02 - 1.4.0 - feat(gitea)
add Actions API support: list filters, run/job endpoints, dispatch, and richer types
- Introduce IActionRunListOptions to allow filtering action runs by status, branch, event, and actor
- Update getActionRuns to accept filtering options and build URL query parameters
- Add new client methods: getActionRun, getJobLog, rerunAction, cancelAction, and dispatchWorkflow
- Expand IGiteaActionRun and IGiteaActionRunJob shapes and add IGiteaActionRunJobStep for more detailed run/job metadata
- Export new types (IActionRunListOptions, IGiteaActionRunJobStep) from the package index
## 2026-03-02 - 1.3.0 - feat(gitea)
add repository branches and tags support: new IGiteaBranch/IGiteaTag interfaces and getRepoBranches/getRepoTags client methods
- Added IGiteaBranch and IGiteaTag interfaces (ts/gitea.interfaces.ts).
- Added getRepoBranches and getRepoTags methods with pagination support to Gitea client (ts/gitea.classes.giteaclient.ts).
- Exported the new interfaces from the package index (ts/index.ts).
## 2026-02-28 - 1.2.0 - feat(giteaclient)
add deleteRepo method to delete a repository via Gitea API
- Implements deleteRepo(owner: string, repo: string): Promise<void>
- Uses DELETE /api/v1/repos/{owner}/{repo} and encodes owner and repo with encodeURIComponent
## 2026-02-28 - 1.1.0 - feat(orgs)
add organization and organization-repository APIs: getOrg, getOrgRepos, createOrg, createOrgRepo
- Added getOrg(orgName): fetch a single organization by name
- Added getOrgRepos(orgName, opts?): list repositories in an organization with pagination, sorting by updated, and optional search query
- Added createOrg(name, opts?): create a new organization with fullName, description, and visibility (defaults to public)
- Added createOrgRepo(orgName, name, opts?): create a repository within an organization; description optional and private defaults to true
- Endpoints use encodeURIComponent for orgName in URLs to ensure safe requests
## 2026-02-24 - 1.0.3 - fix(gitea)
no changes detected in the diff; no code or doc updates
- No files changed in this commit (empty diff).
- Current package version in package.json is 1.0.2; no version bump required.
## 2026-02-24 - 1.0.2 - fix()
no code changes to commit — repository unchanged

View File

@@ -1,6 +1,6 @@
{
"name": "@apiclient.xyz/gitea",
"version": "1.0.2",
"version": "1.5.0",
"private": false,
"description": "A TypeScript client for the Gitea API, providing easy access to repositories, organizations, secrets, and action runs.",
"main": "dist_ts/index.js",

532
readme.md
View File

@@ -1,30 +1,538 @@
# @apiclient.xyz/gitea
A TypeScript client for the Gitea API, providing easy access to repositories, organizations, secrets, and action runs.
A fully typed TypeScript client for the Gitea API. Manage repositories, organizations, secrets, branches, tags, and CI/CD action runs with a clean, object-oriented interface and built-in auto-pagination.
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Install
```sh
npm install @apiclient.xyz/gitea
# or
pnpm install @apiclient.xyz/gitea
```
## Quick Start
```typescript
import { GiteaClient } from '@apiclient.xyz/gitea';
// 1. Connect to your Gitea instance
const client = new GiteaClient('https://gitea.example.com', 'your-api-token');
// 2. Verify the connection
const { ok } = await client.testConnection();
console.log(ok ? '✅ Connected!' : '❌ Connection failed');
// 3. List all your repos
const repos = await client.getRepos();
repos.forEach(repo => console.log(`📦 ${repo.fullName}`));
```
That's it — you're up and running. 🚀
## Usage
All examples use ESM imports and top-level `await`. The package ships as a **pure ESM module** with full TypeScript type declarations.
---
### 🔌 Creating a Client
```typescript
import { GiteaClient } from '@apiclient.xyz/gitea';
const client = new GiteaClient('https://gitea.example.com', 'your-api-token');
// Test connection
const result = await client.testConnection();
// List repositories
const repos = await client.getRepos();
// Manage secrets
await client.setRepoSecret('owner/repo', 'SECRET_KEY', 'secret-value');
```
## License
- `baseUrl` — Your Gitea instance root URL (trailing slashes are stripped automatically)
- `token` — An API token generated in Gitea under **Settings > Applications**
MIT
### 🩺 Testing the Connection
```typescript
const result = await client.testConnection();
if (result.ok) {
console.log('Connected successfully.');
} else {
console.error('Connection failed:', result.error);
}
```
---
### 📦 Repositories
The client returns rich `GiteaRepository` objects with built-in methods for managing branches, tags, secrets, action runs, and more.
#### List / Search Repositories
```typescript
// Get all repositories (auto-paginated — fetches every page automatically)
const allRepos = await client.getRepos();
// Search with a query
const results = await client.getRepos({ search: 'my-project' });
// Grab a specific page
const page2 = await client.getRepos({ page: 2, perPage: 20 });
for (const repo of results) {
console.log(`${repo.fullName}${repo.description}`);
console.log(` Default branch: ${repo.defaultBranch}`);
console.log(` Private: ${repo.isPrivate}`);
console.log(` Topics: ${repo.topics.join(', ')}`);
}
```
#### Get a Single Repository
```typescript
const repo = await client.getRepo('my-org/my-repo');
console.log(repo.fullName, repo.htmlUrl);
```
#### Create a Repository in an Organization
```typescript
const newRepo = await client.createOrgRepo('my-org', 'new-service', {
description: 'A brand new microservice',
private: true,
});
console.log(`Created: ${newRepo.htmlUrl}`);
```
#### Update Repository Properties
```typescript
const repo = await client.getRepo('my-org/my-repo');
await repo.update({
description: 'Updated description',
defaultBranch: 'develop',
private: false,
archived: false,
});
```
#### Manage Topics
```typescript
await repo.setTopics(['typescript', 'api', 'gitea']);
```
#### Avatars
```typescript
// Upload an avatar (base64-encoded image)
await repo.setAvatar(base64ImageString);
// Remove the avatar
await repo.deleteAvatar();
```
#### Transfer Ownership
```typescript
await repo.transfer('new-owner-org');
```
#### Delete a Repository
```typescript
await repo.delete();
```
---
### 🏢 Organizations
Organizations are returned as rich `GiteaOrganization` objects.
#### List All Organizations
```typescript
// Auto-paginated — fetches every org across all pages
const orgs = await client.getOrgs();
for (const org of orgs) {
console.log(`${org.name} (${org.repoCount} repos) — ${org.visibility}`);
}
```
#### Get a Single Organization
```typescript
const org = await client.getOrg('my-org');
console.log(org.fullName, org.description);
```
#### Create an Organization
```typescript
const newOrg = await client.createOrg('new-team', {
fullName: 'New Team',
description: 'Our shiny new team',
visibility: 'public',
});
```
#### List Repos in an Organization
```typescript
const org = await client.getOrg('my-org');
const repos = await org.getRepos({ search: 'api' });
```
#### Update Organization Properties
```typescript
await org.update({
description: 'Updated org description',
visibility: 'private',
fullName: 'My Organization (Renamed)',
});
```
#### Organization Avatars
```typescript
await org.setAvatar(base64ImageString);
await org.deleteAvatar();
```
#### Delete an Organization
```typescript
await org.delete();
```
---
### 🔑 Secrets Management
Manage Gitea Actions secrets at both the **repository** and **organization** level. Perfect for CI/CD automation.
#### Repository Secrets
```typescript
const repo = await client.getRepo('my-org/my-repo');
// List all secrets
const secrets = await repo.getSecrets();
for (const secret of secrets) {
console.log(`🔒 ${secret.name} (created ${secret.createdAt})`);
}
// Create or update a secret
await repo.setSecret('DEPLOY_TOKEN', 's3cret-value');
// Delete a secret
await repo.deleteSecret('DEPLOY_TOKEN');
```
#### Organization Secrets
```typescript
const org = await client.getOrg('my-org');
// List all org-level secrets
const orgSecrets = await org.getSecrets();
// Create or update
await org.setSecret('NPM_TOKEN', 'npm_abc123');
// Delete
await org.deleteSecret('NPM_TOKEN');
```
---
### 🌿 Branches & Tags
Fetch branches and tags for any repository — auto-paginated by default.
```typescript
const repo = await client.getRepo('my-org/my-repo');
// Get all branches
const branches = await repo.getBranches();
for (const branch of branches) {
console.log(`Branch: ${branch.name} @ ${branch.commitSha}`);
}
// Get all tags
const tags = await repo.getTags();
for (const tag of tags) {
console.log(`Tag: ${tag.name} @ ${tag.commitSha}`);
}
```
---
### ⚡ Gitea Actions (CI/CD Runs)
Full support for listing, filtering, inspecting, and managing Gitea Actions workflow runs and jobs.
#### List Action Runs
```typescript
const repo = await client.getRepo('my-org/my-repo');
// Get all recent runs (auto-paginated)
const runs = await repo.getActionRuns();
for (const run of runs) {
console.log(`#${run.runNumber} ${run.displayTitle}`);
console.log(` Status: ${run.resolvedStatus}`);
console.log(` Branch: ${run.headBranch}`);
console.log(` Event: ${run.event}`);
console.log(` Duration: ${run.duration}s`);
console.log(` Triggered by: ${run.actorLogin}`);
}
```
#### Filter Runs
```typescript
// Filter by status, branch, event, or actor
const failedRuns = await repo.getActionRuns({ status: 'failed' });
const mainRuns = await repo.getActionRuns({ branch: 'main' });
const pushRuns = await repo.getActionRuns({ event: 'push' });
const myRuns = await repo.getActionRuns({ actor: 'phil' });
// Combine filters
const filtered = await repo.getActionRuns({
status: 'running',
branch: 'develop',
event: 'pull_request',
});
```
**Supported status values:** `running`, `failed`, `pending`, `success`, `skipped`, `waiting`, `canceled` — automatically translated to Gitea's native API values.
#### Inspect Jobs & Steps
```typescript
const runs = await repo.getActionRuns();
const latestRun = runs[0];
// Get all jobs in a run
const jobs = await latestRun.getJobs();
for (const job of jobs) {
console.log(`Job: ${job.name} [${job.resolvedStatus}] (${job.duration}s)`);
console.log(` Runner: ${job.runnerName}`);
// Inspect individual steps
for (const step of job.steps) {
console.log(` Step ${step.number}: ${step.name}${step.resolvedStatus} (${step.duration}s)`);
}
}
```
#### Fetch Job Logs
```typescript
const jobs = await latestRun.getJobs();
const log = await jobs[0].getLog();
console.log(log); // Raw log output
```
#### Re-run a Workflow
```typescript
// Re-dispatches the workflow on the same ref
await latestRun.rerun();
// With custom inputs
await latestRun.rerun({ environment: 'staging' });
```
#### Delete an Action Run
```typescript
await latestRun.delete();
```
---
### 🔄 Auto-Pagination
By default, all list methods (`getRepos`, `getOrgs`, `getBranches`, `getTags`, `getActionRuns`, etc.) **auto-paginate** and return every item across all pages.
To disable auto-pagination and fetch a specific page, pass the `page` option:
```typescript
// Only fetch page 3
const page3 = await client.getRepos({ page: 3, perPage: 25 });
```
The `autoPaginate` helper is also exported if you need it for custom endpoints:
```typescript
import { autoPaginate } from '@apiclient.xyz/gitea';
```
---
## 🗂️ Exported Classes
| Class | Description |
|---|---|
| `GiteaClient` | Main entry point — connects to a Gitea instance |
| `GiteaOrganization` | Rich object for an organization with repos, secrets, avatars |
| `GiteaRepository` | Rich object for a repo with branches, tags, secrets, runs |
| `GiteaBranch` | Branch with name and commit SHA |
| `GiteaTag` | Tag with name and commit SHA |
| `GiteaSecret` | Secret metadata (name + creation timestamp) |
| `GiteaActionRun` | CI/CD workflow run with jobs, rerun, and delete |
| `GiteaActionRunJob` | Individual job within a run, with steps and log access |
| `GiteaActionRunJobStep` | Individual step within a job |
## 🧩 Exported Interfaces
All interfaces are exported for type annotations:
```typescript
import type {
IGiteaUser,
IGiteaRepository,
IGiteaOrganization,
IGiteaSecret,
IGiteaBranch,
IGiteaTag,
IGiteaActionRun,
IGiteaActionRunJob,
IGiteaActionRunJobStep,
ITestConnectionResult,
IListOptions,
IActionRunListOptions,
} from '@apiclient.xyz/gitea';
```
## 🛠️ Exported Helpers
Utility functions for working with Gitea API data:
| Helper | Description |
|---|---|
| `autoPaginate(fetchPage, opts?)` | Auto-paginate any list endpoint |
| `computeDuration(startedAt, completedAt)` | Compute duration in seconds from ISO timestamps |
| `resolveGiteaStatus(status, conclusion)` | Resolve Gitea's split status/conclusion into a single string |
| `extractRefFromPath(path)` | Extract a human-readable ref from Gitea's `path` field |
| `extractWorkflowIdFromPath(path)` | Extract the workflow filename from Gitea's `path` field |
| `toGiteaApiStatus(status)` | Translate friendly status names to Gitea API values |
---
## Full API Reference
### `GiteaClient`
| Method | Signature | Description |
|---|---|---|
| `constructor` | `(baseUrl: string, token: string)` | Create a new client |
| `testConnection` | `() => Promise<ITestConnectionResult>` | Verify credentials and connectivity |
| `getRepos` | `(opts?: IListOptions) => Promise<GiteaRepository[]>` | List/search repositories (auto-paginated) |
| `getRepo` | `(ownerRepo: string) => Promise<GiteaRepository>` | Get a single repository |
| `createOrgRepo` | `(orgName, name, opts?) => Promise<GiteaRepository>` | Create a repo in an organization |
| `getOrgs` | `(opts?: IListOptions) => Promise<GiteaOrganization[]>` | List organizations (auto-paginated) |
| `getOrg` | `(orgName: string) => Promise<GiteaOrganization>` | Get a single organization |
| `createOrg` | `(name, opts?) => Promise<GiteaOrganization>` | Create a new organization |
### `GiteaRepository`
| Method | Description |
|---|---|
| `getBranches(opts?)` | List branches (auto-paginated) |
| `getTags(opts?)` | List tags (auto-paginated) |
| `getSecrets()` | List repository secrets |
| `setSecret(key, value)` | Create or update a secret |
| `deleteSecret(key)` | Delete a secret |
| `getActionRuns(opts?)` | List CI/CD runs with optional filters |
| `update(data)` | Update repo properties (name, description, default branch, etc.) |
| `setTopics(topics)` | Replace all repository topics |
| `setAvatar(base64)` | Upload an avatar image |
| `deleteAvatar()` | Remove the avatar |
| `transfer(newOwner)` | Transfer ownership |
| `delete()` | Delete the repository |
### `GiteaOrganization`
| Method | Description |
|---|---|
| `getRepos(opts?)` | List org repositories (auto-paginated) |
| `getSecrets()` | List organization secrets |
| `setSecret(key, value)` | Create or update an org secret |
| `deleteSecret(key)` | Delete an org secret |
| `update(data)` | Update org properties (description, visibility, fullName) |
| `setAvatar(base64)` | Upload an avatar image |
| `deleteAvatar()` | Remove the avatar |
| `delete()` | Delete the organization |
### `GiteaActionRun`
| Property | Type | Description |
|---|---|---|
| `id` | `number` | Run ID |
| `runNumber` | `number` | Sequential run number |
| `name` | `string` | Workflow name |
| `displayTitle` | `string` | Display title of the run |
| `status` | `string` | Raw status (running, waiting, completed) |
| `conclusion` | `string` | Raw conclusion (success, failure, cancelled) |
| `resolvedStatus` | `string` | **Computed** — single human-readable status |
| `duration` | `number` | **Computed** — duration in seconds |
| `headBranch` | `string` | Branch that triggered the run |
| `headSha` | `string` | Commit SHA |
| `event` | `string` | Trigger event (push, pull_request, etc.) |
| `ref` | `string` | **Computed** — human-readable ref |
| `workflowId` | `string` | **Computed** — workflow filename |
| `actorLogin` | `string` | User who triggered the run |
| Method | Description |
|---|---|
| `getJobs()` | List all jobs in this run |
| `rerun(inputs?)` | Re-dispatch the workflow on the same ref |
| `delete()` | Delete this action run |
### `GiteaActionRunJob`
| Property | Type | Description |
|---|---|---|
| `id` | `number` | Job ID |
| `name` | `string` | Job name |
| `resolvedStatus` | `string` | **Computed** — resolved status |
| `duration` | `number` | **Computed** — duration in seconds |
| `steps` | `GiteaActionRunJobStep[]` | Individual steps |
| `runnerName` | `string` | Runner that executed the job |
| Method | Description |
|---|---|
| `getLog()` | Fetch raw log output for this job |
---
## License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@@ -7,8 +7,8 @@ const testQenv = new qenv.Qenv('./', '.nogit/');
let giteaClient: GiteaClient;
tap.test('should create a GiteaClient instance', async () => {
const baseUrl = testQenv.getEnvVarOnDemand('GITEA_BASE_URL') || 'https://gitea.lossless.digital';
const token = testQenv.getEnvVarOnDemand('GITEA_TOKEN') || '';
const baseUrl = (await testQenv.getEnvVarOnDemand('GITEA_BASE_URL')) || 'https://gitea.lossless.digital';
const token = (await testQenv.getEnvVarOnDemand('GITEA_TOKEN')) || '';
giteaClient = new GiteaClient(baseUrl, token);
expect(giteaClient).toBeInstanceOf(GiteaClient);
});

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@apiclient.xyz/gitea',
version: '1.0.2',
version: '1.5.0',
description: 'A TypeScript client for the Gitea API, providing easy access to repositories, organizations, secrets, and action runs.'
}

View File

@@ -0,0 +1,124 @@
import type { GiteaClient } from './gitea.classes.giteaclient.js';
import type { IGiteaActionRun } from './gitea.interfaces.js';
import { GiteaActionRunJob } from './gitea.classes.actionrunjob.js';
import {
computeDuration,
resolveGiteaStatus,
extractRefFromPath,
extractWorkflowIdFromPath,
} from './gitea.helpers.js';
export class GiteaActionRun {
// Raw data
public readonly id: number;
public readonly runNumber: number;
public readonly runAttempt: number;
public readonly name: string;
public readonly displayTitle: string;
public readonly status: string;
public readonly conclusion: string;
public readonly headBranch: string;
public readonly headSha: string;
public readonly htmlUrl: string;
public readonly event: string;
public readonly path: string;
public readonly startedAt: string;
public readonly completedAt: string;
public readonly actorLogin: string;
public readonly triggerActorLogin: string;
// Computed
public readonly resolvedStatus: string;
public readonly duration: number;
public readonly ref: string;
public readonly workflowId: string;
/** @internal */
constructor(
private client: GiteaClient,
private ownerRepo: string,
raw: IGiteaActionRun,
) {
this.id = raw.id;
this.runNumber = raw.run_number || 0;
this.runAttempt = raw.run_attempt || 1;
this.name = raw.name || '';
this.displayTitle = raw.display_title || this.name;
this.status = raw.status || '';
this.conclusion = raw.conclusion || '';
this.headBranch = raw.head_branch || '';
this.headSha = raw.head_sha || '';
this.htmlUrl = raw.html_url || '';
this.event = raw.event || '';
this.path = raw.path || '';
this.startedAt = raw.started_at || '';
this.completedAt = raw.completed_at || '';
this.actorLogin = raw.actor?.login || '';
this.triggerActorLogin = raw.trigger_actor?.login || '';
// Computed properties
this.resolvedStatus = resolveGiteaStatus(this.status, this.conclusion);
this.duration = computeDuration(this.startedAt, this.completedAt);
this.ref = this.headBranch || extractRefFromPath(this.path);
this.workflowId = extractWorkflowIdFromPath(this.path);
}
// ---------------------------------------------------------------------------
// Jobs
// ---------------------------------------------------------------------------
async getJobs(): Promise<GiteaActionRunJob[]> {
const jobs = await this.client.requestGetActionRunJobs(this.ownerRepo, this.id);
return jobs.map(j => new GiteaActionRunJob(this.client, this.ownerRepo, j));
}
// ---------------------------------------------------------------------------
// Actions
// ---------------------------------------------------------------------------
/**
* Re-dispatch this workflow on the same ref.
* Gitea 1.25 has no rerun endpoint, so this dispatches the workflow again.
*/
async rerun(inputs?: Record<string, string>): Promise<void> {
const wfId = this.workflowId;
if (!wfId) {
throw new Error(`Cannot rerun: no workflow ID found in path "${this.path}"`);
}
await this.client.requestDispatchWorkflow(this.ownerRepo, wfId, this.ref, inputs);
}
/**
* Delete this action run.
*/
async delete(): Promise<void> {
await this.client.requestDeleteActionRun(this.ownerRepo, this.id);
}
// ---------------------------------------------------------------------------
// Serialization
// ---------------------------------------------------------------------------
toJSON(): IGiteaActionRun {
return {
id: this.id,
name: this.name,
workflow_id: this.workflowId,
status: this.status,
conclusion: this.conclusion,
head_branch: this.headBranch,
head_sha: this.headSha,
html_url: this.htmlUrl,
event: this.event,
path: this.path,
display_title: this.displayTitle,
run_number: this.runNumber,
run_attempt: this.runAttempt,
started_at: this.startedAt,
completed_at: this.completedAt,
actor: { id: 0, login: this.actorLogin, login_name: '', source_id: 0, full_name: '', email: '', avatar_url: '' },
trigger_actor: { id: 0, login: this.triggerActorLogin, login_name: '', source_id: 0, full_name: '', email: '', avatar_url: '' },
repository: { id: 0, name: '', full_name: this.ownerRepo, html_url: '' },
};
}
}

View File

@@ -0,0 +1,118 @@
import type { GiteaClient } from './gitea.classes.giteaclient.js';
import type { IGiteaActionRunJob, IGiteaActionRunJobStep } from './gitea.interfaces.js';
import { computeDuration, resolveGiteaStatus } from './gitea.helpers.js';
export class GiteaActionRunJobStep {
public readonly name: string;
public readonly number: number;
public readonly status: string;
public readonly conclusion: string;
public readonly resolvedStatus: string;
public readonly startedAt: string;
public readonly completedAt: string;
public readonly duration: number;
constructor(raw: IGiteaActionRunJobStep) {
this.name = raw.name || '';
this.number = raw.number || 0;
this.status = raw.status || '';
this.conclusion = raw.conclusion || '';
this.resolvedStatus = resolveGiteaStatus(this.status, this.conclusion);
this.startedAt = raw.started_at || '';
this.completedAt = raw.completed_at || '';
this.duration = computeDuration(this.startedAt, this.completedAt);
}
toJSON(): IGiteaActionRunJobStep {
return {
name: this.name,
number: this.number,
status: this.status,
conclusion: this.conclusion,
started_at: this.startedAt,
completed_at: this.completedAt,
};
}
}
export class GiteaActionRunJob {
// Raw data
public readonly id: number;
public readonly runId: number;
public readonly name: string;
public readonly workflowName: string;
public readonly headBranch: string;
public readonly headSha: string;
public readonly status: string;
public readonly conclusion: string;
public readonly htmlUrl: string;
public readonly startedAt: string;
public readonly completedAt: string;
public readonly labels: string[];
public readonly runnerId: number;
public readonly runnerName: string;
public readonly steps: GiteaActionRunJobStep[];
// Computed
public readonly resolvedStatus: string;
public readonly duration: number;
/** @internal */
constructor(
private client: GiteaClient,
private ownerRepo: string,
raw: IGiteaActionRunJob,
) {
this.id = raw.id;
this.runId = raw.run_id || 0;
this.name = raw.name || '';
this.workflowName = raw.workflow_name || '';
this.headBranch = raw.head_branch || '';
this.headSha = raw.head_sha || '';
this.status = raw.status || '';
this.conclusion = raw.conclusion || '';
this.htmlUrl = raw.html_url || '';
this.startedAt = raw.started_at || '';
this.completedAt = raw.completed_at || '';
this.labels = raw.labels || [];
this.runnerId = raw.runner_id || 0;
this.runnerName = raw.runner_name || '';
this.steps = (raw.steps || []).map(s => new GiteaActionRunJobStep(s));
// Computed
this.resolvedStatus = resolveGiteaStatus(this.status, this.conclusion);
this.duration = computeDuration(this.startedAt, this.completedAt);
}
// ---------------------------------------------------------------------------
// Log
// ---------------------------------------------------------------------------
async getLog(): Promise<string> {
return this.client.requestGetJobLog(this.ownerRepo, this.id);
}
// ---------------------------------------------------------------------------
// Serialization
// ---------------------------------------------------------------------------
toJSON(): IGiteaActionRunJob {
return {
id: this.id,
run_id: this.runId,
name: this.name,
workflow_name: this.workflowName,
head_branch: this.headBranch,
head_sha: this.headSha,
status: this.status,
conclusion: this.conclusion,
html_url: this.htmlUrl,
started_at: this.startedAt,
completed_at: this.completedAt,
steps: this.steps.map(s => s.toJSON()),
labels: this.labels,
runner_id: this.runnerId,
runner_name: this.runnerName,
};
}
}

View File

@@ -0,0 +1,18 @@
import type { IGiteaBranch } from './gitea.interfaces.js';
export class GiteaBranch {
public readonly name: string;
public readonly commitSha: string;
constructor(raw: IGiteaBranch) {
this.name = raw.name || '';
this.commitSha = raw.commit?.id || '';
}
toJSON(): IGiteaBranch {
return {
name: this.name,
commit: { id: this.commitSha },
};
}
}

View File

@@ -1,32 +1,37 @@
import * as plugins from './gitea.plugins.js';
import { logger } from './gitea.logging.js';
import type {
IGiteaUser,
IGiteaRepository,
IGiteaOrganization,
IGiteaSecret,
IGiteaBranch,
IGiteaTag,
IGiteaActionRun,
IGiteaActionRunJob,
ITestConnectionResult,
IListOptions,
IActionRunListOptions,
} from './gitea.interfaces.js';
import { GiteaOrganization } from './gitea.classes.organization.js';
import { GiteaRepository } from './gitea.classes.repository.js';
import { autoPaginate, toGiteaApiStatus } from './gitea.helpers.js';
export class GiteaClient {
private baseUrl: string;
private token: string;
constructor(baseUrl: string, token: string) {
// Remove trailing slash if present
this.baseUrl = baseUrl.replace(/\/+$/, '');
this.token = token;
}
// ---------------------------------------------------------------------------
// HTTP helpers
// ---------------------------------------------------------------------------
// ===========================================================================
// HTTP helpers (internal)
// ===========================================================================
private async request<T = any>(
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
/** @internal */
async request<T = any>(
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
path: string,
data?: any,
customHeaders?: Record<string, string>,
@@ -59,6 +64,9 @@ export class GiteaClient {
case 'PUT':
response = await builder.put();
break;
case 'PATCH':
response = await builder.patch();
break;
case 'DELETE':
response = await builder.delete();
break;
@@ -76,7 +84,8 @@ export class GiteaClient {
}
}
private async requestText(
/** @internal */
async requestText(
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
path: string,
): Promise<string> {
@@ -111,9 +120,22 @@ export class GiteaClient {
return response.text();
}
// ---------------------------------------------------------------------------
// Connection
// ---------------------------------------------------------------------------
/** @internal — fetch binary data (e.g. avatar images) */
async requestBinary(path: string): Promise<Uint8Array> {
const url = `${this.baseUrl}${path}`;
const response = await fetch(url, {
headers: { 'Authorization': `token ${this.token}` },
});
if (!response.ok) {
throw new Error(`GET ${path}: ${response.status} ${response.statusText}`);
}
const buf = await response.arrayBuffer();
return new Uint8Array(buf);
}
// ===========================================================================
// Public API — Connection
// ===========================================================================
public async testConnection(): Promise<ITestConnectionResult> {
try {
@@ -124,11 +146,81 @@ export class GiteaClient {
}
}
// ---------------------------------------------------------------------------
// Repositories
// ---------------------------------------------------------------------------
// ===========================================================================
// Public API — Organizations (returns rich objects)
// ===========================================================================
public async getRepos(opts?: IListOptions): Promise<IGiteaRepository[]> {
/**
* Get all organizations (auto-paginated).
*/
public async getOrgs(opts?: IListOptions): Promise<GiteaOrganization[]> {
return autoPaginate(
(page, perPage) => this.requestGetOrgs({ ...opts, page, perPage }),
opts,
).then(orgs => orgs.map(o => new GiteaOrganization(this, o)));
}
/**
* Get a single organization by name.
*/
public async getOrg(orgName: string): Promise<GiteaOrganization> {
const raw = await this.requestGetOrg(orgName);
return new GiteaOrganization(this, raw);
}
/**
* Create a new organization.
*/
public async createOrg(name: string, opts?: {
fullName?: string;
description?: string;
visibility?: string;
}): Promise<GiteaOrganization> {
const raw = await this.requestCreateOrg(name, opts);
return new GiteaOrganization(this, raw);
}
// ===========================================================================
// Public API — Repositories (returns rich objects)
// ===========================================================================
/**
* Search/list all repositories (auto-paginated).
*/
public async getRepos(opts?: IListOptions): Promise<GiteaRepository[]> {
return autoPaginate(
(page, perPage) => this.requestGetRepos({ ...opts, page, perPage }),
opts,
).then(repos => repos.map(r => new GiteaRepository(this, r)));
}
/**
* Get a single repository by owner/repo.
*/
public async getRepo(ownerRepo: string): Promise<GiteaRepository> {
const raw = await this.requestGetRepo(ownerRepo);
return new GiteaRepository(this, raw);
}
/**
* Create a repository within an organization.
*/
public async createOrgRepo(orgName: string, name: string, opts?: {
description?: string;
private?: boolean;
}): Promise<GiteaRepository> {
const raw = await this.requestCreateOrgRepo(orgName, name, opts);
return new GiteaRepository(this, raw);
}
// ===========================================================================
// Internal request methods — called by domain classes
// ===========================================================================
// --- Repos ---
/** @internal */
async requestGetRepos(opts?: IListOptions): Promise<IGiteaRepository[]> {
const page = opts?.page || 1;
const limit = opts?.perPage || 50;
let url = `/api/v1/repos/search?page=${page}&limit=${limit}&sort=updated`;
@@ -139,73 +231,215 @@ export class GiteaClient {
return body.data || body;
}
// ---------------------------------------------------------------------------
// Organizations
// ---------------------------------------------------------------------------
/** @internal */
async requestGetRepo(ownerRepo: string): Promise<IGiteaRepository> {
return this.request<IGiteaRepository>('GET', `/api/v1/repos/${ownerRepo}`);
}
public async getOrgs(opts?: IListOptions): Promise<IGiteaOrganization[]> {
/** @internal */
async requestCreateOrgRepo(orgName: string, name: string, opts?: {
description?: string;
private?: boolean;
}): Promise<IGiteaRepository> {
return this.request<IGiteaRepository>('POST', `/api/v1/orgs/${encodeURIComponent(orgName)}/repos`, {
name,
description: opts?.description || '',
private: opts?.private ?? true,
});
}
/** @internal */
async requestPatchRepo(ownerRepo: string, data: Record<string, any>): Promise<void> {
await this.request('PATCH', `/api/v1/repos/${ownerRepo}`, data);
}
/** @internal */
async requestSetRepoTopics(ownerRepo: string, topics: string[]): Promise<void> {
await this.request('PUT', `/api/v1/repos/${ownerRepo}/topics`, { topics });
}
/** @internal */
async requestPostRepoAvatar(ownerRepo: string, imageBase64: string): Promise<void> {
await this.request('POST', `/api/v1/repos/${ownerRepo}/avatar`, { image: imageBase64 });
}
/** @internal */
async requestDeleteRepoAvatar(ownerRepo: string): Promise<void> {
await this.request('DELETE', `/api/v1/repos/${ownerRepo}/avatar`);
}
/** @internal */
async requestTransferRepo(ownerRepo: string, newOwner: string, teamIds?: number[]): Promise<void> {
const body: any = { new_owner: newOwner };
if (teamIds?.length) body.team_ids = teamIds;
await this.request('POST', `/api/v1/repos/${ownerRepo}/transfer`, body);
}
/** @internal */
async requestDeleteRepo(owner: string, repo: string): Promise<void> {
await this.request('DELETE', `/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`);
}
// --- Repo Branches & Tags ---
/** @internal */
async requestGetRepoBranches(ownerRepo: string, opts?: IListOptions): Promise<IGiteaBranch[]> {
const page = opts?.page || 1;
const limit = opts?.perPage || 50;
return this.request<IGiteaBranch[]>('GET', `/api/v1/repos/${ownerRepo}/branches?page=${page}&limit=${limit}`);
}
/** @internal */
async requestGetRepoTags(ownerRepo: string, opts?: IListOptions): Promise<IGiteaTag[]> {
const page = opts?.page || 1;
const limit = opts?.perPage || 50;
return this.request<IGiteaTag[]>('GET', `/api/v1/repos/${ownerRepo}/tags?page=${page}&limit=${limit}`);
}
// --- Repo Secrets ---
/** @internal */
async requestGetRepoSecrets(ownerRepo: string): Promise<IGiteaSecret[]> {
return this.request<IGiteaSecret[]>('GET', `/api/v1/repos/${ownerRepo}/actions/secrets`);
}
/** @internal */
async requestSetRepoSecret(ownerRepo: string, key: string, value: string): Promise<void> {
await this.request('PUT', `/api/v1/repos/${ownerRepo}/actions/secrets/${key}`, { data: value });
}
/** @internal */
async requestDeleteRepoSecret(ownerRepo: string, key: string): Promise<void> {
await this.request('DELETE', `/api/v1/repos/${ownerRepo}/actions/secrets/${key}`);
}
// --- Organizations ---
/** @internal */
async requestGetOrgs(opts?: IListOptions): Promise<IGiteaOrganization[]> {
const page = opts?.page || 1;
const limit = opts?.perPage || 50;
return this.request<IGiteaOrganization[]>('GET', `/api/v1/orgs?page=${page}&limit=${limit}`);
}
// ---------------------------------------------------------------------------
// Repository Secrets
// ---------------------------------------------------------------------------
public async getRepoSecrets(ownerRepo: string): Promise<IGiteaSecret[]> {
return this.request<IGiteaSecret[]>('GET', `/api/v1/repos/${ownerRepo}/actions/secrets`);
/** @internal */
async requestGetOrg(orgName: string): Promise<IGiteaOrganization> {
return this.request<IGiteaOrganization>('GET', `/api/v1/orgs/${encodeURIComponent(orgName)}`);
}
public async setRepoSecret(ownerRepo: string, key: string, value: string): Promise<void> {
await this.request('PUT', `/api/v1/repos/${ownerRepo}/actions/secrets/${key}`, { data: value });
/** @internal */
async requestCreateOrg(name: string, opts?: {
fullName?: string;
description?: string;
visibility?: string;
}): Promise<IGiteaOrganization> {
return this.request<IGiteaOrganization>('POST', '/api/v1/orgs', {
username: name,
full_name: opts?.fullName || name,
description: opts?.description || '',
visibility: opts?.visibility || 'public',
});
}
public async deleteRepoSecret(ownerRepo: string, key: string): Promise<void> {
await this.request('DELETE', `/api/v1/repos/${ownerRepo}/actions/secrets/${key}`);
/** @internal */
async requestPatchOrg(orgName: string, data: Record<string, any>): Promise<void> {
await this.request('PATCH', `/api/v1/orgs/${encodeURIComponent(orgName)}`, data);
}
// ---------------------------------------------------------------------------
// Organization Secrets
// ---------------------------------------------------------------------------
/** @internal */
async requestPostOrgAvatar(orgName: string, imageBase64: string): Promise<void> {
await this.request('POST', `/api/v1/orgs/${encodeURIComponent(orgName)}/avatar`, { image: imageBase64 });
}
public async getOrgSecrets(orgName: string): Promise<IGiteaSecret[]> {
/** @internal */
async requestDeleteOrgAvatar(orgName: string): Promise<void> {
await this.request('DELETE', `/api/v1/orgs/${encodeURIComponent(orgName)}/avatar`);
}
/** @internal */
async requestDeleteOrg(orgName: string): Promise<void> {
await this.request('DELETE', `/api/v1/orgs/${encodeURIComponent(orgName)}`);
}
// --- Org repos ---
/** @internal */
async requestGetOrgRepos(orgName: string, opts?: IListOptions): Promise<IGiteaRepository[]> {
const page = opts?.page || 1;
const limit = opts?.perPage || 50;
let url = `/api/v1/orgs/${encodeURIComponent(orgName)}/repos?page=${page}&limit=${limit}&sort=updated`;
if (opts?.search) {
url += `&q=${encodeURIComponent(opts.search)}`;
}
return this.request<IGiteaRepository[]>('GET', url);
}
// --- Org Secrets ---
/** @internal */
async requestGetOrgSecrets(orgName: string): Promise<IGiteaSecret[]> {
return this.request<IGiteaSecret[]>('GET', `/api/v1/orgs/${orgName}/actions/secrets`);
}
public async setOrgSecret(orgName: string, key: string, value: string): Promise<void> {
/** @internal */
async requestSetOrgSecret(orgName: string, key: string, value: string): Promise<void> {
await this.request('PUT', `/api/v1/orgs/${orgName}/actions/secrets/${key}`, { data: value });
}
public async deleteOrgSecret(orgName: string, key: string): Promise<void> {
/** @internal */
async requestDeleteOrgSecret(orgName: string, key: string): Promise<void> {
await this.request('DELETE', `/api/v1/orgs/${orgName}/actions/secrets/${key}`);
}
// ---------------------------------------------------------------------------
// Action Runs
// ---------------------------------------------------------------------------
// --- Action Runs ---
public async getActionRuns(ownerRepo: string, opts?: IListOptions): Promise<IGiteaActionRun[]> {
/** @internal */
async requestGetActionRuns(ownerRepo: string, opts?: IActionRunListOptions): Promise<IGiteaActionRun[]> {
const page = opts?.page || 1;
const limit = opts?.perPage || 30;
const body = await this.request<any>('GET', `/api/v1/repos/${ownerRepo}/actions/runs?page=${page}&limit=${limit}`);
let url = `/api/v1/repos/${ownerRepo}/actions/runs?page=${page}&limit=${limit}`;
// Translate user-friendly status names to Gitea API values
const apiStatus = toGiteaApiStatus(opts?.status);
if (apiStatus) url += `&status=${encodeURIComponent(apiStatus)}`;
if (opts?.branch) url += `&branch=${encodeURIComponent(opts.branch)}`;
if (opts?.event) url += `&event=${encodeURIComponent(opts.event)}`;
if (opts?.actor) url += `&actor=${encodeURIComponent(opts.actor)}`;
const body = await this.request<any>('GET', url);
return body.workflow_runs || body;
}
public async getActionRunJobs(ownerRepo: string, runId: number): Promise<IGiteaActionRunJob[]> {
/** @internal */
async requestGetActionRun(ownerRepo: string, runId: number): Promise<IGiteaActionRun> {
return this.request<IGiteaActionRun>('GET', `/api/v1/repos/${ownerRepo}/actions/runs/${runId}`);
}
/** @internal */
async requestGetActionRunJobs(ownerRepo: string, runId: number): Promise<IGiteaActionRunJob[]> {
const body = await this.request<any>('GET', `/api/v1/repos/${ownerRepo}/actions/runs/${runId}/jobs`);
return body.jobs || body;
}
public async getJobLog(ownerRepo: string, jobId: number): Promise<string> {
/** @internal */
async requestGetJobLog(ownerRepo: string, jobId: number): Promise<string> {
return this.requestText('GET', `/api/v1/repos/${ownerRepo}/actions/jobs/${jobId}/logs`);
}
public async rerunAction(ownerRepo: string, runId: number): Promise<void> {
await this.request('POST', `/api/v1/repos/${ownerRepo}/actions/runs/${runId}/rerun`);
/** @internal */
async requestDispatchWorkflow(
ownerRepo: string,
workflowId: string,
ref: string,
inputs?: Record<string, string>,
): Promise<void> {
await this.request(
'POST',
`/api/v1/repos/${ownerRepo}/actions/workflows/${encodeURIComponent(workflowId)}/dispatches`,
{ ref, inputs: inputs || {} },
);
}
public async cancelAction(ownerRepo: string, runId: number): Promise<void> {
await this.request('POST', `/api/v1/repos/${ownerRepo}/actions/runs/${runId}/cancel`);
/** @internal */
async requestDeleteActionRun(ownerRepo: string, runId: number): Promise<void> {
await this.request('DELETE', `/api/v1/repos/${ownerRepo}/actions/runs/${runId}`);
}
}

View File

@@ -0,0 +1,115 @@
import type { GiteaClient } from './gitea.classes.giteaclient.js';
import type { IGiteaOrganization, IGiteaSecret, IListOptions } from './gitea.interfaces.js';
import { GiteaRepository } from './gitea.classes.repository.js';
import { GiteaSecret } from './gitea.classes.secret.js';
import { autoPaginate } from './gitea.helpers.js';
export class GiteaOrganization {
// Raw data
public readonly id: number;
public readonly name: string;
public readonly fullName: string;
public readonly description: string;
public readonly visibility: string;
public readonly repoCount: number;
public readonly avatarUrl: string;
/** @internal */
constructor(
private client: GiteaClient,
raw: IGiteaOrganization,
) {
this.id = raw.id;
this.name = raw.name || '';
this.fullName = raw.full_name || this.name;
this.description = raw.description || '';
this.visibility = raw.visibility || 'public';
this.repoCount = raw.repo_count || 0;
this.avatarUrl = raw.avatar_url || '';
}
// ---------------------------------------------------------------------------
// Repos
// ---------------------------------------------------------------------------
async getRepos(opts?: IListOptions): Promise<GiteaRepository[]> {
return autoPaginate(
(page, perPage) => this.client.requestGetOrgRepos(this.name, { ...opts, page, perPage }),
opts,
).then(repos => repos.map(r => new GiteaRepository(this.client, r)));
}
// ---------------------------------------------------------------------------
// Secrets
// ---------------------------------------------------------------------------
async getSecrets(): Promise<GiteaSecret[]> {
const secrets = await this.client.requestGetOrgSecrets(this.name);
return secrets.map(s => new GiteaSecret(s));
}
async setSecret(key: string, value: string): Promise<void> {
await this.client.requestSetOrgSecret(this.name, key, value);
}
async deleteSecret(key: string): Promise<void> {
await this.client.requestDeleteOrgSecret(this.name, key);
}
// ---------------------------------------------------------------------------
// Mutation
// ---------------------------------------------------------------------------
/**
* Update organization properties (description, visibility, etc.)
*/
async update(data: {
description?: string;
visibility?: string;
fullName?: string;
}): Promise<void> {
await this.client.requestPatchOrg(this.name, {
description: data.description,
visibility: data.visibility,
full_name: data.fullName,
});
}
/**
* Upload an avatar image for this organization.
* @param imageBase64 - Base64-encoded image data
*/
async setAvatar(imageBase64: string): Promise<void> {
await this.client.requestPostOrgAvatar(this.name, imageBase64);
}
/**
* Remove the organization's avatar.
*/
async deleteAvatar(): Promise<void> {
await this.client.requestDeleteOrgAvatar(this.name);
}
/**
* Delete this organization.
*/
async delete(): Promise<void> {
await this.client.requestDeleteOrg(this.name);
}
// ---------------------------------------------------------------------------
// Serialization
// ---------------------------------------------------------------------------
toJSON(): IGiteaOrganization {
return {
id: this.id,
name: this.name,
full_name: this.fullName,
description: this.description,
visibility: this.visibility,
repo_count: this.repoCount,
avatar_url: this.avatarUrl,
};
}
}

View File

@@ -0,0 +1,171 @@
import type { GiteaClient } from './gitea.classes.giteaclient.js';
import type { IGiteaRepository, IGiteaSecret, IListOptions, IActionRunListOptions } from './gitea.interfaces.js';
import { GiteaBranch } from './gitea.classes.branch.js';
import { GiteaTag } from './gitea.classes.tag.js';
import { GiteaSecret } from './gitea.classes.secret.js';
import { GiteaActionRun } from './gitea.classes.actionrun.js';
import { autoPaginate } from './gitea.helpers.js';
export class GiteaRepository {
// Raw data
public readonly id: number;
public readonly name: string;
public readonly fullName: string;
public readonly description: string;
public readonly defaultBranch: string;
public readonly htmlUrl: string;
public readonly isPrivate: boolean;
public readonly topics: string[];
public readonly updatedAt: string;
public readonly ownerId: number;
public readonly ownerLogin: string;
public readonly ownerAvatarUrl: string;
/** @internal */
constructor(
private client: GiteaClient,
raw: IGiteaRepository,
) {
this.id = raw.id;
this.name = raw.name || '';
this.fullName = raw.full_name || '';
this.description = raw.description || '';
this.defaultBranch = raw.default_branch || 'main';
this.htmlUrl = raw.html_url || '';
this.isPrivate = raw.private ?? true;
this.topics = raw.topics || [];
this.updatedAt = raw.updated_at || '';
this.ownerId = raw.owner?.id || 0;
this.ownerLogin = raw.owner?.login || '';
this.ownerAvatarUrl = raw.owner?.avatar_url || '';
}
// ---------------------------------------------------------------------------
// Branches & Tags
// ---------------------------------------------------------------------------
async getBranches(opts?: IListOptions): Promise<GiteaBranch[]> {
return autoPaginate(
(page, perPage) => this.client.requestGetRepoBranches(this.fullName, { ...opts, page, perPage }),
opts,
).then(branches => branches.map(b => new GiteaBranch(b)));
}
async getTags(opts?: IListOptions): Promise<GiteaTag[]> {
return autoPaginate(
(page, perPage) => this.client.requestGetRepoTags(this.fullName, { ...opts, page, perPage }),
opts,
).then(tags => tags.map(t => new GiteaTag(t)));
}
// ---------------------------------------------------------------------------
// Secrets
// ---------------------------------------------------------------------------
async getSecrets(): Promise<GiteaSecret[]> {
const secrets = await this.client.requestGetRepoSecrets(this.fullName);
return secrets.map(s => new GiteaSecret(s));
}
async setSecret(key: string, value: string): Promise<void> {
await this.client.requestSetRepoSecret(this.fullName, key, value);
}
async deleteSecret(key: string): Promise<void> {
await this.client.requestDeleteRepoSecret(this.fullName, key);
}
// ---------------------------------------------------------------------------
// Action Runs
// ---------------------------------------------------------------------------
async getActionRuns(opts?: IActionRunListOptions): Promise<GiteaActionRun[]> {
return autoPaginate(
(page, perPage) => this.client.requestGetActionRuns(this.fullName, { ...opts, page, perPage }),
opts,
).then(runs => runs.map(r => new GiteaActionRun(this.client, this.fullName, r)));
}
// ---------------------------------------------------------------------------
// Mutation
// ---------------------------------------------------------------------------
/**
* Update repository properties.
*/
async update(data: {
name?: string;
description?: string;
defaultBranch?: string;
private?: boolean;
archived?: boolean;
}): Promise<void> {
await this.client.requestPatchRepo(this.fullName, {
name: data.name,
description: data.description,
default_branch: data.defaultBranch,
private: data.private,
archived: data.archived,
});
}
/**
* Set topics for this repository (replaces all existing topics).
*/
async setTopics(topics: string[]): Promise<void> {
await this.client.requestSetRepoTopics(this.fullName, topics);
}
/**
* Upload an avatar image for this repository.
* @param imageBase64 - Base64-encoded image data
*/
async setAvatar(imageBase64: string): Promise<void> {
await this.client.requestPostRepoAvatar(this.fullName, imageBase64);
}
/**
* Remove the repository's avatar.
*/
async deleteAvatar(): Promise<void> {
await this.client.requestDeleteRepoAvatar(this.fullName);
}
/**
* Transfer this repository to a different owner (org or user).
*/
async transfer(newOwner: string, teamIds?: number[]): Promise<void> {
await this.client.requestTransferRepo(this.fullName, newOwner, teamIds);
}
/**
* Delete this repository.
*/
async delete(): Promise<void> {
const [owner, repo] = this.fullName.split('/');
await this.client.requestDeleteRepo(owner, repo);
}
// ---------------------------------------------------------------------------
// Serialization
// ---------------------------------------------------------------------------
toJSON(): IGiteaRepository {
return {
id: this.id,
name: this.name,
full_name: this.fullName,
description: this.description,
default_branch: this.defaultBranch,
html_url: this.htmlUrl,
private: this.isPrivate,
topics: this.topics,
updated_at: this.updatedAt,
owner: {
id: this.ownerId,
login: this.ownerLogin,
avatar_url: this.ownerAvatarUrl,
},
};
}
}

View File

@@ -0,0 +1,18 @@
import type { IGiteaSecret } from './gitea.interfaces.js';
export class GiteaSecret {
public readonly name: string;
public readonly createdAt: string;
constructor(raw: IGiteaSecret) {
this.name = raw.name || '';
this.createdAt = raw.created_at || '';
}
toJSON(): IGiteaSecret {
return {
name: this.name,
created_at: this.createdAt,
};
}
}

19
ts/gitea.classes.tag.ts Normal file
View File

@@ -0,0 +1,19 @@
import type { IGiteaTag } from './gitea.interfaces.js';
export class GiteaTag {
public readonly name: string;
public readonly commitSha: string;
constructor(raw: IGiteaTag) {
this.name = raw.name || '';
this.commitSha = raw.commit?.sha || '';
}
toJSON(): IGiteaTag {
return {
name: this.name,
id: this.name,
commit: { sha: this.commitSha },
};
}
}

87
ts/gitea.helpers.ts Normal file
View File

@@ -0,0 +1,87 @@
/**
* Auto-paginate a list endpoint.
* If opts includes a specific page, returns just that page (no auto-pagination).
*/
export async function autoPaginate<T>(
fetchPage: (page: number, perPage: number) => Promise<T[]>,
opts?: { page?: number; perPage?: number },
): Promise<T[]> {
const perPage = opts?.perPage || 50;
// If caller requests a specific page, return just that page
if (opts?.page) {
return fetchPage(opts.page, perPage);
}
// Otherwise auto-paginate through all pages
const all: T[] = [];
let page = 1;
while (true) {
const items = await fetchPage(page, perPage);
all.push(...items);
if (items.length < perPage) break;
page++;
}
return all;
}
/**
* Compute duration in seconds from two ISO timestamps.
*/
export function computeDuration(startedAt?: string, completedAt?: string): number {
if (!startedAt || !completedAt) return 0;
const ms = new Date(completedAt).getTime() - new Date(startedAt).getTime();
return ms > 0 ? Math.round(ms / 1000) : 0;
}
/**
* Gitea uses `status` for run state (running, waiting, completed)
* and `conclusion` for the actual result (success, failure, cancelled, skipped).
* When status is "completed", the conclusion carries the meaningful status.
*/
export function resolveGiteaStatus(status: string, conclusion: string): string {
if (status === 'completed' && conclusion) {
return conclusion;
}
return status || conclusion || '';
}
/**
* Extract a human-readable ref from the Gitea `path` field.
* path format: "workflow.yaml@refs/tags/v1.0.0" or "workflow.yaml@refs/heads/main"
*/
export function extractRefFromPath(path?: string): string {
if (!path) return '';
const atIdx = path.indexOf('@');
if (atIdx < 0) return '';
const ref = path.substring(atIdx + 1);
return ref.replace(/^refs\/tags\//, '').replace(/^refs\/heads\//, '');
}
/**
* Extract the workflow filename from the Gitea `path` field.
* path format: "workflow.yaml@refs/tags/v1.0.0" → "workflow.yaml"
*/
export function extractWorkflowIdFromPath(path?: string): string {
if (!path) return '';
const atIdx = path.indexOf('@');
return atIdx >= 0 ? path.substring(0, atIdx) : path;
}
/**
* Translate normalized status names to Gitea API-native query parameter values.
* Gitea accepts: pending, queued, in_progress, failure, success, skipped
*/
export function toGiteaApiStatus(status?: string): string | undefined {
if (!status) return undefined;
const map: Record<string, string> = {
running: 'in_progress',
failed: 'failure',
canceled: 'cancelled',
pending: 'pending',
success: 'success',
skipped: 'skipped',
waiting: 'queued',
};
return map[status] || status;
}

View File

@@ -1,11 +1,51 @@
// ---------------------------------------------------------------------------
// Common
// ---------------------------------------------------------------------------
export interface ITestConnectionResult {
ok: boolean;
error?: string;
}
export interface IListOptions {
search?: string;
page?: number;
perPage?: number;
}
// ---------------------------------------------------------------------------
// Action Run list options
// ---------------------------------------------------------------------------
export interface IActionRunListOptions extends IListOptions {
/** Filter by run status. Accepts normalized names (running, failed, etc.) — auto-translated to Gitea API values. */
status?: string;
/** Filter by head branch */
branch?: string;
/** Filter by trigger event (push, pull_request, schedule, workflow_dispatch, …) */
event?: string;
/** Filter by the user who triggered the run */
actor?: string;
}
// ---------------------------------------------------------------------------
// Users
// ---------------------------------------------------------------------------
export interface IGiteaUser {
id: number;
login: string;
login_name: string;
source_id: number;
full_name: string;
email: string;
avatar_url: string;
}
// ---------------------------------------------------------------------------
// Repositories (raw API response)
// ---------------------------------------------------------------------------
export interface IGiteaRepository {
id: number;
name: string;
@@ -23,6 +63,10 @@ export interface IGiteaRepository {
};
}
// ---------------------------------------------------------------------------
// Organizations (raw API response)
// ---------------------------------------------------------------------------
export interface IGiteaOrganization {
id: number;
name: string;
@@ -30,41 +74,94 @@ export interface IGiteaOrganization {
description: string;
visibility: string;
repo_count: number;
avatar_url: string;
}
// ---------------------------------------------------------------------------
// Secrets
// ---------------------------------------------------------------------------
export interface IGiteaSecret {
name: string;
created_at: string;
}
// ---------------------------------------------------------------------------
// Action Runs (raw API response — aligned with Gitea 1.25 swagger)
// ---------------------------------------------------------------------------
export interface IGiteaActionRun {
id: number;
name: string;
status: string;
conclusion: string;
workflow_id: string;
status: string; // run state: running, waiting, completed
conclusion: string; // result: success, failure, cancelled, skipped
head_branch: string;
head_sha: string;
html_url: string;
event: string;
run_duration: number;
created_at: string;
path: string; // e.g. "workflow.yaml@refs/tags/v1.0"
display_title: string;
run_number: number;
run_attempt: number;
started_at: string;
completed_at: string;
actor: IGiteaUser;
trigger_actor: IGiteaUser;
repository: {
id: number;
name: string;
full_name: string;
html_url: string;
};
}
// ---------------------------------------------------------------------------
// Action Run Jobs (raw API response)
// ---------------------------------------------------------------------------
export interface IGiteaActionRunJob {
id: number;
run_id: number;
name: string;
workflow_name: string;
head_branch: string;
head_sha: string;
status: string;
conclusion: string;
run_duration: number;
html_url: string;
started_at: string;
completed_at: string;
steps: IGiteaActionRunJobStep[];
labels: string[];
runner_id: number;
runner_name: string;
}
export interface ITestConnectionResult {
ok: boolean;
error?: string;
export interface IGiteaActionRunJobStep {
name: string;
number: number;
status: string;
conclusion: string;
started_at: string;
completed_at: string;
}
export interface IListOptions {
search?: string;
page?: number;
perPage?: number;
// ---------------------------------------------------------------------------
// Branches & Tags
// ---------------------------------------------------------------------------
export interface IGiteaBranch {
name: string;
commit: {
id: string;
};
}
export interface IGiteaTag {
name: string;
id: string;
commit: {
sha: string;
};
}

View File

@@ -1,12 +1,40 @@
// Main client
export { GiteaClient } from './gitea.classes.giteaclient.js';
// Domain classes
export { GiteaOrganization } from './gitea.classes.organization.js';
export { GiteaRepository } from './gitea.classes.repository.js';
export { GiteaActionRun } from './gitea.classes.actionrun.js';
export { GiteaActionRunJob, GiteaActionRunJobStep } from './gitea.classes.actionrunjob.js';
export { GiteaBranch } from './gitea.classes.branch.js';
export { GiteaTag } from './gitea.classes.tag.js';
export { GiteaSecret } from './gitea.classes.secret.js';
// Helpers
export {
autoPaginate,
computeDuration,
resolveGiteaStatus,
extractRefFromPath,
extractWorkflowIdFromPath,
toGiteaApiStatus,
} from './gitea.helpers.js';
// Interfaces (raw API types)
export type {
IGiteaUser,
IGiteaRepository,
IGiteaOrganization,
IGiteaSecret,
IGiteaBranch,
IGiteaTag,
IGiteaActionRun,
IGiteaActionRunJob,
IGiteaActionRunJobStep,
ITestConnectionResult,
IListOptions,
IActionRunListOptions,
} from './gitea.interfaces.js';
// Commit info
export { commitinfo } from './00_commitinfo_data.js';