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