Open History to see the last commit
1import * as Result from "effect/Result";
2import { describe, expect, it } from "vite-plus/test";
3
4import {
5 decodeAwardEmojiJson,
6 decodeRepositoryBlobsJson,
7 decodeCommitsJson,
8 decodeMergeRequestDetailJson,
9 decodeMergeRequestDiffsJson,
10 decodeMergeRequestListJson,
11 decodeMergeRequestFileStatsJson,
12 decodeMergeRequestStatsJson,
13 decodeNotesJson,
14 decodeOwnAwardIdJson,
15 decodeTriggerJobChecksJson,
16} from "./gitLabMergeRequestJson.ts";
17
18function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
19 return JSON.stringify(
20 entries.map((entry) => ({
21 iid: 1,
22 title: "Add the merge requests page",
23 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
24 source_branch: "feat/page",
25 target_branch: "main",
26 created_at: "2026-07-01T00:00:00Z",
27 updated_at: "2026-07-02T00:00:00Z",
28 ...entry,
29 })),
30 );
31}
32
33function detailJson(entry: Record<string, unknown>): string {
34 return JSON.stringify({
35 iid: 1,
36 title: "Add the merge requests page",
37 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
38 source_branch: "feat/page",
39 target_branch: "main",
40 created_at: "2026-07-01T00:00:00Z",
41 updated_at: "2026-07-02T00:00:00Z",
42 ...entry,
43 });
44}
45
46function expectSuccess<A>(result: Result.Result<A, unknown>): A {
47 expect(Result.isSuccess(result)).toBe(true);
48 if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
49 return result.success;
50}
51
52describe("decodeMergeRequestListJson", () => {
53 it("reads a merge request as a change request", () => {
54 const batch = expectSuccess(
55 decodeMergeRequestListJson(
56 listJson([
57 {
58 iid: 42,
59 author: { username: "bilal", name: "Bilal" },
60 state: "opened",
61 merge_status: "can_be_merged",
62 draft: false,
63 reviewers: [{ username: "julius" }],
64 labels: ["backend", " "],
65 },
66 ]),
67 ),
68 );
69
70 expect(batch.items).toHaveLength(1);
71 expect(batch.items[0]).toMatchObject({
72 number: 42,
73 author: { login: "bilal", name: "Bilal" },
74 headBranch: "feat/page",
75 baseBranch: "main",
76 state: "open",
77 isDraft: false,
78 mergeability: "mergeable",
79 reviewRequestLogins: ["julius"],
80 labels: [{ name: "backend", color: null }],
81 });
82 });
83
84 it("treats a merged timestamp as merged whatever the state says", () => {
85 const batch = expectSuccess(
86 decodeMergeRequestListJson(
87 listJson([{ state: "opened", merged_at: "2026-07-03T00:00:00Z" }]),
88 ),
89 );
90
91 expect(batch.items[0]?.state).toBe("merged");
92 });
93
94 it("reads the legacy draft flag", () => {
95 const batch = expectSuccess(decodeMergeRequestListJson(listJson([{ work_in_progress: true }])));
96
97 expect(batch.items[0]?.isDraft).toBe(true);
98 });
99
100 it("calls a conflicted merge request conflicting even while the merge check is pending", () => {
101 const batch = expectSuccess(
102 decodeMergeRequestListJson(listJson([{ merge_status: "checking", has_conflicts: true }])),
103 );
104
105 expect(batch.items[0]?.mergeability).toBe("conflicting");
106 });
107
108 it("skips a malformed row but still counts it, so paging does not stop early", () => {
109 const batch = expectSuccess(
110 decodeMergeRequestListJson(
111 JSON.stringify([{ iid: "not a number" }, ...JSON.parse(listJson([{}]))]),
112 ),
113 );
114
115 expect(batch.items).toHaveLength(1);
116 expect(batch.rawIndexes).toEqual([1]);
117 expect(batch.rawCount).toBe(2);
118 });
119});
120
121describe("decodeMergeRequestDetailJson", () => {
122 it("reads the description, file count and pipeline", () => {
123 const detail = expectSuccess(
124 decodeMergeRequestDetailJson(
125 detailJson({
126 description: "Ships the page.",
127 changes_count: "3",
128 reviewers: [{ username: "julius", name: "Julius" }],
129 head_pipeline: {
130 status: "success",
131 web_url: "https://gitlab.com/acme/web/-/pipelines/9",
132 source: "merge_request_event",
133 },
134 }),
135 ),
136 );
137
138 expect(detail.body).toBe("Ships the page.");
139 expect(detail.changedFiles).toBe(3);
140 expect(detail.reviewers).toEqual([{ login: "julius", name: "Julius", avatarUrl: null }]);
141 expect(detail.checks).toEqual([
142 {
143 name: "Pipeline",
144 status: "success",
145 description: "merge_request_event",
146 url: "https://gitlab.com/acme/web/-/pipelines/9",
147 },
148 ]);
149 });
150
151 it("reads an uncounted change set as its floor", () => {
152 const detail = expectSuccess(
153 decodeMergeRequestDetailJson(detailJson({ changes_count: "1000+" })),
154 );
155
156 expect(detail.changedFiles).toBe(1000);
157 });
158
159 it("reads the head commit, and says nothing where GitLab omitted it", () => {
160 const headSha = (entry: Record<string, unknown>) =>
161 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).headSha;
162 const sha = "afce4da4d5fe7d2fd0647b5b864526ea0a2827cb";
163
164 expect(headSha({ sha })).toBe(sha);
165 expect(headSha({ sha, diff_refs: null })).toBe(sha);
166 expect(headSha({ sha, merge_commit_sha: "0".repeat(40) })).toBe(sha);
167 expect(headSha({})).toBeUndefined();
168 expect(headSha({ sha: null })).toBeUndefined();
169 expect(headSha({ sha: " " })).toBeUndefined();
170 });
171
172 it("reads either auto-merge field, and says nothing where GitLab named neither", () => {
173 const armed = (entry: Record<string, unknown>) =>
174 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).autoMergeEnabled;
175
176 expect(armed({ merge_when_pipeline_succeeds: true })).toBe(true);
177 expect(armed({ auto_merge_enabled: true })).toBe(true);
178 expect(armed({ merge_when_pipeline_succeeds: false })).toBe(false);
179 expect(armed({})).toBeUndefined();
180 });
181
182 it("keeps the squash choice stored with auto-merge", () => {
183 expect(
184 expectSuccess(
185 decodeMergeRequestDetailJson(
186 detailJson({ auto_merge_enabled: true, squash_on_merge: true }),
187 ),
188 ),
189 ).toMatchObject({ autoMergeEnabled: true, autoMergeMethod: "squash" });
190
191 expect(
192 expectSuccess(
193 decodeMergeRequestDetailJson(
194 detailJson({
195 auto_merge_enabled: true,
196 squash: true,
197 squash_on_merge: false,
198 }),
199 ),
200 ).autoMergeMethod,
201 ).toBeUndefined();
202 });
203
204 it("keeps a divergence GitLab did not count apart from a divergence of none", () => {
205 const behind = (entry: Record<string, unknown>) =>
206 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).divergedCommits;
207
208 expect(behind({ diverged_commits_count: 3 })).toBe(3);
209 expect(behind({ diverged_commits_count: 0 })).toBe(0);
210 expect(behind({})).toBeUndefined();
211 expect(behind({ diverged_commits_count: null })).toBeUndefined();
212 });
213
214 it.each(["scheduled", " SCHEDULED "])("keeps a delayed pipeline pending: %s", (status) => {
215 const detail = expectSuccess(
216 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status } })),
217 );
218
219 expect(detail.checks[0]?.status).toBe("pending");
220 });
221
222 it("maps a pipeline waiting on a person to neutral, not failure", () => {
223 const detail = expectSuccess(
224 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status: "manual" } })),
225 );
226
227 expect(detail.checks[0]?.status).toBe("neutral");
228 });
229});
230
231describe("decodeNotesJson", () => {
232 it("keeps comments and drops GitLab's own activity notes", () => {
233 const notes = expectSuccess(
234 decodeNotesJson(
235 JSON.stringify([
236 {
237 id: 1,
238 body: "assigned to @bilal",
239 system: true,
240 created_at: "2026-07-01T00:00:00Z",
241 },
242 {
243 id: 2,
244 body: "Looks good.",
245 author: { username: "julius" },
246 created_at: "2026-07-02T00:00:00Z",
247 },
248 { id: 3, body: " ", created_at: "2026-07-03T00:00:00Z" },
249 ]),
250 ),
251 );
252
253 expect(notes.comments).toHaveLength(1);
254 expect(notes.comments[0]).toMatchObject({
255 id: "2",
256 kind: "issue-comment",
257 body: "Looks good.",
258 });
259 expect(notes.rawCount).toBe(3);
260 });
261
262 it("reads a line note as a review comment on its file", () => {
263 const notes = expectSuccess(
264 decodeNotesJson(
265 JSON.stringify([
266 {
267 id: 7,
268 type: "DiffNote",
269 body: "Rename this.",
270 created_at: "2026-07-02T00:00:00Z",
271 position: { new_path: "src/app.ts", old_path: "src/old.ts" },
272 },
273 ]),
274 ),
275 );
276
277 expect(notes.comments[0]).toMatchObject({ kind: "review-comment", path: "src/app.ts" });
278 });
279
280 it("falls back to the old path for a note on a deleted line", () => {
281 const notes = expectSuccess(
282 decodeNotesJson(
283 JSON.stringify([
284 {
285 id: 8,
286 type: "DiffNote",
287 body: "Gone.",
288 created_at: "2026-07-02T00:00:00Z",
289 position: { new_path: null, old_path: "src/old.ts" },
290 },
291 ]),
292 ),
293 );
294
295 expect(notes.comments[0]?.path).toBe("src/old.ts");
296 });
297});
298
299describe("decodeCommitsJson", () => {
300 it("falls back to the creation timestamp when there is no commit date", () => {
301 const commits = expectSuccess(
302 decodeCommitsJson(
303 JSON.stringify([
304 {
305 id: "aaa",
306 created_at: "2026-07-01T00:00:00+08:00",
307 author_name: "Ada Lovelace",
308 author_email: "ada@example.com",
309 },
310 ]),
311 ),
312 );
313
314 expect(commits[0]).toMatchObject({
315 oid: "aaa",
316 committedDate: "2026-07-01T00:00:00+08:00",
317 authors: [{ login: "Ada Lovelace", name: "Ada Lovelace", avatarUrl: null }],
318 });
319 });
320});
321
322describe("decodeMergeRequestDiffsJson", () => {
323 it("quotes literal backslashes without interpreting them as escapes", () => {
324 const result = expectSuccess(
325 decodeMergeRequestDiffsJson(
326 JSON.stringify([
327 {
328 old_path: String.raw`src\notes.ts`,
329 new_path: String.raw`src\notes.ts`,
330 diff: "@@ -1 +1 @@\n-old\n+new",
331 },
332 ]),
333 ),
334 );
335
336 expect(result.patch).toBe(
337 [
338 String.raw`diff --git "a/src\\notes.ts" "b/src\\notes.ts"`,
339 String.raw`--- "a/src\\notes.ts"`,
340 String.raw`+++ "b/src\\notes.ts"`,
341 "@@ -1 +1 @@",
342 "-old",
343 "+new",
344 "",
345 ].join("\n"),
346 );
347 });
348
349 it("preserves spaces and literal backslashes in both rename paths", () => {
350 const result = expectSuccess(
351 decodeMergeRequestDiffsJson(
352 JSON.stringify([
353 {
354 old_path: String.raw` old\name.ts `,
355 new_path: String.raw` new\name.ts `,
356 renamed_file: true,
357 diff: "",
358 },
359 ]),
360 ),
361 );
362
363 expect(result.patch).toBe(
364 [
365 String.raw`diff --git "a/ old\\name.ts " "b/ new\\name.ts "`,
366 String.raw`rename from " old\\name.ts "`,
367 String.raw`rename to " new\\name.ts "`,
368 String.raw`--- "a/ old\\name.ts "`,
369 String.raw`+++ "b/ new\\name.ts "`,
370 ].join("\n"),
371 );
372 });
373
374 it("assembles a unified patch GitLab does not return", () => {
375 const result = expectSuccess(
376 decodeMergeRequestDiffsJson(
377 JSON.stringify([
378 {
379 old_path: "src/app.ts",
380 new_path: "src/app.ts",
381 diff: "@@ -1 +1 @@\n-old\n+new\n",
382 },
383 ]),
384 ),
385 );
386
387 expect(result.patch).toBe(
388 [
389 "diff --git a/src/app.ts b/src/app.ts",
390 "--- a/src/app.ts",
391 "+++ b/src/app.ts",
392 "@@ -1 +1 @@",
393 "-old",
394 "+new",
395 "",
396 ].join("\n"),
397 );
398 expect(result.truncated).toBe(false);
399 });
400
401 it("points a new file at /dev/null on the left and a deleted file on the right", () => {
402 const result = expectSuccess(
403 decodeMergeRequestDiffsJson(
404 JSON.stringify([
405 {
406 old_path: "src/new.ts",
407 new_path: "src/new.ts",
408 new_file: true,
409 b_mode: "100755",
410 diff: "@@ -0,0 +1 @@\n+hello\n",
411 },
412 {
413 old_path: "src/gone.ts",
414 new_path: "src/gone.ts",
415 deleted_file: true,
416 diff: "@@ -1 +0,0 @@\n-bye\n",
417 },
418 ]),
419 ),
420 );
421
422 expect(result.patch).toContain("new file mode 100755");
423 expect(result.patch).toContain("--- /dev/null");
424 expect(result.patch).toContain("deleted file mode 100644");
425 expect(result.patch).toContain("+++ /dev/null");
426 });
427
428 it("reports truncation for a file GitLab refused to inline", () => {
429 const result = expectSuccess(
430 decodeMergeRequestDiffsJson(
431 JSON.stringify([{ old_path: "big.bin", new_path: "big.bin", diff: "", too_large: true }]),
432 ),
433 );
434
435 expect(result.truncated).toBe(true);
436 expect(result.patch).toContain("diff --git a/big.bin b/big.bin");
437 });
438
439 it("reports how many files GitLab returned, so the caller can page", () => {
440 const result = expectSuccess(
441 decodeMergeRequestDiffsJson(
442 JSON.stringify(
443 Array.from({ length: 3 }, (_, index) => ({
444 old_path: `src/${index}.ts`,
445 new_path: `src/${index}.ts`,
446 diff: "@@ -1 +1 @@\n-a\n+b\n",
447 })),
448 ),
449 ),
450 );
451
452 expect(result.rawCount).toBe(3);
453 expect(result.truncated).toBe(false);
454 expect(result.patch).toContain("src/2.ts");
455 });
456});
457
458describe("decodeTriggerJobChecksJson", () => {
459 it("reads a downstream failure GitLab was told to allow as neutral, not failure", () => {
460 const result = expectSuccess(
461 decodeTriggerJobChecksJson(
462 JSON.stringify([
463 { name: "e2e", allow_failure: true, downstream_pipeline: { status: "failed" } },
464 { name: "deploy", allow_failure: false, downstream_pipeline: { status: "running" } },
465 { name: 7 },
466 ]),
467 ),
468 );
469
470 expect(result.checks.map((check) => [check.name, check.status])).toEqual([
471 ["e2e", "neutral"],
472 ["deploy", "pending"],
473 ]);
474 expect(result.rawCount).toBe(3);
475 });
476});
477
478describe("merge request viewer fields", () => {
479 it("leaves merging permitted where GitLab answered without the field", () => {
480 expect(expectSuccess(decodeMergeRequestDetailJson(detailJson({}))).viewerCanMerge).toBe(true);
481 expect(
482 expectSuccess(decodeMergeRequestDetailJson(detailJson({ user: null }))).viewerCanMerge,
483 ).toBe(true);
484 });
485});
486
487describe("decodeAwardEmojiJson", () => {
488 it("reads MR-level awards, keys per-note awards by the REST id inside their gid, and ignores an award outside the eight", () => {
489 const result = expectSuccess(
490 decodeAwardEmojiJson(
491 JSON.stringify({
492 data: {
493 currentUser: { username: "bilal" },
494 project: {
495 mergeRequest: {
496 awardEmoji: {
497 nodes: [
498 { name: "thumbsup", user: { username: "bilal" } },
499 { name: "thumbsup", user: { username: "julius" } },
500 ],
501 },
502 notes: {
503 pageInfo: { hasNextPage: false, endCursor: null },
504 nodes: [
505 {
506 id: "gid://gitlab/DiffNote/42",
507 awardEmoji: { nodes: [{ name: "heart", user: { username: "julius" } }] },
508 },
509 {
510 id: "gid://gitlab/Note/7",
511 awardEmoji: {
512 nodes: [{ name: "partyparrot", user: { username: "bilal" } }],
513 },
514 },
515 ],
516 },
517 },
518 },
519 },
520 }),
521 ),
522 );
523
524 expect(result.reactions).toEqual([
525 { content: "thumbs-up", count: 2, actors: ["julius"], viewerHasReacted: true },
526 ]);
527 expect([...result.reactionsByNoteId]).toEqual([
528 ["42", [{ content: "heart", count: 1, actors: ["julius"], viewerHasReacted: false }]],
529 ]);
530 expect(result.nextCursor).toBeNull();
531 });
532
533 it("matches the viewer's username case-insensitively, since GitLab is not consistent about case", () => {
534 const result = expectSuccess(
535 decodeAwardEmojiJson(
536 JSON.stringify({
537 data: {
538 currentUser: { username: "Bilal" },
539 project: {
540 mergeRequest: {
541 awardEmoji: {
542 nodes: [
543 { name: "heart", user: { username: "bilal" } },
544 { name: "heart", user: { username: "julius" } },
545 ],
546 },
547 notes: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] },
548 },
549 },
550 },
551 }),
552 ),
553 );
554
555 expect(result.reactions).toEqual([
556 { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
557 ]);
558 });
559});
560
561describe("decodeOwnAwardIdJson", () => {
562 const awards = JSON.stringify([
563 { id: 101, name: "thumbsup", user: { username: "julius" } },
564 { id: 102, name: "thumbsup", user: { username: "bilal" } },
565 ]);
566
567 it("finds the reader's own award of that name, which is the one a removal deletes", () => {
568 expect(
569 expectSuccess(decodeOwnAwardIdJson(awards, { content: "thumbs-up", viewer: "bilal" })),
570 ).toBe(102);
571 });
572});
573
574describe("decodeRepositoryBlobsJson", () => {
575 function expectBlobs(result: Result.Result<ReadonlyMap<string, string> | null, unknown>) {
576 const blobs = expectSuccess(result);
577 expect(blobs).not.toBe(null);
578 if (blobs === null) throw new Error("expected an answered blobs query");
579 return blobs;
580 }
581
582 it("leaves out a node missing either half, which names no version", () => {
583 const blobs = expectBlobs(
584 decodeRepositoryBlobsJson(
585 JSON.stringify({
586 data: {
587 project: {
588 repository: {
589 blobs: {
590 nodes: [
591 { path: "src/a.ts", oid: null },
592 { path: null, oid: "bbb222" },
593 null,
594 { path: "src/c.ts", oid: "ccc333" },
595 ],
596 },
597 },
598 },
599 },
600 }),
601 ),
602 );
603
604 expect([...blobs]).toEqual([["src/c.ts", "ccc333"]]);
605 });
606
607 it("keys a blob by the path the host spelled, spaces and all", () => {
608 const blobs = expectBlobs(
609 decodeRepositoryBlobsJson(
610 JSON.stringify({
611 data: {
612 project: {
613 repository: {
614 blobs: {
615 nodes: [
616 { path: " leading.ts", oid: "aaa111" },
617 { path: "trailing.ts ", oid: "bbb222" },
618 { path: " ", oid: "ccc333" },
619 { path: "", oid: "ddd444" },
620 ],
621 },
622 },
623 },
624 },
625 }),
626 ),
627 );
628
629 expect([...blobs]).toEqual([
630 [" leading.ts", "aaa111"],
631 ["trailing.ts ", "bbb222"],
632 [" ", "ccc333"],
633 ]);
634 });
635
636 it("tells a project the reader cannot see from a revision with none of the files", () => {
637 expect(
638 expectSuccess(decodeRepositoryBlobsJson(JSON.stringify({ data: { project: null } }))),
639 ).toBe(null);
640 expect(
641 expectSuccess(
642 decodeRepositoryBlobsJson(JSON.stringify({ data: { project: { repository: null } } })),
643 ),
644 ).toBe(null);
645 expect(
646 expectSuccess(
647 decodeRepositoryBlobsJson(
648 JSON.stringify({ data: { project: { repository: { blobs: { nodes: [] } } } } }),
649 ),
650 ),
651 ).toEqual(new Map());
652 });
653});
654
655describe("decodeMergeRequestStatsJson", () => {
656 it("keys the counts by merge request number", () => {
657 const stats = expectSuccess(
658 decodeMergeRequestStatsJson(
659 JSON.stringify({
660 data: {
661 project: {
662 mergeRequests: {
663 nodes: [
664 { iid: "7", diffStatsSummary: { additions: 12, deletions: 3 } },
665 { iid: "8", diffStatsSummary: null },
666 ],
667 },
668 },
669 },
670 }),
671 ),
672 );
673
674 // A merge request without a summary is left out rather than shown as zero lines changed.
675 expect([...stats]).toEqual([[7, { additions: 12, deletions: 3 }]]);
676 });
677
678 it("answers nothing for a project the token cannot see", () => {
679 const stats = expectSuccess(
680 decodeMergeRequestStatsJson(JSON.stringify({ data: { project: null } })),
681 );
682
683 expect(stats.size).toBe(0);
684 });
685
686 it("reports a file list shorter than the summary as truncated", () => {
687 const read = (fileCount: number) =>
688 expectSuccess(
689 decodeMergeRequestFileStatsJson(
690 JSON.stringify({
691 data: {
692 project: {
693 mergeRequest: {
694 diffStatsSummary: { fileCount },
695 diffStats: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
696 },
697 },
698 },
699 }),
700 ),
701 );
702
703 expect(read(1)).toEqual({
704 files: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
705 truncated: false,
706 });
707 expect(read(2).truncated).toBe(true);
708 });
709});