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

3
.gitignore vendored
View File

@@ -3,7 +3,6 @@
# artifacts
coverage/
public/
pages/
# installs
node_modules/
@@ -17,4 +16,4 @@ node_modules/
dist/
dist_*/
# custom
#------# custom

View File

@@ -1,137 +0,0 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
only:
- tags
tags:
- lossless
- docker
- notpriv
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --production --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=prod --production
tags:
- docker
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- docker
allow_failure: true
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
only:
- tags
script:
- npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

29
.vscode/launch.json vendored
View File

@@ -1,29 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "current file",
"type": "node",
"request": "launch",
"args": [
"${relativeFile}"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "test.ts",
"type": "node",
"request": "launch",
"args": [
"test/test.ts"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
}
]
}

26
.vscode/settings.json vendored
View File

@@ -1,26 +0,0 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}

21
license.md Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Lossless GmbH (https://lossless.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,19 +1,26 @@
{
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "mojoio",
"githost": "code.foss.global",
"gitscope": "apiclient.xyz",
"gitrepo": "gitlab",
"shortDescription": "a gitlab api abstraction package",
"npmPackagename": "@mojoio/gitlab",
"description": "A TypeScript client for the GitLab API, providing easy access to projects, groups, CI/CD variables, and pipelines.",
"npmPackagename": "@apiclient.xyz/gitlab",
"license": "MIT",
"projectDomain": "mojo.io"
"keywords": [
"gitlab",
"api client",
"TypeScript",
"CI/CD",
"pipelines",
"variables",
"devops"
]
}
},
"npmci": {
"npmGlobalTools": [],
"npmRegistryUrl": "registry.npmjs.org",
"npmAccessLevel": "public"
}
}

25960
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,33 +1,42 @@
{
"name": "@mojoio/gitlab",
"version": "1.0.10",
"description": "api abstraction package for gitlab",
"name": "@apiclient.xyz/gitlab",
"version": "2.0.0",
"private": false,
"description": "A TypeScript client for the GitLab API, providing easy access to projects, groups, CI/CD variables, and pipelines.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
"scripts": {
"test": "(tstest test/ --verbose --timeout 600)",
"build": "(tsbuild --web --allowimplicitany)"
},
"repository": {
"type": "git",
"url": "https://code.foss.global/apiclient.xyz/gitlab.git"
},
"keywords": [
"gitlab",
"api client",
"TypeScript",
"CI/CD",
"pipelines",
"variables",
"devops"
],
"author": "Lossless GmbH",
"license": "MIT",
"scripts": {
"test": "(tstest test/)",
"build": "(tsbuild --web)"
"dependencies": {
"@push.rocks/smartlog": "^3.1.10",
"@push.rocks/smartrequest": "^5.0.1"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.27",
"@gitzone/tsrun": "^1.2.17",
"@gitzone/tstest": "^1.0.57",
"@pushrocks/tapbundle": "^3.2.14",
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.18.0"
"@git.zone/tsbuild": "^3.1.0",
"@git.zone/tsrun": "^2.0.0",
"@git.zone/tstest": "^2.8.2",
"@push.rocks/qenv": "^6.1.3",
"@push.rocks/tapbundle": "^5.6.0",
"@types/node": "^22.15.3"
},
"dependencies": {
"@pushrocks/smartfile": "^8.0.10",
"@pushrocks/smartrequest": "^1.1.52",
"@pushrocks/smarturl": "^2.0.1",
"@tsclass/tsclass": "^3.0.34"
},
"private": false,
"browserslist": [
"last 1 chrome versions"
],
"files": [
"ts/**/*",
"ts_web/**/*",
@@ -39,5 +48,8 @@
"cli.js",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
]
}

9914
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,46 +1,30 @@
# @mojoio/gitlab
a gitlab api abstraction package
# @apiclient.xyz/gitlab
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@mojoio/gitlab)
* [gitlab.com (source)](https://gitlab.com/mojoio/gitlab)
* [github.com (source mirror)](https://github.com/mojoio/gitlab)
* [docs (typedoc)](https://mojoio.gitlab.io/gitlab/)
A TypeScript client for the GitLab API, providing easy access to projects, groups, CI/CD variables, and pipelines.
## Status for master
## Install
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/mojoio/gitlab/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/mojoio/gitlab/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@mojoio/gitlab)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/mojoio/gitlab)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@mojoio/gitlab)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@mojoio/gitlab)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@mojoio/gitlab)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
```sh
npm install @apiclient.xyz/gitlab
```
## Usage
Use TypeScript for best in class instellisense.
```typescript
import { GitLabClient } from '@apiclient.xyz/gitlab';
For further information read the linked docs at the top of this README.
const client = new GitLabClient('https://gitlab.com', 'your-private-token');
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
> | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html)
// Test connection
const result = await client.testConnection();
[![repo-footer](https://mojoio.gitlab.io/assets/repo-footer.svg)](https://mojo.io)
// List projects
const projects = await client.getProjects();
## Contribution
// Manage CI/CD variables
await client.createProjectVariable(123, 'SECRET_KEY', 'secret-value');
```
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
## License
For further information read the linked docs at the top of this readme.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
MIT

34
test/test.node.ts Normal file
View File

@@ -0,0 +1,34 @@
import { tap, expect } from '@push.rocks/tapbundle';
import * as qenv from '@push.rocks/qenv';
import { GitLabClient } from '../ts/index.js';
const testQenv = new qenv.Qenv('./', '.nogit/');
let gitlabClient: GitLabClient;
tap.test('should create a GitLabClient instance', async () => {
const baseUrl = testQenv.getEnvVarOnDemand('GITLAB_BASE_URL') || 'https://gitlab.com';
const token = testQenv.getEnvVarOnDemand('GITLAB_TOKEN') || '';
gitlabClient = new GitLabClient(baseUrl, token);
expect(gitlabClient).toBeInstanceOf(GitLabClient);
});
tap.test('should test connection', async () => {
const result = await gitlabClient.testConnection();
expect(result).toHaveProperty('ok');
console.log('Connection test:', result);
});
tap.test('should get projects', async () => {
const projects = await gitlabClient.getProjects({ perPage: 5 });
expect(projects).toBeArray();
console.log(`Found ${projects.length} projects`);
});
tap.test('should get groups', async () => {
const groups = await gitlabClient.getGroups({ perPage: 5 });
expect(groups).toBeArray();
console.log(`Found ${groups.length} groups`);
});
export default tap.start();

View File

@@ -1,43 +0,0 @@
import { expect, tap } from '@pushrocks/tapbundle';
import * as gitlab from '../ts/index';
let testGitlabAccount: gitlab.GitlabAccount;
const test1 = tap.test('should create an anonymous Gitlab Account', async () => {
testGitlabAccount = gitlab.GitlabAccount.createAnonymousAccount();
expect(testGitlabAccount).to.be.instanceOf(gitlab.GitlabAccount);
});
const test2 = tap.test('should get the pushrocks group', async () => {
const pushrocksGroup = await testGitlabAccount.getGroupByName('pushrocks');
expect(pushrocksGroup).to.be.instanceOf(gitlab.GitlabGroup);
console.log(pushrocksGroup);
});
const test3 = tap.test('should get the pushrocks group', async () => {
const pushrocksGroup = await testGitlabAccount.getGroupByName('pushrocks');
expect(pushrocksGroup).to.be.instanceOf(gitlab.GitlabGroup);
await pushrocksGroup.getProjects();
});
const test4 = tap.test('should get the readme of a project', async () => {
const pushrocksGroup = await testGitlabAccount.getGroupByName('pushrocks');
expect(pushrocksGroup).to.be.instanceOf(gitlab.GitlabGroup);
const projects = await pushrocksGroup.getProjects();
const selectedProject = projects.find((project) => {
return project.data?.name === 'smartfile';
});
expect(selectedProject.data.name).to.equal('smartfile');
const readme = await selectedProject.getReadmeAsMarkdown('master');
expect(readme.startsWith('# @pushrocks/smartfile')).to.be.true;
return projects;
});
const test5 = tap.test('should be able to create an article list', async () => {
const projects: gitlab.GitlabProject[] = (await test4.testResultPromise) as any;
for (const project of projects) {
console.log(await project.getProjectAsArticle());
}
})
tap.start();

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';

16
tsconfig.json Normal file
View File

@@ -0,0 +1,16 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"baseUrl": ".",
"paths": {}
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

View File

@@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}