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
221/**
222 * The events GitLab records as notes of its own. A label note names its labels by id ("added ~7
223 * label"), which is why labellings come from `/resource_label_events` instead and are dropped here.
224 */
225function toSystemEvent(
226 body: string,
227): { readonly kind: IssueEventKind; readonly detail: string | null } | null {
228 const text = body.trim();
229 if (text === "closed") return { kind: "closed", detail: null };
230 if (text === "reopened") return { kind: "reopened", detail: null };
231 if (text.startsWith("assigned to ")) {
232 return {
233 kind: "assigned",
234 detail: trimmed(text.slice("assigned to ".length).replace(/^@/, "")),
235 };
236 }
237 if (text.startsWith("unassigned ")) {
238 return {
239 kind: "unassigned",
240 detail: trimmed(text.slice("unassigned ".length).replace(/^@/, "")),
241 };
242 }
243 if (text.startsWith("mentioned in ")) {
244 return { kind: "referenced", detail: trimmed(text.slice("mentioned in ".length)) };
245 }
246 if (text.startsWith("changed title")) {
247 // GitLab marks the new title with its own inline-diff braces.
248 return { kind: "renamed", detail: trimmed(/\{\+(.+)\+\}/.exec(text)?.[1]) };
249 }
250 return null;
251}
252
253// The path class excludes the sigil, so matching is linear on any input.
254const MENTION = /^(?:merge request ([\w.\-/]*)!|issue ([\w.\-/]*)#)([1-9]\d*)$/;
255
256/**
257 * Where a "mentioned in merge request !12" note came from, addressed from the issue's own web URL
258 * so a self-managed host under a subpath resolves. A commit, epic or snippet mention gets none.
259 */
260export function withMentionReference(
261 event: IssueEvent,
262 issueUrl: string,
263 scope: string,
264): IssueEvent {
265 const match = event.kind === "referenced" ? MENTION.exec(event.detail ?? "") : null;
266 const projectUrl = issueUrl.split("/-/")[0]!;
267 if (match === null || !projectUrl.toLowerCase().endsWith(`/${scope.toLowerCase()}`)) {
268 return event;
269 }
270 const [, mergeRequestPath, issuePath, digits] = match;
271 const isMergeRequest = mergeRequestPath !== undefined;
272 const path = mergeRequestPath ?? issuePath ?? "";
273 // A project in the same namespace is named by its path alone.
274 const repository =
275 path === "" ? scope : path.includes("/") ? path : `${scope.replace(/[^/]*$/, "")}${path}`;
276 const base = projectUrl.slice(0, projectUrl.length - scope.length);
277 return {
278 ...event,
279 reference: {
280 repository,
281 number: Number(digits),
282 kind: isMergeRequest ? "pull-request" : "issue",
283 url: `${base}${repository}/-/${isMergeRequest ? "merge_requests" : "issues"}/${digits}`,
284 },
285 };
286}
287
288interface GitLabIssueNotes {
289 readonly comments: ReadonlyArray<IssueComment>;
290 readonly events: ReadonlyArray<IssueEvent>;
291 readonly rawCount: number;
292}
293
294/** One page of notes, split into what people wrote and what GitLab wrote about the issue. */
295export function decodeIssueNotesJson(raw: string): Result.Result<GitLabIssueNotes, DecodeFailure> {
296 return Result.map(decodeUnknownList(raw), (rows) => {
297 const comments: IssueComment[] = [];
298 const events: IssueEvent[] = [];
299 for (const entry of rows) {
300 const note = decodeNoteEntry(entry);
301 if (Exit.isFailure(note)) continue;
302 const value = note.value;
303 const body = value.body ?? "";
304 if (value.system === true) {
305 const event = toSystemEvent(body);
306 if (event === null) continue;
307 events.push({
308 // Notes and label events are numbered separately, so each carries where it came from.
309 id: `note-${value.id}`,
310 kind: event.kind,
311 actor: toActor(value.author),
312 createdAt: value.created_at,
313 detail: event.detail,
314 });
315 continue;
316 }
317 comments.push({
318 id: String(value.id),
319 author: toActor(value.author),
320 body,
321 createdAt: value.created_at,
322 url: null,
323 });
324 }
325 return { comments, events, rawCount: rows.length };
326 });
327}
328
329export function decodeLabelEventsJson(
330 raw: string,
331): Result.Result<ReadonlyArray<IssueEvent>, DecodeFailure> {
332 return Result.map(decodeUnknownList(raw), (rows) =>
333 rows.flatMap((entry) => {
334 const event = decodeLabelEventEntry(entry);
335 if (Exit.isFailure(event)) return [];
336 const action = event.value.action.trim().toLowerCase();
337 if (action !== "add" && action !== "remove") return [];
338 return [
339 {
340 id: `label-${event.value.id}`,
341 kind: action === "add" ? ("labeled" as const) : ("unlabeled" as const),
342 actor: toActor(event.value.user),
343 createdAt: event.value.created_at,
344 detail: trimmed(event.value.label?.name),
345 },
346 ];
347 }),
348 );
349}
350
351function toPullRequestState(value: string | null | undefined): PullRequestState {
352 switch (value?.trim().toLowerCase()) {
353 case "merged":
354 return "merged";
355 case "closed":
356 return "closed";
357 default:
358 // `locked` is an open merge request whose discussion is locked.
359 return "open";
360 }
361}
362
363export function decodeLinkedMergeRequestsJson(
364 raw: string,
365 closesIssue: boolean,
366): Result.Result<ReadonlyArray<IssueLinkedPullRequest>, DecodeFailure> {
367 return Result.map(decodeUnknownList(raw), (rows) =>
368 rows.flatMap((entry) => {
369 const mergeRequest = decodeLinkedMergeRequestEntry(entry);
370 if (Exit.isFailure(mergeRequest)) return [];
371 const value = mergeRequest.value;
372 const repository = trimmed(value.references?.full?.split("!")[0]);
373 const title = trimmed(value.title);
374 const url = trimmed(value.web_url);
375 if (repository === null || title === null || url === null || value.iid <= 0) return [];
376 return [
377 {
378 repository,
379 number: value.iid,
380 title,
381 url,
382 state: toPullRequestState(value.state),
383 isDraft: value.draft ?? value.work_in_progress ?? false,
384 closesIssue,
385 },
386 ];
387 }),
388 );
389}
390
391export function decodeProjectLabelsJson(
392 raw: string,
393): Result.Result<ReadonlyArray<IssueLabelCandidate>, DecodeFailure> {
394 return Result.map(decodeUnknownList(raw), (rows) =>
395 rows.flatMap((entry) => {
396 const label = decodeProjectLabelEntry(entry);
397 if (Exit.isFailure(label)) return [];
398 const name = trimmed(label.value.name);
399 return name === null
400 ? []
401 : [
402 {
403 name,
404 color: trimmed(label.value.color),
405 description: label.value.description ?? null,
406 },
407 ];
408 }),
409 );
410}
411
412/**
413 * The people with access to the project as assignees. GitLab addresses an assignment by numeric
414 * id and by nothing else, so a member it named no id for is dropped rather than offered under a
415 * handle the write would discard.
416 */
417export function decodeProjectMembersJson(
418 raw: string,
419): Result.Result<ReadonlyArray<IssueAssigneeCandidate>, DecodeFailure> {
420 return Result.map(decodeUnknownList(raw), (rows) =>
421 rows.flatMap((entry) => {
422 const user = decodeUserEntry(entry);
423 if (Exit.isFailure(user) || user.value.id === undefined) return [];
424 const actor = toActor(user.value);
425 return actor === null ? [] : [{ ...actor, id: String(user.value.id) }];
426 }),
427 );
428}
429
430export interface GitLabTemplateEntry {
431 readonly key: string;
432 readonly name: string;
433}
434
435export function decodeTemplateEntriesJson(
436 raw: string,
437): Result.Result<ReadonlyArray<GitLabTemplateEntry>, DecodeFailure> {
438 return Result.map(decodeUnknownList(raw), (rows) =>
439 rows.flatMap((entry) => {
440 const template = decodeTemplateEntry(entry);
441 if (Exit.isFailure(template)) return [];
442 const key = trimmed(template.value.key);
443 return key === null ? [] : [{ key, name: trimmed(template.value.name) ?? key }];
444 }),
445 );
446}
447
448/** One template's own answer is the markdown a description starts out as; GitLab adds nothing else. */
449export function decodeTemplateJson(
450 entry: GitLabTemplateEntry,
451 raw: string,
452): Result.Result<IssueTemplate, DecodeFailure> {
453 return Result.map(decodeTemplate(raw), (template) => ({
454 key: entry.key,
455 name: entry.name,
456 about: "",
457 title: "",
458 body: template.content ?? "",
459 labels: [],
460 assignees: [],
461 }));
462}
463
464/**
465 * Awards on every note of the issue, shaped like the merge request query so its decoder answers
466 * for both: `mergeRequest` is an alias for the issue field. GitLab's `Issue` type has no
467 * `awardEmoji`, so the issue's own awards are read from REST `award_emoji` instead.
468 */
469export const ISSUE_AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
470 currentUser { username }
471 project(fullPath: $fullPath) {
472 mergeRequest: issue(iid: $iid) {
473 notes(first: ${PAGE_SIZE}, after: $cursor) {
474 pageInfo { hasNextPage endCursor }
475 nodes { id awardEmoji { nodes { name user { username } } } }
476 }
477 }
478 }
479}`;