BREAKING CHANGE(gitlab): rename to @apiclient.xyz/gitlab v2.0.0 with new GitLabClient API

Replaces legacy @mojoio/gitlab with modern ESM TypeScript client supporting projects, groups, CI/CD variables, and pipelines.
This commit is contained in:
2026-02-24 12:50:18 +00:00
parent cc00a78e2c
commit b0f56f5948
23 changed files with 10463 additions and 26587 deletions

8
ts/00_commitinfo_data.ts Normal file
View File

@@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@apiclient.xyz/gitlab',
version: '2.0.0',
description: 'A TypeScript client for the GitLab API, providing easy access to projects, groups, CI/CD variables, and pipelines.',
};

View File

@@ -1,64 +0,0 @@
import { GitlabGroup } from './gitlab.classes.group';
import * as plugins from './gitlab.plugins';
export class GitlabAccount {
public static createAnonymousAccount() {
return new GitlabAccount();
}
// INSTANCE
public async getGroupByName(nameArg: string): Promise<GitlabGroup> {
return GitlabGroup.getByName(nameArg, this);
}
/**
* handles the basic request/response patterns with the gitlab.com API
*/
public async request(
methodArg: 'GET' | 'POST',
routeArg: string,
searchParamsArg: { [key: string]: string }
) {
if (!routeArg.startsWith('/')) {
throw new Error(`"${routeArg}" -> routeArg must start with a slash`);
}
const smarturlInstance = plugins.smarturl.Smarturl.createFromUrl(
`https://gitlab.com/api/v4${routeArg}`,
{
searchParams: searchParamsArg,
}
);
const response = await plugins.smartrequest.request(smarturlInstance.toString(), {
method: methodArg,
});
// lets deal with pagination headers
const findLinkName = (markup: string) => {
const pattern = /<([^\s>]+)(\s|>)+/;
return markup.match(pattern)[1];
};
if (typeof response.headers.link === 'string') {
const links = response.headers.link.split(',');
const linkObjects: {
original: string;
link: string;
}[] = [];
for (const link of links) {
linkObjects.push({
original: link,
link: findLinkName(link),
});
}
const next = linkObjects.find((linkObject) => linkObject.original.includes('rel="next"'));
if (next && response.body instanceof Array) {
const nextResponse = await this.request(
methodArg,
next.link.replace('https://gitlab.com/api/v4', ''),
{}
);
response.body = response.body.concat(nextResponse);
}
}
return response.body;
}
}

View File

@@ -0,0 +1,304 @@
import * as plugins from './gitlab.plugins.js';
import { logger } from './gitlab.logging.js';
import type {
IGitLabUser,
IGitLabProject,
IGitLabGroup,
IGitLabVariable,
IVariableOptions,
IGitLabPipeline,
IGitLabJob,
ITestConnectionResult,
IListOptions,
} from './gitlab.interfaces.js';
export class GitLabClient {
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
// ---------------------------------------------------------------------------
private async request<T = any>(
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
path: string,
data?: any,
customHeaders?: Record<string, string>,
): Promise<T> {
const url = `${this.baseUrl}${path}`;
let builder = plugins.smartrequest.SmartRequest.create()
.url(url)
.header('PRIVATE-TOKEN', this.token)
.header('Content-Type', 'application/json');
if (customHeaders) {
for (const [k, v] of Object.entries(customHeaders)) {
builder = builder.header(k, v);
}
}
if (data) {
builder = builder.json(data);
}
let response: Awaited<ReturnType<typeof builder.get>>;
switch (method) {
case 'GET':
response = await builder.get();
break;
case 'POST':
response = await builder.post();
break;
case 'PUT':
response = await builder.put();
break;
case 'DELETE':
response = await builder.delete();
break;
}
if (!response.ok) {
const errorText = await response.text();
throw new Error(`${method} ${path}: ${response.status} ${response.statusText} - ${errorText}`);
}
try {
return await response.json() as T;
} catch {
return undefined as unknown as T;
}
}
private async requestText(
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
path: string,
): Promise<string> {
const url = `${this.baseUrl}${path}`;
let builder = plugins.smartrequest.SmartRequest.create()
.url(url)
.header('PRIVATE-TOKEN', this.token)
.header('Accept', 'text/plain');
let response: Awaited<ReturnType<typeof builder.get>>;
switch (method) {
case 'GET':
response = await builder.get();
break;
case 'POST':
response = await builder.post();
break;
case 'PUT':
response = await builder.put();
break;
case 'DELETE':
response = await builder.delete();
break;
}
if (!response.ok) {
const errorText = await response.text();
throw new Error(`${method} ${path}: ${response.status} ${response.statusText} - ${errorText}`);
}
return response.text();
}
// ---------------------------------------------------------------------------
// Connection
// ---------------------------------------------------------------------------
public async testConnection(): Promise<ITestConnectionResult> {
try {
await this.request<IGitLabUser>('GET', '/api/v4/user');
return { ok: true };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
// ---------------------------------------------------------------------------
// Projects
// ---------------------------------------------------------------------------
public async getProjects(opts?: IListOptions): Promise<IGitLabProject[]> {
const page = opts?.page || 1;
const perPage = opts?.perPage || 50;
let url = `/api/v4/projects?membership=true&order_by=updated_at&sort=desc&page=${page}&per_page=${perPage}`;
if (opts?.search) {
url += `&search=${encodeURIComponent(opts.search)}`;
}
return this.request<IGitLabProject[]>('GET', url);
}
// ---------------------------------------------------------------------------
// Groups
// ---------------------------------------------------------------------------
public async getGroups(opts?: IListOptions): Promise<IGitLabGroup[]> {
const page = opts?.page || 1;
const perPage = opts?.perPage || 50;
let url = `/api/v4/groups?order_by=name&sort=asc&page=${page}&per_page=${perPage}`;
if (opts?.search) {
url += `&search=${encodeURIComponent(opts.search)}`;
}
return this.request<IGitLabGroup[]>('GET', url);
}
// ---------------------------------------------------------------------------
// Project Variables (CI/CD)
// ---------------------------------------------------------------------------
public async getProjectVariables(projectId: number | string): Promise<IGitLabVariable[]> {
return this.request<IGitLabVariable[]>(
'GET',
`/api/v4/projects/${encodeURIComponent(projectId)}/variables`,
);
}
public async createProjectVariable(
projectId: number | string,
key: string,
value: string,
opts?: IVariableOptions,
): Promise<IGitLabVariable> {
return this.request<IGitLabVariable>(
'POST',
`/api/v4/projects/${encodeURIComponent(projectId)}/variables`,
{
key,
value,
protected: opts?.protected ?? false,
masked: opts?.masked ?? false,
environment_scope: opts?.environment_scope ?? '*',
},
);
}
public async updateProjectVariable(
projectId: number | string,
key: string,
value: string,
opts?: IVariableOptions,
): Promise<IGitLabVariable> {
const body: any = { value };
if (opts?.protected !== undefined) body.protected = opts.protected;
if (opts?.masked !== undefined) body.masked = opts.masked;
if (opts?.environment_scope !== undefined) body.environment_scope = opts.environment_scope;
return this.request<IGitLabVariable>(
'PUT',
`/api/v4/projects/${encodeURIComponent(projectId)}/variables/${encodeURIComponent(key)}`,
body,
);
}
public async deleteProjectVariable(projectId: number | string, key: string): Promise<void> {
await this.request(
'DELETE',
`/api/v4/projects/${encodeURIComponent(projectId)}/variables/${encodeURIComponent(key)}`,
);
}
// ---------------------------------------------------------------------------
// Group Variables (CI/CD)
// ---------------------------------------------------------------------------
public async getGroupVariables(groupId: number | string): Promise<IGitLabVariable[]> {
return this.request<IGitLabVariable[]>(
'GET',
`/api/v4/groups/${encodeURIComponent(groupId)}/variables`,
);
}
public async createGroupVariable(
groupId: number | string,
key: string,
value: string,
opts?: IVariableOptions,
): Promise<IGitLabVariable> {
return this.request<IGitLabVariable>(
'POST',
`/api/v4/groups/${encodeURIComponent(groupId)}/variables`,
{
key,
value,
protected: opts?.protected ?? false,
masked: opts?.masked ?? false,
environment_scope: opts?.environment_scope ?? '*',
},
);
}
public async updateGroupVariable(
groupId: number | string,
key: string,
value: string,
opts?: IVariableOptions,
): Promise<IGitLabVariable> {
const body: any = { value };
if (opts?.protected !== undefined) body.protected = opts.protected;
if (opts?.masked !== undefined) body.masked = opts.masked;
if (opts?.environment_scope !== undefined) body.environment_scope = opts.environment_scope;
return this.request<IGitLabVariable>(
'PUT',
`/api/v4/groups/${encodeURIComponent(groupId)}/variables/${encodeURIComponent(key)}`,
body,
);
}
public async deleteGroupVariable(groupId: number | string, key: string): Promise<void> {
await this.request(
'DELETE',
`/api/v4/groups/${encodeURIComponent(groupId)}/variables/${encodeURIComponent(key)}`,
);
}
// ---------------------------------------------------------------------------
// Pipelines
// ---------------------------------------------------------------------------
public async getPipelines(projectId: number | string, opts?: IListOptions): Promise<IGitLabPipeline[]> {
const page = opts?.page || 1;
const perPage = opts?.perPage || 30;
return this.request<IGitLabPipeline[]>(
'GET',
`/api/v4/projects/${encodeURIComponent(projectId)}/pipelines?page=${page}&per_page=${perPage}&order_by=updated_at&sort=desc`,
);
}
public async getPipelineJobs(projectId: number | string, pipelineId: number): Promise<IGitLabJob[]> {
return this.request<IGitLabJob[]>(
'GET',
`/api/v4/projects/${encodeURIComponent(projectId)}/pipelines/${pipelineId}/jobs`,
);
}
public async getJobLog(projectId: number | string, jobId: number): Promise<string> {
return this.requestText(
'GET',
`/api/v4/projects/${encodeURIComponent(projectId)}/jobs/${jobId}/trace`,
);
}
public async retryPipeline(projectId: number | string, pipelineId: number): Promise<void> {
await this.request(
'POST',
`/api/v4/projects/${encodeURIComponent(projectId)}/pipelines/${pipelineId}/retry`,
);
}
public async cancelPipeline(projectId: number | string, pipelineId: number): Promise<void> {
await this.request(
'POST',
`/api/v4/projects/${encodeURIComponent(projectId)}/pipelines/${pipelineId}/cancel`,
);
}
}

View File

@@ -1,54 +0,0 @@
import * as plugins from './gitlab.plugins';
import { GitlabAccount } from './gitlab.classes.account';
import { GitlabProject } from './gitlab.classes.project';
export interface IGitlabGroup {
id: number;
web_url: string;
name: string;
path: string;
description: string;
visibility: string;
share_with_group_lock: string;
require_two_factor_authentication: string;
two_factor_grace_period: number;
project_creation_level: string;
auto_devops_enabled: null;
subgroup_creation_level: string;
emails_disabled: null;
mentions_disabled: null;
lfs_enabled: boolean;
default_branch_protection: number;
avatar_url: string;
request_access_enabled: boolean;
full_name: string;
full_path: string;
created_at: string;
parent_id: null;
ldap_cn: null;
ldap_access: null;
}
export class GitlabGroup {
public static async getByName(nameArg: string, gitlabAccountArg: GitlabAccount) {
const response = await gitlabAccountArg.request('GET', '/groups', {
search: 'pushrocks',
});
// console.log(response);
const returnGroup = new GitlabGroup(response[0], gitlabAccountArg);
return returnGroup;
}
// INSTANCE
public gitlabAccountRef: GitlabAccount;
public data: IGitlabGroup;
constructor(dataArg: IGitlabGroup, gitlabAccountArg: GitlabAccount) {
this.gitlabAccountRef = gitlabAccountArg;
this.data = dataArg;
}
public async getProjects() {
return GitlabProject.getProjectsForGroup(this);
}
}

View File

@@ -1,173 +0,0 @@
import { GitlabGroup } from './gitlab.classes.group';
import * as plugins from './gitlab.plugins';
export interface IGitlabData {
id: number;
description: string;
name: string;
name_with_namespace: string;
path: string;
path_with_namespace: string;
created_at: string;
default_branch: string;
tag_list: string[];
ssh_url_to_repo: string;
http_url_to_repo: string;
web_url: string;
readme_url: string;
avatar_url: null;
forks_count: number;
star_count: number;
last_activity_at: string;
namespace: {
id: number;
name: string;
path: string;
kind: string;
full_path: string;
parent_id: null;
avatar_url: string;
web_url: string;
};
container_registry_image_prefix: string;
_links: {
self: string;
issues: string;
merge_requests: string;
repo_branches: string;
labels: string;
events: string;
members: string;
};
packages_enabled: null;
empty_repo: boolean;
archived: boolean;
visibility: 'public' | 'private';
resolve_outdated_diff_discussions: null;
container_registry_enabled: boolean;
issues_enabled: boolean;
merge_requests_enabled: boolean;
wiki_enabled: boolean;
jobs_enabled: boolean;
snippets_enabled: boolean;
service_desk_enabled: null;
service_desk_address: null;
can_create_merge_request_in: boolean;
issues_access_level: 'enabled' | 'disabled';
repository_access_level: 'enabled' | 'disabled';
merge_requests_access_level: 'enabled' | 'disabled';
forking_access_level: 'enabled' | 'disabled';
wiki_access_level: 'enabled' | 'disabled';
builds_access_level: 'enabled' | 'disabled';
snippets_access_level: 'enabled' | 'disabled';
pages_access_level: 'enabled' | 'disabled';
operations_access_level: 'enabled' | 'disabled';
analytics_access_level: 'enabled' | 'disabled';
emails_disabled: null;
shared_runners_enabled: boolean;
lfs_enabled: boolean;
creator_id: number;
import_status: 'none';
open_issues_count: number;
ci_default_git_depth: null;
ci_forward_deployment_enabled: null;
public_jobs: boolean;
build_timeout: number;
auto_cancel_pending_pipelines: 'enabled' | 'disabled';
build_coverage_regex: '';
ci_config_path: '';
shared_with_groups: [];
only_allow_merge_if_pipeline_succeeds: boolean;
allow_merge_on_skipped_pipeline: null;
restrict_user_defined_variables: boolean;
request_access_enabled: boolean;
only_allow_merge_if_all_discussions_are_resolved: boolean;
remove_source_branch_after_merge: null;
printing_merge_request_link_enabled: boolean;
merge_method: 'merge';
suggestion_commit_message: null;
auto_devops_enabled: boolean;
auto_devops_deploy_strategy: 'continuous';
autoclose_referenced_issues: boolean;
approvals_before_merge: number;
mirror: boolean;
external_authorization_classification_label: '';
marked_for_deletion_at: null;
marked_for_deletion_on: null;
requirements_enabled: boolean;
security_and_compliance_enabled: null;
compliance_frameworks: [];
issues_template: '';
merge_requests_template: '';
}
export class GitlabProject {
// STATIC
public static async getProjectsForGroup(gitlabGroupArg: GitlabGroup): Promise<GitlabProject[]> {
const response = await gitlabGroupArg.gitlabAccountRef.request(
'GET',
`/groups/${gitlabGroupArg.data.id}/projects`,
{
per_page: '100',
}
);
const allProjects: GitlabProject[] = [];
for (const projectData of response) {
allProjects.push(new GitlabProject(projectData, gitlabGroupArg));
}
return allProjects;
}
// INSTANCE
gitlabGroupRef: GitlabGroup;
data: IGitlabData;
constructor(dataArg: IGitlabData, gitlabGroupRefArg: GitlabGroup) {
this.data = dataArg;
this.gitlabGroupRef = gitlabGroupRefArg;
}
public async getFileFromProject(
filePathArg: string,
refArg: string
): Promise<plugins.smartfile.Smartfile> {
const response = await this.gitlabGroupRef.gitlabAccountRef.request(
'GET',
`/projects/${this.data.id}/repository/files/${filePathArg}`,
{
ref: refArg,
}
);
return plugins.smartfile.Smartfile.fromBuffer(
filePathArg,
Buffer.from(response.content, response.encoding)
);
}
public async getReadmeAsMarkdown(refArg: string = 'master'): Promise<string> {
const readmeFile = await this.getFileFromProject('readme.md', refArg);
return readmeFile.contents.toString('utf8');
}
public async getNpmKeywords(refArg: string = 'master'): Promise<string[]> {
const packageJsonFile = await this.getFileFromProject('package.json', refArg);
const packageJsonObject: any = JSON.parse(packageJsonFile.contents.toString('utf8'));
return packageJsonObject.keywords ? packageJsonObject.keywords : [];
}
public async getProjectAsArticle(): Promise<plugins.tsclass.content.IArticle> {
return {
url: this.data.web_url,
author: null,
content: await this.getReadmeAsMarkdown().catch(err => null),
tags: await this.getNpmKeywords().catch(err => null),
title: this.data.name,
timestamp: new Date(this.data.last_activity_at).getTime(),
featuredImageUrl: null
}
}
public async syncNpmKeywordsToGitlabTopics() {
}
}

76
ts/gitlab.interfaces.ts Normal file
View File

@@ -0,0 +1,76 @@
export interface IGitLabUser {
id: number;
username: string;
name: string;
email: string;
avatar_url: string;
web_url: string;
state: string;
}
export interface IGitLabProject {
id: number;
name: string;
path_with_namespace: string;
description: string;
default_branch: string;
web_url: string;
visibility: string;
topics: string[];
last_activity_at: string;
}
export interface IGitLabGroup {
id: number;
name: string;
full_path: string;
description: string;
web_url: string;
visibility: string;
}
export interface IGitLabVariable {
key: string;
value: string;
variable_type: string;
protected: boolean;
masked: boolean;
environment_scope: string;
}
export interface IVariableOptions {
protected?: boolean;
masked?: boolean;
environment_scope?: string;
}
export interface IGitLabPipeline {
id: number;
project_id: number;
status: string;
ref: string;
sha: string;
web_url: string;
duration: number;
created_at: string;
source: string;
}
export interface IGitLabJob {
id: number;
name: string;
stage: string;
status: string;
duration: number;
}
export interface ITestConnectionResult {
ok: boolean;
error?: string;
}
export interface IListOptions {
search?: string;
page?: number;
perPage?: number;
}

3
ts/gitlab.logging.ts Normal file
View File

@@ -0,0 +1,3 @@
import * as plugins from './gitlab.plugins.js';
export const logger = new plugins.smartlog.ConsoleLog();

View File

@@ -1,13 +1,4 @@
// @tsclass scope
import * as tsclass from '@tsclass/tsclass';
import * as smartlog from '@push.rocks/smartlog';
import * as smartrequest from '@push.rocks/smartrequest';
export {
tsclass
}
// pushrocks scope
import * as smartfile from '@pushrocks/smartfile';
import * as smartrequest from '@pushrocks/smartrequest';
import * as smarturl from '@pushrocks/smarturl';
export { smartfile, smartrequest, smarturl };
export { smartlog, smartrequest };

View File

@@ -1,3 +1,13 @@
export * from './gitlab.classes.group';
export * from './gitlab.classes.account';
export * from './gitlab.classes.project';
export { GitLabClient } from './gitlab.classes.gitlabclient.js';
export type {
IGitLabUser,
IGitLabProject,
IGitLabGroup,
IGitLabVariable,
IVariableOptions,
IGitLabPipeline,
IGitLabJob,
ITestConnectionResult,
IListOptions,
} from './gitlab.interfaces.js';
export { commitinfo } from './00_commitinfo_data.js';