Open History to see the last commit
1import { afterEach, assert, expect, it, vi } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4
5import * as BitbucketApi from "./BitbucketApi.ts";
6import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
7
8const mockedRequest = vi.fn<BitbucketApi.BitbucketApi["Service"]["request"]>();
9
10const layer = it.layer(
11 BitbucketPullRequestApi.layer.pipe(
12 Layer.provide(
13 Layer.mock(BitbucketApi.BitbucketApi)({
14 request: mockedRequest,
15 }),
16 ),
17 ),
18);
19
20function response(body: string) {
21 return { body, truncated: false };
22}
23
24function page(count: number, firstNumber: number, next?: string): string {
25 return JSON.stringify({
26 pagelen: 50,
27 size: count,
28 values: Array.from({ length: count }, (_, index) => ({
29 id: firstNumber + index,
30 title: `Pull request ${firstNumber + index}`,
31 state: "OPEN",
32 created_on: "2026-06-16T05:04:32+00:00",
33 updated_on: "2026-06-16T05:04:33+00:00",
34 source: { branch: { name: "feat/page" } },
35 destination: { branch: { name: "master" } },
36 links: { html: { href: `https://bitbucket.org/acme/web/pull-requests/${firstNumber}` } },
37 })),
38 ...(next === undefined ? {} : { next }),
39 });
40}
41
42function valuePage(values: ReadonlyArray<unknown>, next?: string): string {
43 return JSON.stringify({ values, ...(next === undefined ? {} : { next }) });
44}
45
46const bilal = { uuid: "{bilal}", nickname: "bilal" };
47const octocat = { uuid: "{octocat}", nickname: "octocat" };
48const hubot = { uuid: "{hubot}", nickname: "hubot" };
49
50function pullRequestJson(overrides: Record<string, unknown>): string {
51 return JSON.stringify({
52 id: 7,
53 title: "Pull request 7",
54 state: "OPEN",
55 author: bilal,
56 created_on: "2026-06-16T05:04:32+00:00",
57 updated_on: "2026-06-16T05:04:33+00:00",
58 source: { branch: { name: "feat/page" } },
59 destination: { branch: { name: "master" } },
60 links: { html: { href: "https://bitbucket.org/acme/web/pull-requests/7" } },
61 ...overrides,
62 });
63}
64
65function callAt(index: number) {
66 const call = mockedRequest.mock.calls[index];
67 assert.isDefined(call);
68 return call[0];
69}
70
71function filterOfCall(index: number): string | null {
72 const url = callAt(index).url;
73 return new URLSearchParams(url.slice(url.indexOf("?") + 1)).get("q");
74}
75
76afterEach(() => {
77 mockedRequest.mockReset();
78});
79
80layer("BitbucketPullRequestApi.layer", (it) => {
81 it.effect("follows the cursor Bitbucket sends rather than counting offsets", () =>
82 Effect.gen(function* () {
83 const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
84 mockedRequest
85 .mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))))
86 .mockReturnValueOnce(Effect.succeed(response(page(50, 51))));
87 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
88
89 const batch = yield* api.listPullRequests({
90 repository: "acme/web",
91 state: "open",
92 limit: 100,
93 });
94
95 assert.strictEqual(batch.items.length, 100);
96 assert.isFalse(batch.truncated);
97 assert.strictEqual(callAt(1).url, next);
98 }),
99 );
100
101 it.effect("counts the rows it walked past as more to come", () =>
102 Effect.gen(function* () {
103 // Bitbucket pages in fifties whatever was asked for, so a request for ninety-nine reads a
104 // hundred and drops one.
105 const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
106 mockedRequest
107 .mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))))
108 .mockReturnValueOnce(Effect.succeed(response(page(50, 51))));
109 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
110
111 const batch = yield* api.listPullRequests({
112 repository: "acme/web",
113 state: "open",
114 limit: 99,
115 });
116
117 assert.strictEqual(batch.items.length, 99);
118 assert.isTrue(batch.truncated);
119 }),
120 );
121
122 it.effect("escapes a quote and a backslash, so a search cannot reshape the filter", () =>
123 Effect.gen(function* () {
124 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
125 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
126
127 yield* api.listPullRequests({
128 repository: "acme/web",
129 state: "open",
130 limit: 50,
131 query: String.raw`a\" OR state = "MERGED"`,
132 });
133
134 const literal = String.raw`a\\\" OR state = \"MERGED\"`;
135 expect(filterOfCall(0)).toBe(`(title ~ "${literal}" OR description ~ "${literal}")`);
136 }),
137 );
138
139 it.effect("narrows by the reader's words and by where it left off at once", () =>
140 Effect.gen(function* () {
141 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
142 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
143
144 yield* api.listPullRequests({
145 repository: "acme/web",
146 state: "open",
147 limit: 50,
148 query: "page",
149 cursor: { updatedBefore: "2026-07-02T00:00:00+00:00", delivered: 50 },
150 });
151
152 // Bitbucket takes one `q`, so the two narrowings are joined rather than one replacing the
153 // other — and the search keeps its brackets, which is what keeps the AND out of its OR.
154 expect(filterOfCall(0)).toBe(
155 '(title ~ "page" OR description ~ "page") AND updated_on <= 2026-07-02T00:00:00+00:00',
156 );
157 }),
158 );
159
160 it.effect("narrows by author and draft state in the same query", () =>
161 Effect.gen(function* () {
162 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
163 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
164
165 yield* api.listPullRequests({
166 repository: "acme/web",
167 state: "open",
168 limit: 50,
169 author: 'ana"',
170 draft: false,
171 });
172
173 expect(filterOfCall(0)).toBe(
174 '(author.nickname = "ana\\"" OR author.display_name = "ana\\"") AND draft = false',
175 );
176 }),
177 );
178
179 it.effect("refuses a repository that is not workspace and slug", () =>
180 Effect.gen(function* () {
181 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
182
183 const error = yield* Effect.flip(
184 api.listPullRequests({ repository: "acme/team/web", state: "open", limit: 50 }),
185 );
186
187 assert.strictEqual(error._tag, "BitbucketRepositoryUnsupportedError");
188 assert.strictEqual(mockedRequest.mock.calls.length, 0);
189 }),
190 );
191
192 it.effect("refuses a commit that is not a sha rather than reading it into a URL", () =>
193 Effect.gen(function* () {
194 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
195
196 const error = yield* Effect.flip(
197 api.getPullRequestDiff({
198 repository: "acme/web",
199 number: 7,
200 commit: "../../acme/other/diff/deadbeef",
201 }),
202 );
203
204 assert.strictEqual(error._tag, "BitbucketDiffCommitError");
205 assert.strictEqual(mockedRequest.mock.calls.length, 0);
206 }),
207 );
208
209 it.effect("reads every file version the patch states, not only the paths asked about", () =>
210 Effect.gen(function* () {
211 mockedRequest.mockReturnValueOnce(
212 Effect.succeed(
213 response(
214 [
215 "diff --git a/a.ts b/a.ts",
216 "index 1111111..2222222 100644",
217 "--- a/a.ts",
218 "+++ b/a.ts",
219 "@@ -1 +1 @@",
220 "-a",
221 "+b",
222 "diff --git a/b.ts b/b.ts",
223 "index 3333333..4444444 100644",
224 "--- a/b.ts",
225 "+++ b/b.ts",
226 "@@ -1 +1 @@",
227 "-c",
228 "+d",
229 "",
230 ].join("\n"),
231 ),
232 ),
233 );
234 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
235
236 const revisions = yield* api.getFileRevisions({
237 repository: "acme/web",
238 number: 71,
239 paths: ["a.ts", "missing.ts"],
240 });
241
242 assert.deepStrictEqual(
243 [...revisions.revisions],
244 [
245 ["a.ts", "2222222"],
246 ["b.ts", "4444444"],
247 ["missing.ts", ""],
248 ],
249 );
250 assert.strictEqual(revisions.complete, true);
251 expect(callAt(0)).toMatchObject({ url: "/repositories/acme/web/pullrequests/71/diff" });
252 }),
253 );
254
255 it.effect("says nothing about the files past the end of a patch it could not read whole", () =>
256 Effect.gen(function* () {
257 mockedRequest.mockReturnValueOnce(
258 Effect.succeed({
259 body: "diff --git a/a.ts b/a.ts\nindex 1111111..2222222 100644\n@@ -1 +1 @@\n",
260 truncated: true,
261 }),
262 );
263 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
264
265 const revisions = yield* api.getFileRevisions({
266 repository: "acme/web",
267 number: 72,
268 paths: ["a.ts", "past-the-cut.ts"],
269 });
270
271 assert.deepStrictEqual([...revisions.revisions], [["a.ts", "2222222"]]);
272 assert.strictEqual(revisions.complete, false);
273 }),
274 );
275
276 it.effect("returns the complete commit timeline oldest first across pages", () =>
277 Effect.gen(function* () {
278 const next = "https://api.bitbucket.org/2.0/commits?page=2";
279 mockedRequest
280 .mockReturnValueOnce(
281 Effect.succeed(
282 response(
283 valuePage(
284 [
285 { hash: "ddd", message: "fourth", date: "2026-07-04T00:00:00Z" },
286 { hash: "ccc", message: "third", date: "2026-07-03T00:00:00Z" },
287 ],
288 next,
289 ),
290 ),
291 ),
292 )
293 .mockReturnValueOnce(
294 Effect.succeed(
295 response(
296 valuePage([
297 { hash: "bbb", message: "second", date: "2026-07-02T00:00:00Z" },
298 { hash: "aaa", message: "first", date: "2026-07-01T00:00:00Z" },
299 ]),
300 ),
301 ),
302 );
303 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
304
305 const commits = yield* api.listCommits({ repository: "acme/web", number: 7 });
306
307 expect(commits.map((commit) => commit.oid)).toEqual(["aaa", "bbb", "ccc", "ddd"]);
308 expect(callAt(1).url).toBe(next);
309 }),
310 );
311
312 it.effect("posts a comment as a JSON document, so the body stays text", () =>
313 Effect.gen(function* () {
314 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
315 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
316
317 yield* api.comment({ repository: "acme/web", number: 7, body: "true" });
318
319 expect(callAt(0)).toMatchObject({
320 method: "POST",
321 url: "/repositories/acme/web/pullrequests/7/comments",
322 body: '{"content":{"raw":"true"}}',
323 });
324 }),
325 );
326
327 it.effect("asks for the time a pull request closed, which Bitbucket leaves out by default", () =>
328 Effect.gen(function* () {
329 mockedRequest.mockReturnValueOnce(
330 Effect.succeed(
331 response(
332 pullRequestJson({ state: "MERGED", closed_on: "2025-06-16T23:40:46.222238+00:00" }),
333 ),
334 ),
335 );
336 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
337
338 const pullRequest = yield* api.getPullRequest({ repository: "acme/web", number: 7 });
339
340 expect(callAt(0).url).toBe("/repositories/acme/web/pullrequests/7?fields=%2Bclosed_on");
341 assert.strictEqual(pullRequest.closedAt, "2025-06-16T23:40:46.222Z");
342 }),
343 );
344
345 it.effect("stops the comment walk at its bound and says the conversation was cut short", () =>
346 Effect.gen(function* () {
347 mockedRequest.mockReturnValue(
348 Effect.succeed(
349 response(
350 JSON.stringify({
351 next: "https://api.bitbucket.org/2.0/comments?page=2",
352 values: [
353 {
354 id: 10,
355 content: { raw: "again" },
356 created_on: "2026-06-16T05:04:32+00:00",
357 },
358 ],
359 }),
360 ),
361 ),
362 );
363 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
364
365 const { truncated } = yield* api.listComments({ repository: "acme/web", number: 7 });
366
367 assert.strictEqual(mockedRequest.mock.calls.length, 10);
368 assert.isTrue(truncated);
369 }),
370 );
371
372 it.effect("reassembles a thread from the flat comment list, replies included", () =>
373 Effect.gen(function* () {
374 mockedRequest.mockReturnValueOnce(
375 Effect.succeed(
376 response(
377 JSON.stringify({
378 values: [
379 {
380 id: 10,
381 content: { raw: "rename this" },
382 user: { nickname: "bilal" },
383 created_on: "2026-06-16T05:04:32+00:00",
384 inline: { path: "src/a.ts", to: 12, from: null },
385 resolution: { type: "pullrequest_comment_resolution" },
386 },
387 {
388 id: 11,
389 content: { raw: "done" },
390 user: { nickname: "julius" },
391 created_on: "2026-06-16T06:04:32+00:00",
392 parent: { id: 10 },
393 },
394 {
395 id: 12,
396 content: { raw: "thanks" },
397 user: { nickname: "bilal" },
398 created_on: "2026-06-16T07:04:32+00:00",
399 parent: { id: 11 },
400 },
401 {
402 id: 13,
403 content: { raw: "ship it" },
404 user: { nickname: "bilal" },
405 created_on: "2026-06-16T08:04:32+00:00",
406 },
407 ],
408 }),
409 ),
410 ),
411 );
412 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
413
414 const { threads } = yield* api.listComments({ repository: "acme/web", number: 7 });
415
416 assert.strictEqual(threads.length, 1);
417 expect(threads[0]).toMatchObject({
418 id: "10",
419 path: "src/a.ts",
420 line: 12,
421 side: "right",
422 isResolved: true,
423 });
424 expect(threads[0]?.comments.map((comment) => comment.id)).toEqual(["10", "11", "12"]);
425 }),
426 );
427
428 it.effect("asks for the credentials' permission on this repository, and nobody else's", () =>
429 Effect.gen(function* () {
430 mockedRequest.mockReturnValue(
431 Effect.succeed(
432 response(
433 JSON.stringify({ values: [{ type: "repository_permission", permission: "read" }] }),
434 ),
435 ),
436 );
437 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
438
439 assert.isFalse(yield* api.getRepositoryPermission({ repository: "acme/web" }));
440
441 expect(new URL(callAt(0).url, "https://api.bitbucket.org").pathname).toBe(
442 "/user/workspaces/acme/permissions/repositories",
443 );
444 assert.strictEqual(filterOfCall(0), 'repository.full_name="acme/web"');
445 }),
446 );
447
448 it.effect("escapes a repository name before it goes inside a filter literal", () =>
449 Effect.gen(function* () {
450 mockedRequest.mockReturnValue(Effect.succeed(response(JSON.stringify({ values: [] }))));
451 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
452
453 yield* api.getRepositoryPermission({ repository: 'acme/we"b' });
454
455 assert.strictEqual(filterOfCall(0), 'repository.full_name="acme/we\\"b"');
456 }),
457 );
458
459 const permissionFailure = (status: number) =>
460 Effect.fail(
461 new BitbucketApi.BitbucketResponseError({
462 operation: "request",
463 status,
464 responseBodyLength: 0,
465 }),
466 );
467
468 it.effect.each([403, 404, 410])(
469 "reads HTTP %s from the permissions endpoint as an unknown permission",
470 (status) =>
471 Effect.gen(function* () {
472 mockedRequest.mockReturnValue(permissionFailure(status));
473 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
474
475 assert.isTrue(yield* api.getRepositoryPermission({ repository: "acme/web" }));
476 }),
477 );
478
479 it.effect.each([401, 500])("still fails the permission read on HTTP %s", (status) =>
480 Effect.gen(function* () {
481 mockedRequest.mockReturnValue(permissionFailure(status));
482 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
483
484 const error = yield* Effect.flip(api.getRepositoryPermission({ repository: "acme/web" }));
485 assert.strictEqual(error._tag, "BitbucketResponseError");
486 if (error._tag === "BitbucketResponseError") {
487 assert.strictEqual(error.status, status);
488 }
489 }),
490 );
491
492 it.effect("reads the workspace's people and marks whoever is already a reviewer", () =>
493 Effect.gen(function* () {
494 mockedRequest
495 .mockReturnValueOnce(Effect.succeed(response(pullRequestJson({ reviewers: [octocat] }))))
496 .mockReturnValueOnce(
497 Effect.succeed(
498 response(
499 JSON.stringify({ values: [{ user: bilal }, { user: octocat }, { user: hubot }] }),
500 ),
501 ),
502 );
503 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
504
505 const list = yield* api.listReviewerCandidates({ repository: "acme/web", number: 7 });
506
507 expect(callAt(1).url).toBe("/workspaces/acme/members?pagelen=50");
508 expect(list.candidates.map((candidate) => [candidate.id, candidate.isRequested])).toEqual([
509 ["{octocat}", true],
510 ["{hubot}", false],
511 ]);
512 assert.isFalse(list.truncated);
513 }),
514 );
515
516 it.effect("writes the reviewer set back with the one being asked added to it", () =>
517 Effect.gen(function* () {
518 mockedRequest
519 .mockReturnValueOnce(Effect.succeed(response(pullRequestJson({ reviewers: [octocat] }))))
520 .mockReturnValueOnce(Effect.succeed(response("{}")));
521 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
522
523 yield* api.setReviewerRequest({
524 repository: "acme/web",
525 number: 7,
526 reviewers: [{ id: "{hubot}" }],
527 requested: true,
528 });
529
530 // Bitbucket writes `reviewers` whole, so the one already on the pull request travels with
531 // the new one or the request would take them off it.
532 const call = callAt(1);
533 expect(call.method).toBe("PUT");
534 expect(call.url).toBe("/repositories/acme/web/pullrequests/7");
535 expect(JSON.parse(call.body ?? "")).toEqual({
536 reviewers: [{ uuid: "{octocat}" }, { uuid: "{hubot}" }],
537 });
538 }),
539 );
540});