Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | 82x 82x 82x 82x 82x 82x 82x 82x 129x 129x 129x 129x 129x 436x 192x 192x 413x 380x 13x 15x 367x 192x 192x 436x 281x 155x 155x 2x 153x 127x 26x 26x 53x 53x 26x 439x 436x 436x 436x 436x 436x 436x 436x 236x 200x 200x 429x 114x 114x 114x 114x 114x 108x 108x 107x 107x 107x 58x 47x 11x 1x 10x 76x 20x 76x 114x 315x 16x 299x 299x 293x 12x 12x 12x 12x 9x 6x 3x 6x 82x 228x 120x 48x 26x 5x 82x 8x 31x 2x 82x 163x 163x 428x 329x 163x 82x | /**
* GitLab REST API Client
*
* Unified client for GitLab API calls that handles:
* - URL building with base URL from config
* - Query parameters serialization
* - Request body encoding (JSON or form-urlencoded)
* - Response error handling
* - GID cleanup from responses
* - Authentication via enhancedFetch
*/
import { enhancedFetch } from './fetch';
import { getGitLabBaseUrl } from './gitlab-base-url';
import { cleanGidsFromObject } from './idConversion';
import { assertSafeApiPath } from './api-path';
import { normalizeProjectId } from './projectIdentifier';
import { parseRetryAfterSeconds } from './retry-after';
import { readBoundedJson, readBoundedText } from './bounded-json';
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
type QueryParamValue = string | number | boolean | undefined | null;
type QueryParamArray = string[] | number[];
type QueryParams = Record<string, QueryParamValue | QueryParamArray>;
interface RequestOptions {
/** Query parameters omit null, undefined and empty strings; arrays use key[] format. */
query?: QueryParams;
/** Request body for POST/PUT/PATCH */
body?: Record<string, unknown> | URLSearchParams | FormData;
/** Content type: 'json' or 'form' for x-www-form-urlencoded (default: 'form') */
contentType?: 'json' | 'form';
/** Skip GID cleanup from response */
rawResponse?: boolean;
/** Bound response bytes before decoding; used for potentially large Duo payloads. */
responseByteLimit?: number;
/** Non-idempotent Duo commands refuse redirects rather than replaying their body. */
redirect?: RequestRedirect;
}
/** HTTP failure with the same diagnostic text and machine-readable response metadata. */
export class GitLabApiError extends Error {
constructor(
readonly status: number,
readonly details: string,
message: string,
readonly retryAfterSeconds?: number,
) {
super(message);
this.name = 'GitLabApiError';
}
}
/**
* Build query string, omitting null, undefined, empty strings and empty arrays.
* Arrays are serialized using key[] format (Rails convention) for GitLab API compatibility.
* Example: { scope: ["failed", "success"] } -> "scope[]=failed&scope[]=success"
*/
function buildQueryString(params?: QueryParams): string {
if (!params) return '';
const searchParams = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value === undefined || value === null || value === '') continue;
if (Array.isArray(value)) {
// GitLab Rails API expects array params as key[]=val1&key[]=val2
for (const item of value) {
searchParams.append(`${key}[]`, String(item));
}
} else {
searchParams.set(key, String(value));
}
}
const str = searchParams.toString();
return str ? `?${str}` : '';
}
/**
* Encode request body based on content type
*/
function encodeBody(
body: Record<string, unknown> | URLSearchParams | FormData | undefined,
contentType: 'json' | 'form',
): { body?: string | FormData; headers: Record<string, string> } {
if (!body) {
return { headers: {} };
}
// Already encoded
Iif (body instanceof URLSearchParams) {
return {
body: body.toString(),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
};
}
// Duck-type check covers both global FormData and undici.FormData
if (
body != null &&
typeof body === 'object' &&
typeof (body as Record<string, unknown>).append === 'function' &&
typeof (body as Record<string, unknown>).getAll === 'function'
) {
return {
body: body as FormData,
headers: {}, // Let fetch set Content-Type with boundary
};
}
// Encode as JSON or form
if (contentType === 'json') {
return {
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
};
}
// Form-urlencoded
const params = new URLSearchParams();
for (const [key, value] of Object.entries(body)) {
Eif (value !== undefined && value !== null) {
params.set(key, String(value));
}
}
return {
body: params.toString(),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
};
}
/**
* Make a GitLab API request
*/
async function request<T>(
method: HttpMethod,
path: string,
options: RequestOptions = {},
receiveHeaders?: (headers: Headers) => void,
): Promise<T> {
assertSafeApiPath(path);
const baseUrl = getGitLabBaseUrl();
const queryString = buildQueryString(options.query);
const url = `${baseUrl}/api/v4/${path}${queryString}`;
const { body, headers } = encodeBody(options.body, options.contentType ?? 'form');
// For GET requests with no body/headers, don't pass options (matches existing behavior)
const hasBody = !!body;
const hasHeaders = Object.keys(headers).length > 0;
let response: Response;
if (method === 'GET' && !hasBody && !hasHeaders && options.redirect === undefined) {
response = await enhancedFetch(url);
} else {
const fetchOptions: RequestInit = {
method,
...(options.redirect === undefined ? {} : { redirect: options.redirect }),
...(hasBody && { body }),
...(hasHeaders && { headers }),
};
response = await enhancedFetch(url, fetchOptions);
}
if (!response.ok) {
const receivedAt = Date.now();
const retryAfter =
response.status === 429
? parseRetryAfterSeconds(response.headers?.get('Retry-After') ?? null, receivedAt)
: null;
let errorDetails = '';
try {
if (typeof response.text === 'function') {
const text =
options.responseByteLimit === undefined
? await response.text()
: await readBoundedText(response, options.responseByteLimit);
if (text.trim()) {
// Try to parse as JSON and extract meaningful error info
const errorResponse = JSON.parse(text) as {
message?: string | { value?: string[] } | Record<string, unknown>;
error?: string;
};
const parts: string[] = [];
if (errorResponse.message) {
if (typeof errorResponse.message === 'string') {
parts.push(errorResponse.message);
} else if (
typeof errorResponse.message === 'object' &&
'value' in errorResponse.message &&
Array.isArray(errorResponse.message.value)
) {
parts.push(errorResponse.message.value.join(', '));
} else {
parts.push(JSON.stringify(errorResponse.message));
}
}
if (errorResponse.error) {
parts.push(errorResponse.error);
}
errorDetails = parts.join(' - ');
}
}
} catch {
// If error response can't be parsed, leave errorDetails empty
}
throw new GitLabApiError(
response.status,
errorDetails,
`GitLab API error: ${response.status} ${response.statusText}${errorDetails ? ` - ${errorDetails}` : ''}`,
retryAfter === null ? undefined : Math.ceil(retryAfter),
);
}
// Handle 204 No Content responses (common for DELETE, some PUT/POST operations)
// Callers expecting void/undefined should use appropriate generic type: gitlab.delete<void>()
// Type assertion is intentional to allow typed handlers to work with void responses
if (response.status === 204) {
return undefined as T;
}
const data = (
options.responseByteLimit === undefined
? await response.json()
: await readBoundedJson(response, options.responseByteLimit)
) as T;
receiveHeaders?.(response.headers);
return options.rawResponse ? data : cleanGidsFromObject(data);
}
/** GitLab offset pagination metadata, independent of permission-filtered page length. */
export interface ApiPage<T> {
items: T[];
nextPage: number | null;
}
async function getPage<T>(
path: string,
options?: Omit<RequestOptions, 'body' | 'contentType'>,
): Promise<ApiPage<T>> {
let nextPage: number | null = null;
const items = await request<T[]>('GET', path, options, (headers) => {
// GitLab 16.0 OffsetHeaderBuilder always emits X-Next-Page, empty on the last page.
const value = headers.get('x-next-page');
if (value === '') return;
if (value === null || !/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value))) {
throw new Error('GitLab did not return valid pagination metadata');
}
nextPage = Number(value);
});
return { items, nextPage };
}
/**
* GitLab API client with typed methods
*/
export const gitlab = {
/** Read a page with its server-supplied continuation, including filtered empty pages. */
getPage,
/**
* GET request
* @example gitlab.get('projects/123/labels', { query: { per_page: 20 } })
*/
get: <T = unknown>(path: string, options?: Omit<RequestOptions, 'body' | 'contentType'>) =>
request<T>('GET', path, options),
/**
* POST request
* @example gitlab.post('projects/123/labels', { body: { name: 'bug', color: '#ff0000' } })
*/
post: <T = unknown>(path: string, options?: RequestOptions) => request<T>('POST', path, options),
/**
* PUT request
* @example gitlab.put('projects/123/labels/1', { body: { color: '#00ff00' } })
*/
put: <T = unknown>(path: string, options?: RequestOptions) => request<T>('PUT', path, options),
/**
* DELETE request
* @example gitlab.delete('projects/123/labels/1')
*/
delete: <T = unknown>(path: string, options?: Omit<RequestOptions, 'body' | 'contentType'>) =>
request<T>('DELETE', path, options),
/**
* PATCH request
* @example gitlab.patch('projects/123', { body: { description: 'New desc' } })
*/
patch: <T = unknown>(path: string, options?: RequestOptions) =>
request<T>('PATCH', path, options),
};
/**
* Helper to build entity paths
*/
export const paths = {
/** Encode path for URL */
encode: (path: string) => encodeURIComponent(path),
/** Projects path */
project: (id: string | number) => `projects/${normalizeProjectId(String(id))}`,
/** Groups path */
group: (id: string | number) => `groups/${normalizeProjectId(String(id))}`,
/** Namespace (project or group) path based on detection */
namespace: (path: string, entityType: 'projects' | 'groups') =>
`${entityType}/${normalizeProjectId(path)}`,
};
/**
* Helper to filter options for query params, excluding specified keys.
* Preserves arrays for buildQueryString() to serialize as key[] params.
*/
export function toQuery<T extends Record<string, unknown>>(
options: T,
exclude: (keyof T)[] = [],
): QueryParams {
const result: QueryParams = {};
for (const [key, value] of Object.entries(options)) {
if (!exclude.includes(key) && value !== undefined) {
result[key] = value as QueryParamValue | QueryParamArray;
}
}
return result;
}
export default gitlab;
|