@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 444 lines 15.4 KB
Raw
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 */
8 import * as Exit from "effect/Exit";
9 import * as Result from "effect/Result";
10 import * as Schema from "effect/Schema";
11 import 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";
24 import { decodeJsonResult } from "@t3tools/shared/schemaJson";
25 import 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. */
28 export const PAGE_SIZE = 100;
29
30 const 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. */
39 const 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
48 const 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
63 const 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
72 const 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
81 const 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
94 const 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. */
101 const RawTemplateEntrySchema = Schema.Struct({
102 key: Schema.String,
103 name: Schema.optional(Schema.NullOr(Schema.String)),
104 });
105
106 const RawTemplateSchema = Schema.Struct({ content: Schema.optional(Schema.NullOr(Schema.String)) });
107
108 const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
109 const decodeIssue = decodeJsonResult(RawIssueSchema);
110 const decodeIssueList = decodeJsonResult(Schema.Array(RawIssueSchema));
111 const decodeIssueEntry = Schema.decodeUnknownExit(RawIssueSchema);
112 const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema);
113 const decodeLabelEventEntry = Schema.decodeUnknownExit(RawLabelEventSchema);
114 const decodeLinkedMergeRequestEntry = Schema.decodeUnknownExit(RawLinkedMergeRequestSchema);
115 const decodeProjectLabelEntry = Schema.decodeUnknownExit(RawProjectLabelSchema);
116 const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema);
117 const decodeTemplateEntry = Schema.decodeUnknownExit(RawTemplateEntrySchema);
118 const decodeTemplate = decodeJsonResult(RawTemplateSchema);
119
120 type DecodeFailure =
121 ReturnType<typeof decodeIssue> extends Result.Result<unknown, infer E> ? E : never;
122
123 function trimmed(value: string | null | undefined): string | null {
124 const text = value?.trim() ?? "";
125 return text.length > 0 ? text : null;
126 }
127
128 function 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
135 function 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
150 const OPEN: IssueState = { category: "open", name: "Open" };
151 const CLOSED: IssueState = { category: "closed", name: "Closed" };
152
153 /** GitLab has exactly the two states and records no reason for a close. */
154 export const ISSUE_STATES: ReadonlyArray<IssueState> = [OPEN, CLOSED];
155
156 function 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
174 interface 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
180 export 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
190 interface 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. */
195 export 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. */
204 export 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
215 export 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 */
225 function 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 interface GitLabIssueNotes {
254 readonly comments: ReadonlyArray<IssueComment>;
255 readonly events: ReadonlyArray<IssueEvent>;
256 readonly rawCount: number;
257 }
258
259 /** One page of notes, split into what people wrote and what GitLab wrote about the issue. */
260 export function decodeIssueNotesJson(raw: string): Result.Result<GitLabIssueNotes, DecodeFailure> {
261 return Result.map(decodeUnknownList(raw), (rows) => {
262 const comments: IssueComment[] = [];
263 const events: IssueEvent[] = [];
264 for (const entry of rows) {
265 const note = decodeNoteEntry(entry);
266 if (Exit.isFailure(note)) continue;
267 const value = note.value;
268 const body = value.body ?? "";
269 if (value.system === true) {
270 const event = toSystemEvent(body);
271 if (event === null) continue;
272 events.push({
273 // Notes and label events are numbered separately, so each carries where it came from.
274 id: `note-${value.id}`,
275 kind: event.kind,
276 actor: toActor(value.author),
277 createdAt: value.created_at,
278 detail: event.detail,
279 });
280 continue;
281 }
282 comments.push({
283 id: String(value.id),
284 author: toActor(value.author),
285 body,
286 createdAt: value.created_at,
287 url: null,
288 });
289 }
290 return { comments, events, rawCount: rows.length };
291 });
292 }
293
294 export function decodeLabelEventsJson(
295 raw: string,
296 ): Result.Result<ReadonlyArray<IssueEvent>, DecodeFailure> {
297 return Result.map(decodeUnknownList(raw), (rows) =>
298 rows.flatMap((entry) => {
299 const event = decodeLabelEventEntry(entry);
300 if (Exit.isFailure(event)) return [];
301 const action = event.value.action.trim().toLowerCase();
302 if (action !== "add" && action !== "remove") return [];
303 return [
304 {
305 id: `label-${event.value.id}`,
306 kind: action === "add" ? ("labeled" as const) : ("unlabeled" as const),
307 actor: toActor(event.value.user),
308 createdAt: event.value.created_at,
309 detail: trimmed(event.value.label?.name),
310 },
311 ];
312 }),
313 );
314 }
315
316 function toPullRequestState(value: string | null | undefined): PullRequestState {
317 switch (value?.trim().toLowerCase()) {
318 case "merged":
319 return "merged";
320 case "closed":
321 return "closed";
322 default:
323 // `locked` is an open merge request whose discussion is locked.
324 return "open";
325 }
326 }
327
328 export function decodeLinkedMergeRequestsJson(
329 raw: string,
330 closesIssue: boolean,
331 ): Result.Result<ReadonlyArray<IssueLinkedPullRequest>, DecodeFailure> {
332 return Result.map(decodeUnknownList(raw), (rows) =>
333 rows.flatMap((entry) => {
334 const mergeRequest = decodeLinkedMergeRequestEntry(entry);
335 if (Exit.isFailure(mergeRequest)) return [];
336 const value = mergeRequest.value;
337 const repository = trimmed(value.references?.full?.split("!")[0]);
338 const title = trimmed(value.title);
339 const url = trimmed(value.web_url);
340 if (repository === null || title === null || url === null || value.iid <= 0) return [];
341 return [
342 {
343 repository,
344 number: value.iid,
345 title,
346 url,
347 state: toPullRequestState(value.state),
348 isDraft: value.draft ?? value.work_in_progress ?? false,
349 closesIssue,
350 },
351 ];
352 }),
353 );
354 }
355
356 export function decodeProjectLabelsJson(
357 raw: string,
358 ): Result.Result<ReadonlyArray<IssueLabelCandidate>, DecodeFailure> {
359 return Result.map(decodeUnknownList(raw), (rows) =>
360 rows.flatMap((entry) => {
361 const label = decodeProjectLabelEntry(entry);
362 if (Exit.isFailure(label)) return [];
363 const name = trimmed(label.value.name);
364 return name === null
365 ? []
366 : [
367 {
368 name,
369 color: trimmed(label.value.color),
370 description: label.value.description ?? null,
371 },
372 ];
373 }),
374 );
375 }
376
377 /**
378 * The people with access to the project as assignees. GitLab addresses an assignment by numeric
379 * id and by nothing else, so a member it named no id for is dropped rather than offered under a
380 * handle the write would discard.
381 */
382 export function decodeProjectMembersJson(
383 raw: string,
384 ): Result.Result<ReadonlyArray<IssueAssigneeCandidate>, DecodeFailure> {
385 return Result.map(decodeUnknownList(raw), (rows) =>
386 rows.flatMap((entry) => {
387 const user = decodeUserEntry(entry);
388 if (Exit.isFailure(user) || user.value.id === undefined) return [];
389 const actor = toActor(user.value);
390 return actor === null ? [] : [{ ...actor, id: String(user.value.id) }];
391 }),
392 );
393 }
394
395 export interface GitLabTemplateEntry {
396 readonly key: string;
397 readonly name: string;
398 }
399
400 export function decodeTemplateEntriesJson(
401 raw: string,
402 ): Result.Result<ReadonlyArray<GitLabTemplateEntry>, DecodeFailure> {
403 return Result.map(decodeUnknownList(raw), (rows) =>
404 rows.flatMap((entry) => {
405 const template = decodeTemplateEntry(entry);
406 if (Exit.isFailure(template)) return [];
407 const key = trimmed(template.value.key);
408 return key === null ? [] : [{ key, name: trimmed(template.value.name) ?? key }];
409 }),
410 );
411 }
412
413 /** One template's own answer is the markdown a description starts out as; GitLab adds nothing else. */
414 export function decodeTemplateJson(
415 entry: GitLabTemplateEntry,
416 raw: string,
417 ): Result.Result<IssueTemplate, DecodeFailure> {
418 return Result.map(decodeTemplate(raw), (template) => ({
419 key: entry.key,
420 name: entry.name,
421 about: "",
422 title: "",
423 body: template.content ?? "",
424 labels: [],
425 assignees: [],
426 }));
427 }
428
429 /**
430 * Awards on every note of the issue, shaped like the merge request query so its decoder answers
431 * for both: `mergeRequest` is an alias for the issue field. GitLab's `Issue` type has no
432 * `awardEmoji`, so the issue's own awards are read from REST `award_emoji` instead.
433 */
434 export const ISSUE_AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
435 currentUser { username }
436 project(fullPath: $fullPath) {
437 mergeRequest: issue(iid: $iid) {
438 notes(first: ${PAGE_SIZE}, after: $cursor) {
439 pageInfo { hasNextPage endCursor }
440 nodes { id awardEmoji { nodes { name user { username } } } }
441 }
442 }
443 }
444 }`;