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 decodeGraphqlListSupportJson,
9 decodeMergeRequestGraphqlListJson,
10 decodeMergeMessagesJson,
11 decodeMergeRequestDetailJson,
12 decodeMergeRequestDiffsJson,
13 decodeMergeRequestListJson,
14 decodeMergeRequestFileStatsJson,
15 decodeMergeRequestStatsJson,
16 decodeMergeRequestWatchFingerprintJson,
17 decodeReferenceCandidatesJson,
18 decodeNotesJson,
19 decodeOwnAwardIdJson,
20 decodeListStatesJson,
21 decodeTriggerJobChecksJson,
22 decodePipelineStageChecksJson,
23} from "./gitLabMergeRequestJson.ts";
24
25function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
26 return JSON.stringify(
27 entries.map((entry) => ({
28 iid: 1,
29 title: "Add the merge requests page",
30 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
31 source_branch: "feat/page",
32 target_branch: "main",
33 created_at: "2026-07-01T00:00:00Z",
34 updated_at: "2026-07-02T00:00:00Z",
35 ...entry,
36 })),
37 );
38}
39
40function detailJson(entry: Record<string, unknown>): string {
41 return JSON.stringify({
42 iid: 1,
43 title: "Add the merge requests page",
44 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
45 source_branch: "feat/page",
46 target_branch: "main",
47 created_at: "2026-07-01T00:00:00Z",
48 updated_at: "2026-07-02T00:00:00Z",
49 ...entry,
50 });
51}
52
53function expectSuccess<A>(result: Result.Result<A, unknown>): A {
54 expect(Result.isSuccess(result)).toBe(true);
55 if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
56 return result.success;
57}
58
59describe("decodeMergeRequestListJson", () => {
60 it("reads a merge request as a change request", () => {
61 const batch = expectSuccess(
62 decodeMergeRequestListJson(
63 listJson([
64 {
65 iid: 42,
66 author: { username: "bilal", name: "Bilal" },
67 state: "opened",
68 merge_status: "can_be_merged",
69 draft: false,
70 reviewers: [{ username: "julius" }],
71 labels: ["backend", " "],
72 },
73 ]),
74 ),
75 );
76
77 expect(batch.items).toHaveLength(1);
78 expect(batch.items[0]).toMatchObject({
79 number: 42,
80 author: { login: "bilal", name: "Bilal" },
81 headBranch: "feat/page",
82 baseBranch: "main",
83 state: "open",
84 isDraft: false,
85 mergeability: "mergeable",
86 reviewRequestLogins: ["julius"],
87 labels: [{ name: "backend", color: null }],
88 });
89 });
90
91 it("treats a merged timestamp as merged whatever the state says", () => {
92 const batch = expectSuccess(
93 decodeMergeRequestListJson(
94 listJson([{ state: "opened", merged_at: "2026-07-03T00:00:00Z" }]),
95 ),
96 );
97
98 expect(batch.items[0]?.state).toBe("merged");
99 });
100
101 it("reads the legacy draft flag", () => {
102 const batch = expectSuccess(decodeMergeRequestListJson(listJson([{ work_in_progress: true }])));
103
104 expect(batch.items[0]?.isDraft).toBe(true);
105 });
106
107 it("calls a conflicted merge request conflicting even while the merge check is pending", () => {
108 const batch = expectSuccess(
109 decodeMergeRequestListJson(listJson([{ merge_status: "checking", has_conflicts: true }])),
110 );
111
112 expect(batch.items[0]?.mergeability).toBe("conflicting");
113 });
114
115 it("skips a malformed row but still counts it, so paging does not stop early", () => {
116 const batch = expectSuccess(
117 decodeMergeRequestListJson(
118 JSON.stringify([{ iid: "not a number" }, ...JSON.parse(listJson([{}]))]),
119 ),
120 );
121
122 expect(batch.items).toHaveLength(1);
123 expect(batch.rawIndexes).toEqual([1]);
124 expect(batch.rawCount).toBe(2);
125 });
126});
127
128describe("decodeMergeRequestDetailJson", () => {
129 it("preserves a required rebase while CI is running or successful", () => {
130 for (const status of ["running", "success"]) {
131 const detail = expectSuccess(
132 decodeMergeRequestDetailJson(
133 detailJson({
134 merge_status: "can_be_merged",
135 detailed_merge_status: "need_rebase",
136 has_conflicts: false,
137 head_pipeline: { status },
138 }),
139 ),
140 );
141 expect(detail.rebaseRequired).toBe(true);
142 expect(detail.mergeability).toBe("mergeable");
143 }
144 });
145
146 it("distinguishes a cleared rebase blocker from an inconclusive merge check", () => {
147 expect(
148 expectSuccess(
149 decodeMergeRequestDetailJson(detailJson({ detailed_merge_status: "mergeable" })),
150 ).rebaseRequired,
151 ).toBe(false);
152 for (const detailed_merge_status of [undefined, "checking", "ci_still_running"]) {
153 expect(
154 expectSuccess(decodeMergeRequestDetailJson(detailJson({ detailed_merge_status })))
155 .rebaseRequired,
156 ).toBeUndefined();
157 }
158 });
159
160 it("reads the description, file count and pipeline", () => {
161 const detail = expectSuccess(
162 decodeMergeRequestDetailJson(
163 detailJson({
164 description: "Ships the page.",
165 changes_count: "3",
166 reviewers: [{ username: "julius", name: "Julius" }],
167 head_pipeline: {
168 status: "success",
169 web_url: "https://gitlab.com/acme/web/-/pipelines/9",
170 source: "merge_request_event",
171 },
172 }),
173 ),
174 );
175
176 expect(detail.body).toBe("Ships the page.");
177 expect(detail.changedFiles).toBe(3);
178 expect(detail.reviewers).toEqual([{ login: "julius", name: "Julius", avatarUrl: null }]);
179 expect(detail.checks).toEqual([
180 {
181 name: "Pipeline",
182 status: "success",
183 description: "merge_request_event",
184 url: "https://gitlab.com/acme/web/-/pipelines/9",
185 },
186 ]);
187 });
188
189 it.each(["canceled", "canceling"])("maps a %s pipeline to cancelled", (status) => {
190 const detail = expectSuccess(
191 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status } })),
192 );
193
194 expect(detail.checks[0]?.status).toBe("cancelled");
195 });
196
197 it("reads an uncounted change set as its floor", () => {
198 const detail = expectSuccess(
199 decodeMergeRequestDetailJson(detailJson({ changes_count: "1000+" })),
200 );
201
202 expect(detail.changedFiles).toBe(1000);
203 });
204
205 it("reads the head commit, and says nothing where GitLab omitted it", () => {
206 const headSha = (entry: Record<string, unknown>) =>
207 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).headSha;
208 const sha = "afce4da4d5fe7d2fd0647b5b864526ea0a2827cb";
209
210 expect(headSha({ sha })).toBe(sha);
211 expect(headSha({ sha, diff_refs: null })).toBe(sha);
212 expect(headSha({ sha, merge_commit_sha: "0".repeat(40) })).toBe(sha);
213 expect(headSha({})).toBeUndefined();
214 expect(headSha({ sha: null })).toBeUndefined();
215 expect(headSha({ sha: " " })).toBeUndefined();
216 });
217
218 it("reads the diff refs threads are placed against", () => {
219 const diffRefs = (entry: Record<string, unknown>) =>
220 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).diffRefs;
221
222 expect(diffRefs({ diff_refs: { base_sha: "b", start_sha: "s", head_sha: "h" } })).toEqual({
223 baseSha: "b",
224 startSha: "s",
225 headSha: "h",
226 });
227 expect(diffRefs({ diff_refs: null })).toBeUndefined();
228 expect(
229 diffRefs({ diff_refs: { base_sha: null, start_sha: "s", head_sha: "h" } }),
230 ).toBeUndefined();
231 });
232
233 it("reads either auto-merge field, and says nothing where GitLab named neither", () => {
234 const armed = (entry: Record<string, unknown>) =>
235 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).autoMergeEnabled;
236
237 expect(armed({ merge_when_pipeline_succeeds: true })).toBe(true);
238 expect(armed({ auto_merge_enabled: true })).toBe(true);
239 expect(armed({ merge_when_pipeline_succeeds: false })).toBe(false);
240 expect(armed({})).toBeUndefined();
241 });
242
243 it("keeps the squash choice stored with auto-merge", () => {
244 expect(
245 expectSuccess(
246 decodeMergeRequestDetailJson(
247 detailJson({ auto_merge_enabled: true, squash_on_merge: true }),
248 ),
249 ),
250 ).toMatchObject({ autoMergeEnabled: true, autoMergeMethod: "squash" });
251
252 expect(
253 expectSuccess(
254 decodeMergeRequestDetailJson(
255 detailJson({
256 auto_merge_enabled: true,
257 squash: true,
258 squash_on_merge: false,
259 }),
260 ),
261 ).autoMergeMethod,
262 ).toBeUndefined();
263 });
264
265 it("keeps a divergence GitLab did not count apart from a divergence of none", () => {
266 const behind = (entry: Record<string, unknown>) =>
267 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).divergedCommits;
268
269 expect(behind({ diverged_commits_count: 3 })).toBe(3);
270 expect(behind({ diverged_commits_count: 0 })).toBe(0);
271 expect(behind({})).toBeUndefined();
272 expect(behind({ diverged_commits_count: null })).toBeUndefined();
273 });
274
275 it.each(["scheduled", " SCHEDULED "])("keeps a delayed pipeline pending: %s", (status) => {
276 const detail = expectSuccess(
277 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status } })),
278 );
279
280 expect(detail.checks[0]?.status).toBe("pending");
281 });
282
283 it("maps a pipeline waiting on a person to neutral, not failure", () => {
284 const detail = expectSuccess(
285 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status: "manual" } })),
286 );
287
288 expect(detail.checks[0]?.status).toBe("neutral");
289 });
290});
291
292describe("decodePipelineStageChecksJson", () => {
293 function stagesJson(
294 stages: ReadonlyArray<Record<string, unknown> | null> | null,
295 hasNextPage = false,
296 ): string {
297 return JSON.stringify({
298 data: {
299 project: {
300 mergeRequest: {
301 headPipeline:
302 stages === null
303 ? null
304 : {
305 path: "/fork/web/-/pipelines/9",
306 stages: { nodes: stages, pageInfo: { hasNextPage } },
307 },
308 },
309 },
310 },
311 });
312 }
313
314 it("shows every job under its stage", () => {
315 const checks = expectSuccess(
316 decodePipelineStageChecksJson(
317 stagesJson([
318 {
319 name: "build",
320 status: "success",
321 jobs: {
322 nodes: [
323 { name: "compile", status: "FAILED", retried: true, webPath: "/acme/web/-/jobs/1" },
324 {
325 name: "compile",
326 status: "SUCCESS",
327 detailedStatus: { label: "passed" },
328 webPath: "/acme/web/-/jobs/2",
329 },
330 ],
331 },
332 },
333 {
334 name: "test",
335 status: "failed",
336 jobs: {
337 nodes: [
338 {
339 name: "unit",
340 status: "FAILED",
341 allowFailure: false,
342 webPath: "/acme/web/-/jobs/3",
343 },
344 {
345 name: "lint",
346 status: "FAILED",
347 allowFailure: true,
348 webPath: "/acme/web/-/jobs/4",
349 },
350 { name: "slow", status: "CANCELED", webPath: "/acme/web/-/jobs/5" },
351 { name: "e2e", status: "RUNNING", webPath: "/acme/web/-/jobs/6" },
352 ],
353 },
354 },
355 {
356 name: "deploy",
357 status: "manual",
358 jobs: { nodes: [{ name: "release", status: "MANUAL", webPath: "/acme/web/-/jobs/7" }] },
359 },
360 ]),
361 "https://gitlab.example.com",
362 ),
363 );
364
365 expect(checks?.map((check) => [check.name, check.status, check.url])).toEqual([
366 ["build / compile", "success", "https://gitlab.example.com/acme/web/-/jobs/2"],
367 ["test / unit", "failure", "https://gitlab.example.com/acme/web/-/jobs/3"],
368 ["test / lint", "neutral", "https://gitlab.example.com/acme/web/-/jobs/4"],
369 ["test / slow", "cancelled", "https://gitlab.example.com/acme/web/-/jobs/5"],
370 ["test / e2e", "pending", "https://gitlab.example.com/acme/web/-/jobs/6"],
371 ["deploy / release", "neutral", "https://gitlab.example.com/acme/web/-/jobs/7"],
372 ]);
373 expect(checks?.[0]?.description).toBe("passed");
374 });
375
376 it.each([
377 ["no jobs", undefined],
378 ["an empty job list", { nodes: [] }],
379 [
380 "more jobs than one page",
381 { nodes: [{ name: "unit", status: "FAILED" }], pageInfo: { hasNextPage: true } },
382 ],
383 ["a job GitLab could not resolve", { nodes: [{ name: "unit", status: "FAILED" }, null] }],
384 [
385 "a job without a name",
386 {
387 nodes: [
388 { name: "unit", status: "FAILED" },
389 { name: null, status: "FAILED" },
390 ],
391 },
392 ],
393 ])("keeps a stage whole where its jobs come back with %s", (_, jobs) => {
394 expect(
395 expectSuccess(
396 decodePipelineStageChecksJson(
397 stagesJson([
398 {
399 name: "test",
400 status: "failed",
401 detailedStatus: { label: "failed", detailsPath: "/fork/web/-/pipelines/9#test" },
402 ...(jobs === undefined ? {} : { jobs }),
403 },
404 ]),
405 "https://gitlab.com",
406 ),
407 ),
408 ).toEqual([
409 {
410 name: "test",
411 status: "failure",
412 description: "failed",
413 url: "https://gitlab.com/fork/web/-/pipelines/9#test",
414 },
415 ]);
416 });
417
418 it("answers nothing where there are no stages to show", () => {
419 expect(
420 expectSuccess(decodePipelineStageChecksJson(stagesJson(null), "https://gitlab.com")),
421 ).toBe(null);
422 expect(expectSuccess(decodePipelineStageChecksJson(stagesJson([]), "https://gitlab.com"))).toBe(
423 null,
424 );
425 // A stage past the first page could be the failed one.
426 expect(
427 expectSuccess(
428 decodePipelineStageChecksJson(
429 stagesJson([{ name: "build", status: "success" }], true),
430 "https://gitlab.com",
431 ),
432 ),
433 ).toBe(null);
434 // A stage GitLab failed to resolve comes back null beside an error, and could be the failed one.
435 expect(
436 expectSuccess(
437 decodePipelineStageChecksJson(
438 stagesJson([{ name: "build", status: "success" }, null]),
439 "https://gitlab.com",
440 ),
441 ),
442 ).toBe(null);
443 expect(
444 expectSuccess(
445 decodePipelineStageChecksJson(
446 stagesJson([
447 { name: "build", status: "success" },
448 { name: null, status: "failed" },
449 ]),
450 "https://gitlab.com",
451 ),
452 ),
453 ).toBe(null);
454 expect(
455 expectSuccess(
456 decodePipelineStageChecksJson(
457 JSON.stringify({
458 ...JSON.parse(stagesJson([{ name: "build", status: "success" }])),
459 errors: [{ message: "boom" }],
460 }),
461 "https://gitlab.com",
462 ),
463 ),
464 ).toBe(null);
465 // GitLab answers an error it hit with no data at all.
466 expect(
467 expectSuccess(
468 decodePipelineStageChecksJson(
469 JSON.stringify({ errors: [{ message: "boom" }] }),
470 "https://gitlab.com",
471 ),
472 ),
473 ).toBe(null);
474 });
475});
476
477describe("decodeNotesJson", () => {
478 it("keeps comments and drops GitLab's own activity notes", () => {
479 const notes = expectSuccess(
480 decodeNotesJson(
481 JSON.stringify([
482 {
483 id: 1,
484 body: "assigned to @bilal",
485 system: true,
486 created_at: "2026-07-01T00:00:00Z",
487 },
488 {
489 id: 2,
490 body: "Looks good.",
491 author: { username: "julius" },
492 created_at: "2026-07-02T00:00:00Z",
493 },
494 { id: 3, body: " ", created_at: "2026-07-03T00:00:00Z" },
495 ]),
496 ),
497 );
498
499 expect(notes.comments).toHaveLength(1);
500 expect(notes.comments[0]).toMatchObject({
501 id: "2",
502 kind: "issue-comment",
503 body: "Looks good.",
504 });
505 expect(notes.rawCount).toBe(3);
506 });
507
508 it("reads a line note as a review comment on its file", () => {
509 const notes = expectSuccess(
510 decodeNotesJson(
511 JSON.stringify([
512 {
513 id: 7,
514 type: "DiffNote",
515 body: "Rename this.",
516 created_at: "2026-07-02T00:00:00Z",
517 position: { new_path: "src/app.ts", old_path: "src/old.ts" },
518 },
519 ]),
520 ),
521 );
522
523 expect(notes.comments[0]).toMatchObject({ kind: "review-comment", path: "src/app.ts" });
524 });
525
526 it("falls back to the old path for a note on a deleted line", () => {
527 const notes = expectSuccess(
528 decodeNotesJson(
529 JSON.stringify([
530 {
531 id: 8,
532 type: "DiffNote",
533 body: "Gone.",
534 created_at: "2026-07-02T00:00:00Z",
535 position: { new_path: null, old_path: "src/old.ts" },
536 },
537 ]),
538 ),
539 );
540
541 expect(notes.comments[0]?.path).toBe("src/old.ts");
542 });
543});
544
545describe("decodeCommitsJson", () => {
546 it("falls back to the creation timestamp when there is no commit date", () => {
547 const commits = expectSuccess(
548 decodeCommitsJson(
549 JSON.stringify([
550 {
551 id: "aaa",
552 created_at: "2026-07-01T00:00:00+08:00",
553 author_name: "Ada Lovelace",
554 author_email: "ada@example.com",
555 },
556 ]),
557 ),
558 );
559
560 expect(commits[0]).toMatchObject({
561 oid: "aaa",
562 committedDate: "2026-07-01T00:00:00+08:00",
563 authors: [{ login: "Ada Lovelace", name: "Ada Lovelace", avatarUrl: null }],
564 });
565 });
566});
567
568describe("decodeMergeRequestDiffsJson", () => {
569 it("quotes literal backslashes without interpreting them as escapes", () => {
570 const result = expectSuccess(
571 decodeMergeRequestDiffsJson(
572 JSON.stringify([
573 {
574 old_path: String.raw`src\notes.ts`,
575 new_path: String.raw`src\notes.ts`,
576 diff: "@@ -1 +1 @@\n-old\n+new",
577 },
578 ]),
579 ),
580 );
581
582 expect(result.patch).toBe(
583 [
584 String.raw`diff --git "a/src\\notes.ts" "b/src\\notes.ts"`,
585 String.raw`--- "a/src\\notes.ts"`,
586 String.raw`+++ "b/src\\notes.ts"`,
587 "@@ -1 +1 @@",
588 "-old",
589 "+new",
590 "",
591 ].join("\n"),
592 );
593 });
594
595 it("preserves spaces and literal backslashes in both rename paths", () => {
596 const result = expectSuccess(
597 decodeMergeRequestDiffsJson(
598 JSON.stringify([
599 {
600 old_path: String.raw` old\name.ts `,
601 new_path: String.raw` new\name.ts `,
602 renamed_file: true,
603 diff: "",
604 },
605 ]),
606 ),
607 );
608
609 expect(result.patch).toBe(
610 [
611 String.raw`diff --git "a/ old\\name.ts " "b/ new\\name.ts "`,
612 "similarity index 100%",
613 String.raw`rename from " old\\name.ts "`,
614 String.raw`rename to " new\\name.ts "`,
615 String.raw`--- "a/ old\\name.ts "`,
616 String.raw`+++ "b/ new\\name.ts "`,
617 ].join("\n"),
618 );
619 });
620
621 it("assembles a unified patch GitLab does not return", () => {
622 const result = expectSuccess(
623 decodeMergeRequestDiffsJson(
624 JSON.stringify([
625 {
626 old_path: "src/app.ts",
627 new_path: "src/app.ts",
628 diff: "@@ -1 +1 @@\n-old\n+new\n",
629 },
630 ]),
631 ),
632 );
633
634 expect(result.patch).toBe(
635 [
636 "diff --git a/src/app.ts b/src/app.ts",
637 "--- a/src/app.ts",
638 "+++ b/src/app.ts",
639 "@@ -1 +1 @@",
640 "-old",
641 "+new",
642 "",
643 ].join("\n"),
644 );
645 expect(result.truncated).toBe(false);
646 });
647
648 it("points a new file at /dev/null on the left and a deleted file on the right", () => {
649 const result = expectSuccess(
650 decodeMergeRequestDiffsJson(
651 JSON.stringify([
652 {
653 old_path: "src/new.ts",
654 new_path: "src/new.ts",
655 new_file: true,
656 b_mode: "100755",
657 diff: "@@ -0,0 +1 @@\n+hello\n",
658 },
659 {
660 old_path: "src/gone.ts",
661 new_path: "src/gone.ts",
662 deleted_file: true,
663 diff: "@@ -1 +0,0 @@\n-bye\n",
664 },
665 ]),
666 ),
667 );
668
669 expect(result.patch).toContain("new file mode 100755");
670 expect(result.patch).toContain("--- /dev/null");
671 expect(result.patch).toContain("deleted file mode 100644");
672 expect(result.patch).toContain("+++ /dev/null");
673 });
674
675 it("reports truncation for a file GitLab refused to inline", () => {
676 const result = expectSuccess(
677 decodeMergeRequestDiffsJson(
678 JSON.stringify([{ old_path: "big.bin", new_path: "big.bin", diff: "", too_large: true }]),
679 ),
680 );
681
682 expect(result.truncated).toBe(true);
683 expect(result.patch).toContain("diff --git a/big.bin b/big.bin");
684 });
685
686 it("reports how many files GitLab returned, so the caller can page", () => {
687 const result = expectSuccess(
688 decodeMergeRequestDiffsJson(
689 JSON.stringify(
690 Array.from({ length: 3 }, (_, index) => ({
691 old_path: `src/${index}.ts`,
692 new_path: `src/${index}.ts`,
693 diff: "@@ -1 +1 @@\n-a\n+b\n",
694 })),
695 ),
696 ),
697 );
698
699 expect(result.rawCount).toBe(3);
700 expect(result.truncated).toBe(false);
701 expect(result.patch).toContain("src/2.ts");
702 });
703});
704
705describe("decodeTriggerJobChecksJson", () => {
706 it("reads a downstream failure GitLab was told to allow as neutral, not failure", () => {
707 const result = expectSuccess(
708 decodeTriggerJobChecksJson(
709 JSON.stringify([
710 { name: "e2e", allow_failure: true, downstream_pipeline: { status: "failed" } },
711 { name: "deploy", allow_failure: false, downstream_pipeline: { status: "running" } },
712 { name: 7 },
713 ]),
714 ),
715 );
716
717 expect(result.checks.map((check) => [check.name, check.status])).toEqual([
718 ["e2e", "neutral"],
719 ["deploy", "pending"],
720 ]);
721 expect(result.rawCount).toBe(3);
722 });
723});
724
725describe("merge request viewer fields", () => {
726 it("leaves merging permitted where GitLab answered without the field", () => {
727 expect(expectSuccess(decodeMergeRequestDetailJson(detailJson({}))).viewerCanMerge).toBe(true);
728 expect(
729 expectSuccess(decodeMergeRequestDetailJson(detailJson({ user: null }))).viewerCanMerge,
730 ).toBe(true);
731 });
732});
733
734describe("decodeAwardEmojiJson", () => {
735 it("reads MR-level awards, keys per-note awards by the REST id inside their gid, ignores an award outside the eight, and collects bot note authors", () => {
736 const result = expectSuccess(
737 decodeAwardEmojiJson(
738 JSON.stringify({
739 data: {
740 currentUser: { username: "bilal" },
741 project: {
742 mergeRequest: {
743 awardEmoji: {
744 nodes: [
745 { name: "thumbsup", user: { username: "bilal" } },
746 { name: "thumbsup", user: { username: "julius" } },
747 ],
748 },
749 notes: {
750 pageInfo: { hasNextPage: false, endCursor: null },
751 nodes: [
752 {
753 id: "gid://gitlab/DiffNote/42",
754 author: { username: "julius", bot: false },
755 awardEmoji: { nodes: [{ name: "heart", user: { username: "julius" } }] },
756 },
757 {
758 id: "gid://gitlab/Note/7",
759 author: { username: "project_278964_bot_89f97e2c", bot: true },
760 awardEmoji: {
761 nodes: [{ name: "partyparrot", user: { username: "bilal" } }],
762 },
763 },
764 ],
765 },
766 },
767 },
768 },
769 }),
770 ),
771 );
772
773 expect(result.reactions).toEqual([
774 { content: "thumbs-up", count: 2, actors: ["julius"], viewerHasReacted: true },
775 ]);
776 expect([...result.reactionsByNoteId]).toEqual([
777 ["42", [{ content: "heart", count: 1, actors: ["julius"], viewerHasReacted: false }]],
778 ]);
779 expect([...result.botLogins]).toEqual(["project_278964_bot_89f97e2c"]);
780 expect(result.nextCursor).toBeNull();
781 });
782
783 it("dates a note's edit only when someone edited its text, not when its thread was resolved", () => {
784 const result = expectSuccess(
785 decodeAwardEmojiJson(
786 JSON.stringify({
787 data: {
788 currentUser: { username: "bilal" },
789 project: {
790 mergeRequest: {
791 awardEmoji: { nodes: [] },
792 notes: {
793 pageInfo: { hasNextPage: false, endCursor: null },
794 nodes: [
795 {
796 id: "gid://gitlab/Note/1",
797 lastEditedAt: "2026-07-02T00:00:00Z",
798 lastEditedBy: { username: "julius" },
799 resolved: false,
800 },
801 {
802 id: "gid://gitlab/Note/2",
803 lastEditedAt: "2026-07-01T00:00:00Z",
804 lastEditedBy: null,
805 resolved: false,
806 },
807 {
808 id: "gid://gitlab/DiscussionNote/3",
809 lastEditedAt: "2026-07-03T00:00:00Z",
810 lastEditedBy: { username: "julius" },
811 resolved: true,
812 },
813 ],
814 },
815 },
816 },
817 },
818 }),
819 ),
820 );
821
822 expect([...result.editedAtByNoteId]).toEqual([["1", "2026-07-02T00:00:00Z"]]);
823 });
824
825 it("matches the viewer's username case-insensitively, since GitLab is not consistent about case", () => {
826 const result = expectSuccess(
827 decodeAwardEmojiJson(
828 JSON.stringify({
829 data: {
830 currentUser: { username: "Bilal" },
831 project: {
832 mergeRequest: {
833 awardEmoji: {
834 nodes: [
835 { name: "heart", user: { username: "bilal" } },
836 { name: "heart", user: { username: "julius" } },
837 ],
838 },
839 notes: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] },
840 },
841 },
842 },
843 }),
844 ),
845 );
846
847 expect(result.reactions).toEqual([
848 { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
849 ]);
850 });
851});
852
853describe("decodeOwnAwardIdJson", () => {
854 const awards = JSON.stringify([
855 { id: 101, name: "thumbsup", user: { username: "julius" } },
856 { id: 102, name: "thumbsup", user: { username: "bilal" } },
857 ]);
858
859 it("finds the reader's own award of that name, which is the one a removal deletes", () => {
860 expect(
861 expectSuccess(decodeOwnAwardIdJson(awards, { content: "thumbs-up", viewer: "bilal" })),
862 ).toEqual({ id: 102, empty: false });
863 });
864});
865
866describe("decodeRepositoryBlobsJson", () => {
867 function expectBlobs(result: Result.Result<ReadonlyMap<string, string> | null, unknown>) {
868 const blobs = expectSuccess(result);
869 expect(blobs).not.toBe(null);
870 if (blobs === null) throw new Error("expected an answered blobs query");
871 return blobs;
872 }
873
874 it("leaves out a node missing either half, which names no version", () => {
875 const blobs = expectBlobs(
876 decodeRepositoryBlobsJson(
877 JSON.stringify({
878 data: {
879 project: {
880 repository: {
881 blobs: {
882 nodes: [
883 { path: "src/a.ts", oid: null },
884 { path: null, oid: "bbb222" },
885 null,
886 { path: "src/c.ts", oid: "ccc333" },
887 ],
888 },
889 },
890 },
891 },
892 }),
893 ),
894 );
895
896 expect([...blobs]).toEqual([["src/c.ts", "ccc333"]]);
897 });
898
899 it("keys a blob by the path the host spelled, spaces and all", () => {
900 const blobs = expectBlobs(
901 decodeRepositoryBlobsJson(
902 JSON.stringify({
903 data: {
904 project: {
905 repository: {
906 blobs: {
907 nodes: [
908 { path: " leading.ts", oid: "aaa111" },
909 { path: "trailing.ts ", oid: "bbb222" },
910 { path: " ", oid: "ccc333" },
911 { path: "", oid: "ddd444" },
912 ],
913 },
914 },
915 },
916 },
917 }),
918 ),
919 );
920
921 expect([...blobs]).toEqual([
922 [" leading.ts", "aaa111"],
923 ["trailing.ts ", "bbb222"],
924 [" ", "ccc333"],
925 ]);
926 });
927
928 it("tells a project the reader cannot see from a revision with none of the files", () => {
929 expect(
930 expectSuccess(decodeRepositoryBlobsJson(JSON.stringify({ data: { project: null } }))),
931 ).toBe(null);
932 expect(
933 expectSuccess(
934 decodeRepositoryBlobsJson(JSON.stringify({ data: { project: { repository: null } } })),
935 ),
936 ).toBe(null);
937 expect(
938 expectSuccess(
939 decodeRepositoryBlobsJson(
940 JSON.stringify({ data: { project: { repository: { blobs: { nodes: [] } } } } }),
941 ),
942 ),
943 ).toEqual(new Map());
944 });
945});
946
947describe("decodeListStatesJson", () => {
948 const statesOf = (enterprise: boolean | null, nodes: ReadonlyArray<unknown>) =>
949 expectSuccess(
950 decodeListStatesJson(
951 JSON.stringify({
952 data: {
953 metadata: enterprise === null ? null : { enterprise },
954 project: { mergeRequests: { nodes } },
955 },
956 }),
957 ),
958 );
959 const approvedBy = (...usernames: ReadonlyArray<string>) => ({
960 nodes: usernames.map((username) => ({ username })),
961 });
962 const reviewers = (...reviewStates: ReadonlyArray<string>) => ({
963 nodes: reviewStates.map((reviewState) => ({ mergeRequestInteraction: { reviewState } })),
964 });
965
966 it.each([
967 {
968 reading: "an approval short of Enterprise approval rules",
969 enterprise: true,
970 approval: { approved: false, approvedBy: approvedBy("GitLabDuo") },
971 decision: "review-required",
972 },
973 {
974 reading: "Enterprise approval rules no one has approved against",
975 enterprise: true,
976 approval: { approved: false, approvedBy: approvedBy() },
977 decision: "review-required",
978 },
979 {
980 reading: "Enterprise approval rules met",
981 enterprise: true,
982 approval: { approved: true, approvedBy: approvedBy("julius") },
983 decision: "approved",
984 },
985 {
986 reading: "Enterprise without approval rules or approvals",
987 enterprise: true,
988 approval: { approved: true, approvedBy: approvedBy() },
989 decision: null,
990 },
991 {
992 reading: "Community Edition with an approval",
993 enterprise: false,
994 approval: { approved: true, approvedBy: approvedBy("julius") },
995 decision: "approved",
996 },
997 {
998 reading: "Community Edition without approvals",
999 enterprise: false,
1000 approval: { approved: false, approvedBy: approvedBy() },
1001 decision: null,
1002 },
1003 {
1004 reading: "a reviewer requesting changes after another approved",
1005 enterprise: true,
1006 approval: {
1007 approved: true,
1008 approvedBy: approvedBy("julius"),
1009 reviewers: reviewers("APPROVED", "REQUESTED_CHANGES"),
1010 },
1011 decision: "changes-requested",
1012 },
1013 {
1014 reading: "a Community Edition reviewer requesting changes",
1015 enterprise: false,
1016 approval: {
1017 approved: false,
1018 approvedBy: approvedBy(),
1019 reviewers: reviewers("REQUESTED_CHANGES"),
1020 },
1021 decision: "changes-requested",
1022 },
1023 {
1024 reading: "reviewers who have not asked for changes",
1025 enterprise: false,
1026 approval: {
1027 approved: true,
1028 approvedBy: approvedBy("julius"),
1029 reviewers: reviewers("UNREVIEWED", "REVIEWED"),
1030 },
1031 decision: "approved",
1032 },
1033 ])("reads $reading as $decision", ({ enterprise, approval, decision }) => {
1034 expect([...statesOf(enterprise, [{ iid: "7", ...approval }])]).toEqual([
1035 [7, { reviewDecision: decision, checksState: null }],
1036 ]);
1037 });
1038
1039 it.each([
1040 { pipeline: { status: "SUCCESS" }, checksState: "passing" },
1041 { pipeline: { status: "FAILED" }, checksState: "failing" },
1042 { pipeline: { status: "CANCELED" }, checksState: "failing" },
1043 { pipeline: { status: "RUNNING" }, checksState: "pending" },
1044 { pipeline: { status: "WAITING_FOR_RESOURCE" }, checksState: "pending" },
1045 { pipeline: { status: "MANUAL" }, checksState: null },
1046 { pipeline: { status: "SKIPPED" }, checksState: null },
1047 { pipeline: null, checksState: null },
1048 ])(
1049 "reads a $pipeline.status head pipeline as $checksState checks",
1050 ({ pipeline, checksState }) => {
1051 expect([
1052 ...statesOf(false, [
1053 { iid: "7", approved: false, approvedBy: approvedBy(), headPipeline: pipeline },
1054 ]),
1055 ]).toEqual([[7, { reviewDecision: null, checksState }]]);
1056 },
1057 );
1058
1059 it("leaves out a merge request it cannot key, and a project the reader cannot see", () => {
1060 expect([...statesOf(true, [null, { iid: "x", approved: true }])]).toEqual([]);
1061 expect(
1062 expectSuccess(decodeListStatesJson(JSON.stringify({ data: { project: null } }))),
1063 ).toEqual(new Map());
1064 });
1065
1066 it("keeps the checks of a merge request whose approval it cannot judge", () => {
1067 expect([
1068 ...statesOf(null, [
1069 {
1070 iid: "7",
1071 approved: false,
1072 approvedBy: approvedBy(),
1073 headPipeline: { status: "FAILED" },
1074 },
1075 ]),
1076 ...statesOf(true, [
1077 { iid: "8", approved: null, approvedBy: approvedBy("julius") },
1078 { iid: "9", approved: true, approvedBy: null },
1079 ]),
1080 ]).toEqual([
1081 [7, { checksState: "failing" }],
1082 [8, { checksState: null }],
1083 [9, { checksState: null }],
1084 ]);
1085 });
1086});
1087
1088describe("decodeReferenceCandidatesJson", () => {
1089 it("prefixes merge requests with ! and skips malformed entries", () => {
1090 const raw = JSON.stringify([
1091 { iid: 5, title: "Ship it", state: "merged" },
1092 { iid: 6, title: "Draft", state: "opened" },
1093 { iid: 7, title: "Locked", state: "locked" },
1094 { title: "No iid", state: "opened" },
1095 ]);
1096 const decoded = decodeReferenceCandidatesJson(raw, "change-request");
1097 expect(Result.isSuccess(decoded) && decoded.success).toEqual({
1098 items: [
1099 { reference: "!5", kind: "change-request", number: 5, title: "Ship it", state: "merged" },
1100 { reference: "!6", kind: "change-request", number: 6, title: "Draft", state: "open" },
1101 { reference: "!7", kind: "change-request", number: 7, title: "Locked", state: "closed" },
1102 ],
1103 rawCount: 4,
1104 });
1105 const issues = decodeReferenceCandidatesJson(raw, "issue");
1106 expect(Result.isSuccess(issues) && issues.success.items[0]?.reference).toBe("#5");
1107 });
1108});
1109
1110describe("decodeMergeRequestStatsJson", () => {
1111 it("keys the counts by merge request number", () => {
1112 const stats = expectSuccess(
1113 decodeMergeRequestStatsJson(
1114 JSON.stringify({
1115 data: {
1116 project: {
1117 mergeRequests: {
1118 nodes: [
1119 { iid: "7", diffStatsSummary: { additions: 12, deletions: 3 } },
1120 { iid: "8", diffStatsSummary: null },
1121 ],
1122 },
1123 },
1124 },
1125 }),
1126 ),
1127 );
1128
1129 // A merge request without a summary is left out rather than shown as zero lines changed.
1130 expect([...stats]).toEqual([[7, { additions: 12, deletions: 3 }]]);
1131 });
1132
1133 it("answers nothing for a project the token cannot see", () => {
1134 const stats = expectSuccess(
1135 decodeMergeRequestStatsJson(JSON.stringify({ data: { project: null } })),
1136 );
1137
1138 expect(stats.size).toBe(0);
1139 });
1140
1141 it("reports a file list shorter than the summary as truncated", () => {
1142 const read = (fileCount: number) =>
1143 expectSuccess(
1144 decodeMergeRequestFileStatsJson(
1145 JSON.stringify({
1146 data: {
1147 project: {
1148 mergeRequest: {
1149 diffStatsSummary: { fileCount },
1150 diffStats: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
1151 },
1152 },
1153 },
1154 }),
1155 ),
1156 );
1157
1158 expect(read(1)).toEqual({
1159 files: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
1160 truncated: false,
1161 });
1162 expect(read(2).truncated).toBe(true);
1163 });
1164});
1165
1166describe("decodeMergeRequestGraphqlListJson", () => {
1167 it("reads a row and its review state in one page, counting rows it cannot read", () => {
1168 const page = expectSuccess(
1169 decodeMergeRequestGraphqlListJson(
1170 JSON.stringify({
1171 data: {
1172 metadata: { enterprise: false },
1173 project: {
1174 mergeRequests: {
1175 pageInfo: { hasNextPage: true, endCursor: "eyJpZCI6IjcifQ" },
1176 nodes: [
1177 {
1178 iid: "7",
1179 title: "Add the merge requests page",
1180 webUrl: "https://gitlab.com/acme/web/-/merge_requests/7",
1181 state: "opened",
1182 draft: true,
1183 createdAt: "2026-07-01T00:00:00Z",
1184 updatedAt: "2026-07-02T00:00:00Z",
1185 sourceBranch: "feat/page",
1186 targetBranch: "main",
1187 conflicts: true,
1188 mergeStatusEnum: "CHECKING",
1189 author: { username: "bilal", name: "Bilal", avatarUrl: null },
1190 labels: { nodes: [{ title: "bug" }] },
1191 approved: false,
1192 approvedBy: { nodes: [] },
1193 reviewers: {
1194 nodes: [
1195 {
1196 username: "julius",
1197 mergeRequestInteraction: { reviewState: "REQUESTED_CHANGES" },
1198 },
1199 ],
1200 },
1201 headPipeline: { status: "FAILED" },
1202 },
1203 { iid: "8" },
1204 ],
1205 },
1206 },
1207 },
1208 }),
1209 ),
1210 );
1211
1212 expect(page.items).toEqual([
1213 expect.objectContaining({
1214 number: 7,
1215 state: "open",
1216 isDraft: true,
1217 mergeability: "conflicting",
1218 reviewRequestLogins: ["julius"],
1219 labels: [expect.objectContaining({ name: "bug" })],
1220 }),
1221 ]);
1222 expect([...page.states]).toEqual([
1223 [7, { reviewDecision: "changes-requested", checksState: "failing" }],
1224 ]);
1225 expect(page).toMatchObject({ rawCount: 2, hasNextPage: true, endCursor: "eyJpZCI6IjcifQ" });
1226 });
1227 it("fails on a project the reader cannot see, rather than reading it as empty", () => {
1228 expect(
1229 Result.isFailure(
1230 decodeMergeRequestGraphqlListJson(
1231 JSON.stringify({ data: { metadata: { enterprise: true }, project: null } }),
1232 ),
1233 ),
1234 ).toBe(true);
1235 });
1236});
1237
1238describe("decodeGraphqlListSupportJson", () => {
1239 it.each([
1240 { version: "17.8.4", supported: false },
1241 { version: "17.9.0", supported: true },
1242 { version: "19.6.0-pre", supported: true },
1243 { version: null, supported: false },
1244 ])("reads GitLab $version as supported: $supported", ({ version, supported }) => {
1245 expect(
1246 expectSuccess(
1247 decodeGraphqlListSupportJson(JSON.stringify({ data: { metadata: { version } } })),
1248 ),
1249 ).toBe(supported);
1250 });
1251});
1252
1253describe("decodeMergeMessagesJson", () => {
1254 it("fails a partial response instead of reading errored fields as absent templates", () => {
1255 const decoded = decodeMergeMessagesJson(
1256 JSON.stringify({
1257 errors: [{ message: "Internal server error", path: ["project", "mergeRequest"] }],
1258 data: {
1259 project: { mergeRequest: { title: "Add thing", defaultMergeCommitMessage: null } },
1260 },
1261 }),
1262 );
1263
1264 expect(Result.isFailure(decoded)).toBe(true);
1265 });
1266});
1267
1268describe("decodeMergeRequestWatchFingerprintJson", () => {
1269 const pipeline = (status: string, downstream: string, failed = 0, moreBridges = false) => ({
1270 id: "gid://gitlab/Ci::Pipeline/9",
1271 status,
1272 succeeded: { count: 3 },
1273 failed: { count: failed },
1274 stopped: { count: 0 },
1275 jobs: {
1276 pageInfo: { hasNextPage: moreBridges },
1277 nodes: [
1278 {
1279 name: "deploy",
1280 status,
1281 downstreamPipeline: { id: "gid://gitlab/Ci::Pipeline/10", status: downstream },
1282 },
1283 ],
1284 },
1285 });
1286 const edit = (at: string, resolved = false) => ({
1287 lastEditedAt: at,
1288 lastEditedBy: { username: "reviewer" },
1289 resolved,
1290 });
1291 const read = (overrides: Record<string, unknown>) =>
1292 expectSuccess(
1293 decodeMergeRequestWatchFingerprintJson(
1294 JSON.stringify({
1295 data: {
1296 project: {
1297 mergeRequest: {
1298 state: "opened",
1299 mergeStatusEnum: "CAN_BE_MERGED",
1300 detailedMergeStatus: "MERGEABLE",
1301 conflicts: false,
1302 diffHeadSha: "a".repeat(40),
1303 userPermissions: { updateMergeRequest: true },
1304 headPipeline: pipeline("RUNNING", "RUNNING"),
1305 userNotesCount: 2,
1306 notes: {
1307 nodes: [
1308 edit("2026-07-02T00:00:00Z"),
1309 { lastEditedAt: null, lastEditedBy: null, resolved: null },
1310 edit("2026-07-01T00:00:00Z"),
1311 ],
1312 },
1313 ...overrides,
1314 },
1315 },
1316 },
1317 }),
1318 ),
1319 );
1320
1321 // A remarks change makes the watch reread every comment, so pipeline progress must not touch it.
1322 it("moves pipeline progress into status and comment edits into remarks", () => {
1323 const base = read({});
1324 const passed = read({ headPipeline: pipeline("SUCCESS", "RUNNING") });
1325 const downstreamPassed = read({ headPipeline: pipeline("SUCCESS", "SUCCESS") });
1326 const jobFailed = read({ headPipeline: pipeline("RUNNING", "RUNNING", 1) });
1327 const edited = read({ notes: { nodes: [edit("2026-07-03T00:00:00Z")] } });
1328 // Resolving a thread restamps its notes without an edit, so it must not reread comments.
1329 const resolved = read({
1330 notes: { nodes: [edit("2026-07-02T00:00:00Z"), edit("2026-07-03T00:00:00Z", true)] },
1331 });
1332
1333 expect(base?.remarks).toBe("2 2026-07-02T00:00:00Z");
1334 expect(passed?.status).not.toBe(base?.status);
1335 expect(downstreamPassed?.status).not.toBe(passed?.status);
1336 expect(jobFailed?.status).not.toBe(base?.status);
1337 expect(passed?.remarks).toBe(base?.remarks);
1338 expect(edited?.status).toBe(base?.status);
1339 expect(edited?.remarks).not.toBe(base?.remarks);
1340 expect(resolved?.remarks).toBe(base?.remarks);
1341 expect(read({ userNotesCount: 3 })?.remarks).not.toBe(base?.remarks);
1342 // A target branch moving on leaves merge_status at can_be_merged on fast-forward projects.
1343 expect(read({ detailedMergeStatus: "NEED_REBASE" })?.status).not.toBe(base?.status);
1344 });
1345
1346 // Only the REST read asks GitLab to recheck mergeability, and only for viewers who can update.
1347 it("covers the detail read once merge status has settled or no read could settle it", () => {
1348 expect(read({})?.coversDetail).toBe(true);
1349 // A capped job count or a second bridge page can hide a job settling.
1350 expect(read({ headPipeline: pipeline("RUNNING", "RUNNING", 1001) })?.coversDetail).toBe(false);
1351 expect(read({ headPipeline: pipeline("RUNNING", "RUNNING", 0, true) })?.coversDetail).toBe(
1352 false,
1353 );
1354 expect(read({ mergeStatusEnum: "UNCHECKED" })?.coversDetail).toBe(false);
1355 expect(read({ mergeStatusEnum: "CHECKING", conflicts: true })?.coversDetail).toBe(true);
1356 expect(
1357 read({ mergeStatusEnum: "UNCHECKED", userPermissions: { updateMergeRequest: false } })
1358 ?.coversDetail,
1359 ).toBe(true);
1360 });
1361
1362 it("answers null when GitLab returned no merge request", () => {
1363 expect(
1364 expectSuccess(
1365 decodeMergeRequestWatchFingerprintJson(
1366 JSON.stringify({ data: { project: { mergeRequest: null } } }),
1367 ),
1368 ),
1369 ).toBeNull();
1370 });
1371});