Open History to see the last commit
1/**
2 * Decoders for GitLab issues as `glab api` answers them. REST enums are decoded as plain strings
3 * and normalized here, so a GitLab release that adds a state or a label action never fails a
4 * whole payload; a row that cannot be read is skipped rather than failing its page.
5 *
6 * @module source-control-gitlab/server/gitLabIssueJson
7 */
8import * as Exit from "effect/Exit";
9import * as Result from "effect/Result";
10import * as Schema from "effect/Schema";
11import type {
12 IssueActor,
13 IssueAssigneeCandidate,
14 IssueComment,
15 IssueEvent,
16 IssueEventKind,
17 IssueLabel,
18 IssueLabelCandidate,
19 IssueLinkedPullRequest,
20 IssueState,
21 IssueTemplate,
22 PullRequestState,
23} from "@t3tools/contracts";
24import { decodeJsonResult } from "@t3tools/shared/schemaJson";
25import type { TrackerIssueSummary } from "@t3tools/source-control-core/server/IssueTracker";
26
27/** GitLab's ceiling on `per_page`, which is what every bounded read asks for. */
28export const PAGE_SIZE = 100;
29
30const RawUserSchema = Schema.Struct({
31 /** GitLab writes an issue's assignees as numeric ids, so the id travels with the handle. */
32 id: Schema.optional(Schema.Int),
33 username: Schema.String,
34 name: Schema.optional(Schema.NullOr(Schema.String)),
35 avatar_url: Schema.optional(Schema.NullOr(Schema.String)),
36});
37
38/** `with_labels_details=true` returns label objects; hosts that ignore it still send names. */
39const RawLabelRefSchema = Schema.Union([
40 Schema.String,
41 Schema.Struct({
42 name: Schema.String,
43 color: Schema.optional(Schema.NullOr(Schema.String)),
44 description: Schema.optional(Schema.NullOr(Schema.String)),
45 }),
46]);
47
48const RawIssueSchema = Schema.Struct({
49 iid: Schema.Int,
50 title: Schema.String,
51 web_url: Schema.String,
52 description: Schema.optional(Schema.NullOr(Schema.String)),
53 author: Schema.optional(Schema.NullOr(RawUserSchema)),
54 state: Schema.optional(Schema.NullOr(Schema.String)),
55 created_at: Schema.String,
56 updated_at: Schema.String,
57 closed_at: Schema.optional(Schema.NullOr(Schema.String)),
58 assignees: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))),
59 labels: Schema.optional(Schema.NullOr(Schema.Array(RawLabelRefSchema))),
60 user_notes_count: Schema.optional(Schema.NullOr(Schema.Int)),
61});
62
63const RawNoteSchema = Schema.Struct({
64 id: Schema.Int,
65 body: Schema.optional(Schema.NullOr(Schema.String)),
66 author: Schema.optional(Schema.NullOr(RawUserSchema)),
67 created_at: Schema.String,
68 /** True for the notes GitLab writes itself ("closed", "assigned to @x"), which are events. */
69 system: Schema.optional(Schema.Boolean),
70});
71
72const RawLabelEventSchema = Schema.Struct({
73 id: Schema.Int,
74 action: Schema.String,
75 created_at: Schema.String,
76 user: Schema.optional(Schema.NullOr(RawUserSchema)),
77 /** Null once the label itself has been deleted, which leaves the event with no subject. */
78 label: Schema.optional(Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.String) }))),
79});
80
81const RawLinkedMergeRequestSchema = Schema.Struct({
82 iid: Schema.Int,
83 title: Schema.String,
84 web_url: Schema.String,
85 state: Schema.optional(Schema.NullOr(Schema.String)),
86 draft: Schema.optional(Schema.Boolean),
87 work_in_progress: Schema.optional(Schema.Boolean),
88 /** `full` is `group/project!12`, which is the only place the merge request names its project. */
89 references: Schema.optional(
90 Schema.NullOr(Schema.Struct({ full: Schema.optional(Schema.NullOr(Schema.String)) })),
91 ),
92});
93
94const RawProjectLabelSchema = Schema.Struct({
95 name: Schema.String,
96 color: Schema.optional(Schema.NullOr(Schema.String)),
97 description: Schema.optional(Schema.NullOr(Schema.String)),
98});
99
100/** A row of `GET /projects/:id/templates/issues`, which names a template but carries none of it. */
101const RawTemplateEntrySchema = Schema.Struct({
102 key: Schema.String,
103 name: Schema.optional(Schema.NullOr(Schema.String)),
104});
105
106const RawTemplateSchema = Schema.Struct({ content: Schema.optional(Schema.NullOr(Schema.String)) });
107
108const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
109const decodeIssue = decodeJsonResult(RawIssueSchema);
110const decodeIssueList = decodeJsonResult(Schema.Array(RawIssueSchema));
111const decodeIssueEntry = Schema.decodeUnknownExit(RawIssueSchema);
112const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema);
113const decodeLabelEventEntry = Schema.decodeUnknownExit(RawLabelEventSchema);
114const decodeLinkedMergeRequestEntry = Schema.decodeUnknownExit(RawLinkedMergeRequestSchema);
115const decodeProjectLabelEntry = Schema.decodeUnknownExit(RawProjectLabelSchema);
116const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema);
117const decodeTemplateEntry = Schema.decodeUnknownExit(RawTemplateEntrySchema);
118const decodeTemplate = decodeJsonResult(RawTemplateSchema);
119
120type DecodeFailure =
121 ReturnType<typeof decodeIssue> extends Result.Result<unknown, infer E> ? E : never;
122
123function trimmed(value: string | null | undefined): string | null {
124 const text = value?.trim() ?? "";
125 return text.length > 0 ? text : null;
126}
127
128function toActor(raw: typeof RawUserSchema.Type | null | undefined): IssueActor | null {
129 const login = trimmed(raw?.username);
130 return login === null
131 ? null
132 : { login, name: trimmed(raw?.name), avatarUrl: trimmed(raw?.avatar_url) };
133}
134
135function toLabels(
136 raw: ReadonlyArray<typeof RawLabelRefSchema.Type> | null | undefined,
137): ReadonlyArray<IssueLabel> {
138 return (raw ?? []).flatMap((label): ReadonlyArray<IssueLabel> => {
139 if (typeof label === "string") {
140 const name = trimmed(label);
141 return name === null ? [] : [{ name, color: null }];
142 }
143 const name = trimmed(label.name);
144 return name === null
145 ? []
146 : [{ name, color: trimmed(label.color), description: trimmed(label.description) }];
147 });
148}
149
150const OPEN: IssueState = { category: "open", name: "Open" };
151const CLOSED: IssueState = { category: "closed", name: "Closed" };
152
153/** GitLab has exactly the two states and records no reason for a close. */
154export const ISSUE_STATES: ReadonlyArray<IssueState> = [OPEN, CLOSED];
155
156function toSummary(raw: typeof RawIssueSchema.Type): TrackerIssueSummary {
157 return {
158 key: String(raw.iid),
159 displayKey: `#${raw.iid}`,
160 title: raw.title,
161 url: raw.web_url,
162 author: toActor(raw.author),
163 // GitLab calls the open one `opened`.
164 state: raw.state?.trim().toLowerCase() === "closed" ? CLOSED : OPEN,
165 createdAt: raw.created_at,
166 updatedAt: raw.updated_at,
167 closedAt: trimmed(raw.closed_at),
168 assignees: (raw.assignees ?? []).flatMap((user) => toActor(user) ?? []),
169 labels: toLabels(raw.labels),
170 commentCount: Math.max(0, raw.user_notes_count ?? 0),
171 };
172}
173
174interface GitLabIssueList {
175 readonly items: ReadonlyArray<TrackerIssueSummary>;
176 /** Rows GitLab returned, counted before decoding, so a skipped row cannot hide a next page. */
177 readonly rawCount: number;
178}
179
180export function decodeIssueListJson(raw: string): Result.Result<GitLabIssueList, DecodeFailure> {
181 return Result.map(decodeUnknownList(raw), (rows) => ({
182 items: rows.flatMap((entry) => {
183 const issue = decodeIssueEntry(entry);
184 return Exit.isSuccess(issue) ? [toSummary(issue.value)] : [];
185 }),
186 rawCount: rows.length,
187 }));
188}
189
190interface GitLabIssueDetail extends TrackerIssueSummary {
191 readonly body: string;
192}
193
194/** GitLab's GET /issues/:iid ignores `with_labels_details`, so the detail is read as an `iids[]` list. */
195export function decodeIssueDetailListJson(
196 raw: string,
197): Result.Result<GitLabIssueDetail | null, DecodeFailure> {
198 return Result.map(decodeIssueList(raw), ([issue]) =>
199 issue === undefined ? null : { ...toSummary(issue), body: issue.description ?? "" },
200 );
201}
202
203/** The ids of the users a `/users?username=` lookup answered with: one, or none. */
204export function decodeUserIdsJson(
205 raw: string,
206): Result.Result<ReadonlyArray<number>, DecodeFailure> {
207 return Result.map(decodeUnknownList(raw), (rows) =>
208 rows.flatMap((entry) => {
209 const user = decodeUserEntry(entry);
210 return Exit.isSuccess(user) && user.value.id !== undefined ? [user.value.id] : [];
211 }),
212 );
213}
214
215export function decodeCreatedIssueJson(
216 raw: string,
217): Result.Result<{ readonly number: number; readonly url: string }, DecodeFailure> {
218 return Result.map(decodeIssue(raw), (issue) => ({ number: issue.iid, url: issue.web_url }));
219}
220
221const ENTITY: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'" };
222
223/**
224 * The events GitLab records as notes of its own. A label note names its labels by id ("added ~7
225 * label"), which is why labellings come from `/resource_label_events` instead and are dropped here.
226 */
227function toSystemEvent(
228 body: string,
229): { readonly kind: IssueEventKind; readonly detail: string | null } | null {
230 const text = body.trim();
231 if (text === "closed") return { kind: "closed", detail: null };
232 if (text === "reopened") return { kind: "reopened", detail: null };
233 if (text.startsWith("assigned to ")) {
234 return {
235 kind: "assigned",
236 detail: trimmed(text.slice("assigned to ".length).replace(/^@/, "")),
237 };
238 }
239 if (text.startsWith("unassigned ")) {
240 return {
241 kind: "unassigned",
242 detail: trimmed(text.slice("unassigned ".length).replace(/^@/, "")),
243 };
244 }
245 if (text.startsWith("mentioned in ")) {
246 return { kind: "referenced", detail: trimmed(text.slice("mentioned in ".length)) };
247 }
248 // GitLab 17.11+ uses HTML <code class="idiff"> diffs; older notes used **…** with {-…-}/{+…+}.
249 if (/^<(?:p|div)>changed title\b/.test(text)) {
250 const html = / to <code class="idiff">(.*?)<\/code><\/(?:p|div)>$/.exec(text)?.[1];
251 const detail = html
252 ?.replace(/<[^<>]*>/g, "")
253 .replace(/&(?:amp|lt|gt|quot|#39);/g, (m) => ENTITY[m.slice(1, -1)] ?? m);
254 return { kind: "renamed", detail: trimmed(detail) };
255 }
256 if (text.startsWith("changed title")) {
257 const raw = legacyNewTitle(text);
258 return { kind: "renamed", detail: trimmed(raw?.replace(/\{\+(.*?)\+\}/g, "$1")) };
259 }
260 return null;
261}
262
263/**
264 * The new side of "changed title from **old** to **new**". Whole {-…-} runs in the old title are
265 * skipped so a deleted "** to **" is not the boundary; GitLab does not escape markers, so only the
266 * old side's runs are deletions. A single forward scan, so a malformed note cannot backtrack.
267 */
268function legacyNewTitle(text: string): string | null {
269 const prefix = "changed title from **";
270 const boundary = "** to **";
271 if (!text.startsWith(prefix) || !text.endsWith("**")) return null;
272 let index = prefix.length;
273 let deletionsClose = true;
274 while (index < text.length && !text.startsWith(boundary, index)) {
275 if (deletionsClose && text.startsWith("{-", index)) {
276 const end = text.indexOf("-}", index + 2);
277 if (end !== -1) {
278 index = end + 2;
279 continue;
280 }
281 // No later "{-" can close either; stop searching so the scan stays linear.
282 deletionsClose = false;
283 }
284 index += 1;
285 }
286 const start = index + boundary.length;
287 return start <= text.length - 2 ? text.slice(start, -2) : null;
288}
289
290// The path class excludes the sigil, so matching is linear on any input.
291const MENTION = /^(?:merge request ([\w.\-/]*)!|issue ([\w.\-/]*)#)([1-9]\d*)$/;
292
293/**
294 * Where a "mentioned in merge request !12" note came from, addressed from the issue's own web URL
295 * so a self-managed host under a subpath resolves. A commit, epic or snippet mention gets none.
296 */
297export function withMentionReference(
298 event: IssueEvent,
299 issueUrl: string,
300 scope: string,
301): IssueEvent {
302 const match = event.kind === "referenced" ? MENTION.exec(event.detail ?? "") : null;
303 const projectUrl = issueUrl.split("/-/")[0]!;
304 if (match === null || !projectUrl.toLowerCase().endsWith(`/${scope.toLowerCase()}`)) {
305 return event;
306 }
307 const [, mergeRequestPath, issuePath, digits] = match;
308 const isMergeRequest = mergeRequestPath !== undefined;
309 const path = mergeRequestPath ?? issuePath ?? "";
310 // A project in the same namespace is named by its path alone.
311 const repository =
312 path === "" ? scope : path.includes("/") ? path : `${scope.replace(/[^/]*$/, "")}${path}`;
313 const base = projectUrl.slice(0, projectUrl.length - scope.length);
314 return {
315 ...event,
316 reference: {
317 repository,
318 number: Number(digits),
319 kind: isMergeRequest ? "pull-request" : "issue",
320 url: `${base}${repository}/-/${isMergeRequest ? "merge_requests" : "issues"}/${digits}`,
321 },
322 };
323}
324
325interface GitLabIssueNotes {
326 readonly comments: ReadonlyArray<IssueComment>;
327 readonly events: ReadonlyArray<IssueEvent>;
328 readonly rawCount: number;
329}
330
331/** One page of notes, split into what people wrote and what GitLab wrote about the issue. */
332export function decodeIssueNotesJson(raw: string): Result.Result<GitLabIssueNotes, DecodeFailure> {
333 return Result.map(decodeUnknownList(raw), (rows) => {
334 const comments: IssueComment[] = [];
335 const events: IssueEvent[] = [];
336 for (const entry of rows) {
337 const note = decodeNoteEntry(entry);
338 if (Exit.isFailure(note)) continue;
339 const value = note.value;
340 const body = value.body ?? "";
341 if (value.system === true) {
342 const event = toSystemEvent(body);
343 if (event === null) continue;
344 events.push({
345 // Notes and label events are numbered separately, so each carries where it came from.
346 id: `note-${value.id}`,
347 kind: event.kind,
348 actor: toActor(value.author),
349 createdAt: value.created_at,
350 detail: event.detail,
351 });
352 continue;
353 }
354 comments.push({
355 id: String(value.id),
356 author: toActor(value.author),
357 body,
358 createdAt: value.created_at,
359 url: null,
360 });
361 }
362 return { comments, events, rawCount: rows.length };
363 });
364}
365
366export function decodeLabelEventsJson(
367 raw: string,
368): Result.Result<ReadonlyArray<IssueEvent>, DecodeFailure> {
369 return Result.map(decodeUnknownList(raw), (rows) =>
370 rows.flatMap((entry) => {
371 const event = decodeLabelEventEntry(entry);
372 if (Exit.isFailure(event)) return [];
373 const action = event.value.action.trim().toLowerCase();
374 if (action !== "add" && action !== "remove") return [];
375 return [
376 {
377 id: `label-${event.value.id}`,
378 kind: action === "add" ? ("labeled" as const) : ("unlabeled" as const),
379 actor: toActor(event.value.user),
380 createdAt: event.value.created_at,
381 detail: trimmed(event.value.label?.name),
382 },
383 ];
384 }),
385 );
386}
387
388function toPullRequestState(value: string | null | undefined): PullRequestState {
389 switch (value?.trim().toLowerCase()) {
390 case "merged":
391 return "merged";
392 case "closed":
393 return "closed";
394 default:
395 // `locked` is an open merge request whose discussion is locked.
396 return "open";
397 }
398}
399
400export function decodeLinkedMergeRequestsJson(
401 raw: string,
402 closesIssue: boolean,
403): Result.Result<ReadonlyArray<IssueLinkedPullRequest>, DecodeFailure> {
404 return Result.map(decodeUnknownList(raw), (rows) =>
405 rows.flatMap((entry) => {
406 const mergeRequest = decodeLinkedMergeRequestEntry(entry);
407 if (Exit.isFailure(mergeRequest)) return [];
408 const value = mergeRequest.value;
409 const repository = trimmed(value.references?.full?.split("!")[0]);
410 const title = trimmed(value.title);
411 const url = trimmed(value.web_url);
412 if (repository === null || title === null || url === null || value.iid <= 0) return [];
413 return [
414 {
415 repository,
416 number: value.iid,
417 title,
418 url,
419 state: toPullRequestState(value.state),
420 isDraft: value.draft ?? value.work_in_progress ?? false,
421 closesIssue,
422 },
423 ];
424 }),
425 );
426}
427
428export function decodeProjectLabelsJson(
429 raw: string,
430): Result.Result<ReadonlyArray<IssueLabelCandidate>, DecodeFailure> {
431 return Result.map(decodeUnknownList(raw), (rows) =>
432 rows.flatMap((entry) => {
433 const label = decodeProjectLabelEntry(entry);
434 if (Exit.isFailure(label)) return [];
435 const name = trimmed(label.value.name);
436 return name === null
437 ? []
438 : [
439 {
440 name,
441 color: trimmed(label.value.color),
442 description: label.value.description ?? null,
443 },
444 ];
445 }),
446 );
447}
448
449/**
450 * The people with access to the project as assignees. GitLab addresses an assignment by numeric
451 * id and by nothing else, so a member it named no id for is dropped rather than offered under a
452 * handle the write would discard.
453 */
454export function decodeProjectMembersJson(
455 raw: string,
456): Result.Result<ReadonlyArray<IssueAssigneeCandidate>, DecodeFailure> {
457 return Result.map(decodeUnknownList(raw), (rows) =>
458 rows.flatMap((entry) => {
459 const user = decodeUserEntry(entry);
460 if (Exit.isFailure(user) || user.value.id === undefined) return [];
461 const actor = toActor(user.value);
462 return actor === null ? [] : [{ ...actor, id: String(user.value.id) }];
463 }),
464 );
465}
466
467export interface GitLabTemplateEntry {
468 readonly key: string;
469 readonly name: string;
470}
471
472export function decodeTemplateEntriesJson(
473 raw: string,
474): Result.Result<ReadonlyArray<GitLabTemplateEntry>, DecodeFailure> {
475 return Result.map(decodeUnknownList(raw), (rows) =>
476 rows.flatMap((entry) => {
477 const template = decodeTemplateEntry(entry);
478 if (Exit.isFailure(template)) return [];
479 const key = trimmed(template.value.key);
480 return key === null ? [] : [{ key, name: trimmed(template.value.name) ?? key }];
481 }),
482 );
483}
484
485/** One template's own answer is the markdown a description starts out as; GitLab adds nothing else. */
486export function decodeTemplateJson(
487 entry: GitLabTemplateEntry,
488 raw: string,
489): Result.Result<IssueTemplate, DecodeFailure> {
490 return Result.map(decodeTemplate(raw), (template) => ({
491 key: entry.key,
492 name: entry.name,
493 about: "",
494 title: "",
495 body: template.content ?? "",
496 labels: [],
497 assignees: [],
498 }));
499}
500
501/**
502 * Awards on every note of the issue, shaped like the merge request query so its decoder answers
503 * for both: `mergeRequest` is an alias for the issue field. GitLab's `Issue` type has no
504 * `awardEmoji`, so the issue's own awards are read from REST `award_emoji` instead.
505 */
506export const ISSUE_AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
507 currentUser { username }
508 project(fullPath: $fullPath) {
509 mergeRequest: issue(iid: $iid) {
510 notes(first: ${PAGE_SIZE}, after: $cursor) {
511 pageInfo { hasNextPage endCursor }
512 nodes { id awardEmoji { nodes { name user { username } } } }
513 }
514 }
515 }
516}`;