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