Open History to see the last commit
1import * as Cache from "effect/Cache";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Layer from "effect/Layer";
7import * as Result from "effect/Result";
8import * as Schema from "effect/Schema";
9import type {
10 PullRequestAction,
11 PullRequestCheck,
12 PullRequestComment,
13 PullRequestCommit,
14 PullRequestListState,
15 PullRequestMergeMethod,
16 PullRequestMergeability,
17 PullRequestReviewCommentDraft,
18 PullRequestReviewPosition,
19 PullRequestReviewThread,
20 PullRequestReviewVerdict,
21 PullRequestReviewerCandidateList,
22} from "@t3tools/contracts";
23
24import * as BitbucketApi from "./BitbucketApi.ts";
25import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diffFileRevisions";
26import { sortChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
27import {
28 buildReviewThreads,
29 decodeCommentsJson,
30 decodeCommitsJson,
31 decodeConflictsJson,
32 decodeDiffstatJson,
33 decodePullRequestJson,
34 decodePullRequestPageJson,
35 decodeRepositoryPermissionJson,
36 decodeStatusesJson,
37 decodeViewerJson,
38 decodeWorkspaceMembersJson,
39 type BitbucketDiffStat,
40 type BitbucketPullRequest,
41 type BitbucketRawComment,
42} from "./bitbucketPullRequestJson.ts";
43import type { ProviderListCursor } from "@t3tools/source-control-core/server/PullRequestProvider";
44
45export class BitbucketPullRequestReadError extends Schema.TaggedError<BitbucketPullRequestReadError>()(
46 "BitbucketPullRequestReadError",
47 {
48 operation: Schema.String,
49 cause: Schema.Defect(),
50 },
51) {
52 get detail(): string {
53 return `Bitbucket returned an unreadable ${this.operation} response.`;
54 }
55
56 override get message(): string {
57 return `Bitbucket failed in ${this.operation}: ${this.detail}`;
58 }
59}
60
61export class BitbucketViewerUnavailableError extends Schema.TaggedError<BitbucketViewerUnavailableError>()(
62 "BitbucketViewerUnavailableError",
63 {},
64) {
65 get detail(): string {
66 return "Bitbucket returned no account name for the configured credentials.";
67 }
68
69 override get message(): string {
70 return `Bitbucket failed in getViewer: ${this.detail}`;
71 }
72}
73
74export class BitbucketRepositoryUnsupportedError extends Schema.TaggedError<BitbucketRepositoryUnsupportedError>()(
75 "BitbucketRepositoryUnsupportedError",
76 {
77 repository: Schema.String,
78 },
79) {
80 get detail(): string {
81 return "A Bitbucket repository is addressed as workspace/repository.";
82 }
83
84 override get message(): string {
85 return `Bitbucket failed in resolveRepository: ${this.detail}`;
86 }
87}
88
89export class BitbucketDiffCommitError extends Schema.TaggedError<BitbucketDiffCommitError>()(
90 "BitbucketDiffCommitError",
91 {},
92) {
93 get detail(): string {
94 return "The named commit was not a commit sha.";
95 }
96
97 override get message(): string {
98 return `Bitbucket failed in getPullRequestDiff: ${this.detail}`;
99 }
100}
101
102export type BitbucketPullRequestApiError =
103 | BitbucketApi.BitbucketApiError
104 | BitbucketPullRequestReadError
105 | BitbucketViewerUnavailableError
106 | BitbucketRepositoryUnsupportedError
107 | BitbucketDiffCommitError;
108
109function isRepositoryPermissionUnavailableError(
110 error: BitbucketPullRequestApiError,
111): error is BitbucketApi.BitbucketResponseError {
112 return (
113 error._tag === "BitbucketResponseError" &&
114 (error.status === 403 || error.status === 404 || error.status === 410)
115 );
116}
117
118/**
119 * Asking for more does not fail — it answers with an empty page and no error at
120 * all, so this is a number to respect rather than to push against.
121 */
122const MAX_PAGE_SIZE = 50;
123const MAX_LIST_PAGES = 10;
124const CONVERSATION_PAGE_SIZE = 50;
125const CONVERSATION_PAGES = 10;
126const DIFF_MAX_BYTES = 8 * 1024 * 1024;
127/**
128 * Deliberately far shorter than the window the caller holds versions for: a refresh drops what the
129 * caller holds precisely so the next read reaches Bitbucket, and this must not be what answers it
130 * instead.
131 */
132const REVISION_PATCH_TTL = Duration.seconds(5);
133const REVISION_PATCH_CAPACITY = 16;
134export interface BitbucketPullRequestBatch {
135 readonly items: ReadonlyArray<BitbucketPullRequest>;
136 readonly truncated: boolean;
137}
138
139export class BitbucketPullRequestApi extends Context.Service<
140 BitbucketPullRequestApi,
141 {
142 readonly getViewer: () => Effect.Effect<string, BitbucketPullRequestApiError>;
143
144 readonly listPullRequests: (input: {
145 readonly repository: string;
146 readonly state: PullRequestListState;
147 readonly limit: number;
148 readonly query?: string | undefined;
149 readonly cursor?: ProviderListCursor | undefined;
150 /** Matched against the login a row shows, which is the nickname or else the display name. */
151 readonly author?: string | undefined;
152 readonly draft?: boolean | undefined;
153 }) => Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError>;
154
155 readonly getPullRequest: (input: {
156 readonly repository: string;
157 readonly number: number;
158 }) => Effect.Effect<BitbucketPullRequest, BitbucketPullRequestApiError>;
159
160 readonly getRepositoryPermission: (input: {
161 readonly repository: string;
162 }) => Effect.Effect<boolean, BitbucketPullRequestApiError>;
163
164 readonly getPullRequestDiff: (input: {
165 readonly repository: string;
166 readonly number: number;
167 readonly commit?: string | undefined;
168 }) => Effect.Effect<
169 { readonly patch: string; readonly truncated: boolean },
170 BitbucketPullRequestApiError
171 >;
172
173 readonly getDiffStat: (input: {
174 readonly repository: string;
175 readonly number: number;
176 }) => Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError>;
177
178 /**
179 * Answers with every file the patch carries rather than only the paths asked about, since
180 * reading one file's version here means parsing all of them. `complete` is false for a patch
181 * cut short, which cannot speak for what came after the cut.
182 */
183 readonly getFileRevisions: (input: {
184 readonly repository: string;
185 readonly number: number;
186 readonly paths: ReadonlyArray<string>;
187 }) => Effect.Effect<
188 { readonly revisions: ReadonlyMap<string, string>; readonly complete: boolean },
189 BitbucketPullRequestApiError
190 >;
191
192 readonly getMergeability: (input: {
193 readonly repository: string;
194 readonly number: number;
195 }) => Effect.Effect<PullRequestMergeability, BitbucketPullRequestApiError>;
196
197 readonly listComments: (input: {
198 readonly repository: string;
199 readonly number: number;
200 }) => Effect.Effect<
201 {
202 readonly comments: ReadonlyArray<PullRequestComment>;
203 readonly threads: ReadonlyArray<PullRequestReviewThread>;
204 readonly truncated: boolean;
205 },
206 BitbucketPullRequestApiError
207 >;
208
209 readonly listCommits: (input: {
210 readonly repository: string;
211 readonly number: number;
212 }) => Effect.Effect<ReadonlyArray<PullRequestCommit>, BitbucketPullRequestApiError>;
213
214 readonly listChecks: (input: {
215 readonly repository: string;
216 readonly number: number;
217 }) => Effect.Effect<ReadonlyArray<PullRequestCheck>, BitbucketPullRequestApiError>;
218
219 readonly listReviewerCandidates: (input: {
220 readonly repository: string;
221 readonly number: number;
222 }) => Effect.Effect<PullRequestReviewerCandidateList, BitbucketPullRequestApiError>;
223
224 readonly setReviewerRequest: (input: {
225 readonly repository: string;
226 readonly number: number;
227 readonly reviewers: ReadonlyArray<{ readonly id: string }>;
228 readonly requested: boolean;
229 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
230
231 readonly runAction: (input: {
232 readonly repository: string;
233 readonly number: number;
234 readonly action: PullRequestAction;
235 readonly mergeMethod?: PullRequestMergeMethod;
236 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
237
238 readonly updateChangeRequest: (input: {
239 readonly repository: string;
240 readonly number: number;
241 readonly title?: string | undefined;
242 readonly body?: string | undefined;
243 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
244
245 readonly comment: (input: {
246 readonly repository: string;
247 readonly number: number;
248 readonly body: string;
249 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
250
251 readonly updateComment: (input: {
252 readonly repository: string;
253 readonly number: number;
254 readonly commentId: string;
255 readonly body: string;
256 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
257
258 readonly submitReview: (input: {
259 readonly repository: string;
260 readonly number: number;
261 readonly verdict: PullRequestReviewVerdict;
262 readonly body: string;
263 readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
264 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
265
266 readonly replyToComment: (input: {
267 readonly repository: string;
268 readonly number: number;
269 readonly commentId: string;
270 readonly body: string;
271 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
272
273 readonly setCommentResolution: (input: {
274 readonly repository: string;
275 readonly number: number;
276 readonly commentId: string;
277 readonly resolved: boolean;
278 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
279 }
280>()("@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi") {}
281
282function repositorySegments(
283 repository: string,
284): Result.Result<
285 { readonly workspace: string; readonly slug: string },
286 BitbucketRepositoryUnsupportedError
287> {
288 const segments = repository
289 .split("/")
290 .map((segment) => segment.trim())
291 .filter((segment) => segment.length > 0);
292 const [workspace, slug] = segments;
293 if (segments.length !== 2 || workspace === undefined || slug === undefined) {
294 return Result.fail(new BitbucketRepositoryUnsupportedError({ repository }));
295 }
296 return Result.succeed({ workspace, slug });
297}
298
299function repositoryPathOf(segments: { readonly workspace: string; readonly slug: string }): string {
300 return `/repositories/${encodeURIComponent(segments.workspace)}/${encodeURIComponent(
301 segments.slug,
302 )}`;
303}
304
305function isCommitSha(value: string): boolean {
306 return /^[0-9a-f]{7,64}$/i.test(value);
307}
308
309/**
310 * Bitbucket unions repeated `state` parameters, so a tab that spans several of its states asks
311 * for each.
312 */
313function stateParams(state: PullRequestListState): ReadonlyArray<string> {
314 switch (state) {
315 case "open":
316 return ["OPEN"];
317 case "merged":
318 return ["MERGED"];
319 case "closed":
320 return ["DECLINED", "SUPERSEDED"];
321 case "all":
322 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
323 }
324}
325
326/**
327 * The parentheses matter, because the expression is ANDed with the state filter beside it and
328 * an unbracketed `OR` would swallow it.
329 */
330function searchFilter(query: string): string {
331 const literal = filterLiteral(query);
332 return `(title ~ "${literal}" OR description ~ "${literal}")`;
333}
334
335function authorFilter(login: string): string {
336 const literal = filterLiteral(login);
337 return `(author.nickname = "${literal}" OR author.display_name = "${literal}")`;
338}
339
340/**
341 * The backslash is escaped first, or escaping the quote would only produce a literal
342 * backslash followed by a live quote.
343 */
344function filterLiteral(value: string): string {
345 return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
346}
347
348function mergeStrategy(method: PullRequestMergeMethod | undefined): string {
349 switch (method) {
350 case "squash":
351 return "squash";
352 case "rebase":
353 return "rebase_fast_forward";
354 default:
355 return "merge_commit";
356 }
357}
358
359function bitbucketReviewPosition(
360 position: PullRequestReviewPosition,
361): { readonly from: number } | { readonly to: number } {
362 switch (position.kind) {
363 case "added":
364 return { to: position.newLine };
365 case "deleted":
366 return { from: position.oldLine };
367 case "context":
368 return position.side === "left" ? { from: position.oldLine } : { to: position.newLine };
369 }
370}
371
372/** @public Service construction is part of the canonical Effect module API. */
373export const make = Effect.gen(function* () {
374 const bitbucket = yield* BitbucketApi.BitbucketApi;
375
376 const withRepository = <A>(
377 repository: string,
378 use: (
379 path: string,
380 workspace: string,
381 slug: string,
382 ) => Effect.Effect<A, BitbucketPullRequestApiError>,
383 ): Effect.Effect<A, BitbucketPullRequestApiError> => {
384 const segments = repositorySegments(repository);
385 return Result.isSuccess(segments)
386 ? use(repositoryPathOf(segments.success), segments.success.workspace, segments.success.slug)
387 : Effect.fail(segments.failure);
388 };
389
390 const listPage = (input: {
391 readonly url: string;
392 readonly limit: number;
393 readonly page: number;
394 readonly collected: ReadonlyArray<BitbucketPullRequest>;
395 }): Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError> =>
396 bitbucket.request({ method: "GET", url: input.url }).pipe(
397 Effect.flatMap((response) => {
398 const decoded = decodePullRequestPageJson(response.body);
399 if (!Result.isSuccess(decoded)) {
400 return Effect.fail(
401 new BitbucketPullRequestReadError({
402 operation: "listPullRequests",
403 cause: decoded.failure,
404 }),
405 );
406 }
407 const collected = [...input.collected, ...decoded.success.items];
408 const next = decoded.success.next;
409 if (next === null || collected.length >= input.limit || input.page >= MAX_LIST_PAGES) {
410 return Effect.succeed({
411 items: collected.slice(0, input.limit),
412 truncated: next !== null || collected.length > input.limit,
413 });
414 }
415 return listPage({ ...input, url: next, page: input.page + 1, collected });
416 }),
417 );
418
419 const readPage = <A>(input: {
420 readonly operation: string;
421 readonly url: string;
422 readonly decode: (body: string) => Result.Result<A, unknown>;
423 }): Effect.Effect<A, BitbucketPullRequestApiError> =>
424 bitbucket.request({ method: "GET", url: input.url }).pipe(
425 Effect.flatMap((response) => {
426 const decoded = input.decode(response.body);
427 return Result.isSuccess(decoded)
428 ? Effect.succeed(decoded.success)
429 : Effect.fail(
430 new BitbucketPullRequestReadError({
431 operation: input.operation,
432 cause: decoded.failure,
433 }),
434 );
435 }),
436 );
437
438 /**
439 * Threads are assembled once at the end rather than per page, because a reply and the remark
440 * it answers can land either side of a page boundary.
441 */
442 const commentsPage = (input: {
443 readonly url: string;
444 readonly page: number;
445 readonly comments: ReadonlyArray<PullRequestComment>;
446 readonly entries: ReadonlyArray<BitbucketRawComment>;
447 }): Effect.Effect<
448 {
449 readonly comments: ReadonlyArray<PullRequestComment>;
450 readonly threads: ReadonlyArray<PullRequestReviewThread>;
451 readonly truncated: boolean;
452 },
453 BitbucketPullRequestApiError
454 > =>
455 readPage({ operation: "listComments", url: input.url, decode: decodeCommentsJson }).pipe(
456 Effect.flatMap((page) => {
457 const comments = [...input.comments, ...page.comments];
458 const entries = [...input.entries, ...page.entries];
459 if (page.next !== null && input.page < CONVERSATION_PAGES) {
460 return commentsPage({ url: page.next, page: input.page + 1, comments, entries });
461 }
462 return Effect.succeed({
463 comments,
464 threads: buildReviewThreads(entries),
465 truncated: page.next !== null,
466 });
467 }),
468 );
469
470 const itemPages = <A>(input: {
471 readonly operation: string;
472 readonly url: string;
473 readonly decode: (
474 body: string,
475 ) => Result.Result<{ readonly items: ReadonlyArray<A>; readonly next: string | null }, unknown>;
476 readonly items: ReadonlyArray<A>;
477 /** Commit pages are individually oldest-first, so older pages are prepended. */
478 readonly prepend: boolean;
479 }): Effect.Effect<ReadonlyArray<A>, BitbucketPullRequestApiError> =>
480 readPage({ operation: input.operation, url: input.url, decode: input.decode }).pipe(
481 Effect.flatMap((page) => {
482 const items = input.prepend
483 ? [...page.items, ...input.items]
484 : [...input.items, ...page.items];
485 return page.next === null
486 ? Effect.succeed(items)
487 : itemPages({ ...input, url: page.next, items });
488 }),
489 );
490
491 const diffStatPages = (input: {
492 readonly url: string;
493 readonly totals: BitbucketDiffStat;
494 }): Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError> =>
495 readPage({ operation: "getDiffStat", url: input.url, decode: decodeDiffstatJson }).pipe(
496 Effect.flatMap((page) => {
497 const totals = {
498 additions: input.totals.additions + page.additions,
499 deletions: input.totals.deletions + page.deletions,
500 changedFiles: input.totals.changedFiles + page.changedFiles,
501 };
502 return page.next === null
503 ? Effect.succeed(totals)
504 : diffStatPages({ url: page.next, totals });
505 }),
506 );
507
508 const pullRequestDiff = (input: {
509 readonly repository: string;
510 readonly number: number;
511 readonly commit?: string | undefined;
512 }): Effect.Effect<
513 { readonly patch: string; readonly truncated: boolean },
514 BitbucketPullRequestApiError
515 > =>
516 input.commit !== undefined && !isCommitSha(input.commit)
517 ? Effect.fail(new BitbucketDiffCommitError())
518 : withRepository(input.repository, (path) =>
519 bitbucket
520 .request({
521 method: "GET",
522 url:
523 input.commit === undefined
524 ? `${path}/pullrequests/${input.number}/diff`
525 : `${path}/diff/${input.commit}`,
526 maxBytes: DIFF_MAX_BYTES,
527 })
528 .pipe(
529 Effect.map((response) => ({ patch: response.body, truncated: response.truncated })),
530 ),
531 );
532
533 /**
534 * The parsed answer rather than the patch, which at this capacity would hold sixteen bodies
535 * of up to the byte ceiling each resident, and saves walking a patch of a hundred thousand
536 * lines again on every tick.
537 */
538 const revisionPatches = yield* Cache.makeWith(
539 (key: string) => {
540 const [repository, number] = JSON.parse(key) as [string, number];
541 return pullRequestDiff({ repository, number }).pipe(
542 Effect.map((diff) => ({
543 revisions: parseDiffFileRevisions(diff.patch),
544 truncated: diff.truncated,
545 })),
546 );
547 },
548 {
549 capacity: REVISION_PATCH_CAPACITY,
550 timeToLive: (exit) => (Exit.isSuccess(exit) ? REVISION_PATCH_TTL : Duration.zero),
551 },
552 );
553
554 return BitbucketPullRequestApi.of({
555 getViewer: () =>
556 bitbucket.request({ method: "GET", url: "/user" }).pipe(
557 Effect.flatMap((response): Effect.Effect<string, BitbucketPullRequestApiError> => {
558 const decoded = decodeViewerJson(response.body);
559 if (!Result.isSuccess(decoded)) {
560 return Effect.fail(
561 new BitbucketPullRequestReadError({ operation: "getViewer", cause: decoded.failure }),
562 );
563 }
564 return decoded.success === null
565 ? Effect.fail(new BitbucketViewerUnavailableError())
566 : Effect.succeed(decoded.success);
567 }),
568 ),
569
570 listPullRequests: (input) =>
571 withRepository(input.repository, (path) => {
572 const search = input.query?.trim() ?? "";
573 // Exclude already-sent IDs at the inclusive timestamp before applying the page limit.
574 const predicates = [
575 ...(search.length === 0 ? [] : [searchFilter(search)]),
576 ...(input.author === undefined ? [] : [authorFilter(input.author)]),
577 ...(input.draft === undefined ? [] : [`draft = ${input.draft}`]),
578 ...(input.cursor === undefined ? [] : [`updated_on <= ${input.cursor.updatedBefore}`]),
579 ...(input.cursor?.seenAt ?? []).map((number) => `id != ${number}`),
580 ];
581 return listPage({
582 // Reviewers are not on a listing by default, and `viewerReviewRequested` needs them.
583 url: `${path}/pullrequests?${stateParams(input.state)
584 .map((state) => `state=${state}`)
585 .join("&")}&pagelen=${MAX_PAGE_SIZE}&sort=-updated_on&fields=%2Bvalues.reviewers${
586 predicates.length === 0 ? "" : `&q=${encodeURIComponent(predicates.join(" AND "))}`
587 }`,
588 limit: input.limit,
589 page: 1,
590 collected: [],
591 });
592 }),
593
594 getPullRequest: (input) =>
595 withRepository(input.repository, (path) =>
596 readPage({
597 operation: "getPullRequest",
598 // `closed_on` is left out of the default representation. It is the only merge or
599 // decline time Bitbucket states on the pull request itself, and settlement needs it.
600 url: `${path}/pullrequests/${input.number}?fields=%2Bclosed_on`,
601 decode: decodePullRequestJson,
602 }),
603 ),
604
605 // Bitbucket has retired permission endpoints before (CHANGE-2770), and some credentials may
606 // not reach `/user` endpoints at all. A 403, 404 or 410 here is read as a permission that
607 // could not be learned, the same as an empty page: it grants, and the write itself says why
608 // if the account may not do it. Other failures (a bad token, a network fault) still fail.
609 getRepositoryPermission: (input) =>
610 withRepository(input.repository, (_path, workspace, slug) =>
611 readPage({
612 operation: "getRepositoryPermission",
613 url: `/user/workspaces/${encodeURIComponent(workspace)}/permissions/repositories?q=${encodeURIComponent(
614 `repository.full_name="${filterLiteral(`${workspace}/${slug}`)}"`,
615 )}`,
616 decode: decodeRepositoryPermissionJson,
617 }),
618 ).pipe(Effect.catchIf(isRepositoryPermissionUnavailableError, () => Effect.succeed(true))),
619
620 getPullRequestDiff: pullRequestDiff,
621
622 getFileRevisions: (input) =>
623 input.paths.length === 0
624 ? Effect.succeed({ revisions: new Map(), complete: false })
625 : Cache.get(revisionPatches, JSON.stringify([input.repository, input.number])).pipe(
626 Effect.map((diff) => {
627 const revisions = new Map(diff.revisions);
628 // A patch cut short at the byte ceiling says nothing about the files past the cut,
629 // so those paths are left out rather than reported as removed.
630 if (!diff.truncated) {
631 for (const path of input.paths) {
632 if (!revisions.has(path)) revisions.set(path, "");
633 }
634 }
635 return { revisions, complete: !diff.truncated };
636 }),
637 ),
638
639 getDiffStat: (input) =>
640 withRepository(input.repository, (path) =>
641 diffStatPages({
642 url: `${path}/pullrequests/${input.number}/diffstat?pagelen=${MAX_PAGE_SIZE}`,
643 totals: { additions: 0, deletions: 0, changedFiles: 0 },
644 }),
645 ),
646
647 getMergeability: (input) =>
648 withRepository(input.repository, (path) =>
649 readPage({
650 operation: "getMergeability",
651 url: `${path}/pullrequests/${input.number}/conflicts`,
652 decode: decodeConflictsJson,
653 }),
654 ),
655
656 listComments: (input) =>
657 withRepository(input.repository, (path) =>
658 commentsPage({
659 url: `${path}/pullrequests/${input.number}/comments?pagelen=${CONVERSATION_PAGE_SIZE}`,
660 page: 1,
661 comments: [],
662 entries: [],
663 }),
664 ),
665
666 listCommits: (input) =>
667 withRepository(input.repository, (path) =>
668 itemPages({
669 operation: "listCommits",
670 url: `${path}/pullrequests/${input.number}/commits?pagelen=${CONVERSATION_PAGE_SIZE}`,
671 decode: decodeCommitsJson,
672 items: [],
673 prepend: true,
674 }),
675 ),
676
677 listChecks: (input) =>
678 withRepository(input.repository, (path) =>
679 itemPages({
680 operation: "listChecks",
681 url: `${path}/pullrequests/${input.number}/statuses?pagelen=${CONVERSATION_PAGE_SIZE}`,
682 decode: decodeStatusesJson,
683 items: [],
684 prepend: false,
685 }).pipe(Effect.map(sortChecks)),
686 ),
687
688 listReviewerCandidates: (input) =>
689 withRepository(input.repository, (path, workspace) =>
690 Effect.all(
691 [
692 readPage({
693 operation: "getPullRequest",
694 url: `${path}/pullrequests/${input.number}`,
695 decode: decodePullRequestJson,
696 }),
697 readPage({
698 operation: "listReviewerCandidates",
699 url: `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`,
700 decode: decodeWorkspaceMembersJson,
701 }),
702 ],
703 { concurrency: 2 },
704 ).pipe(
705 Effect.map(([pullRequest, members]) => {
706 const requested = new Set(pullRequest.reviewerIds);
707 const author = pullRequest.author?.login;
708 return {
709 // The author is dropped rather than shown unusable: Bitbucket refuses to make the
710 // person who opened a pull request its reviewer.
711 candidates: members.items.flatMap((candidate) =>
712 candidate.login === author
713 ? []
714 : [{ ...candidate, isRequested: requested.has(candidate.id) }],
715 ),
716 truncated: members.next !== null,
717 };
718 }),
719 ),
720 ),
721
722 setReviewerRequest: (input) =>
723 withRepository(input.repository, (path) => {
724 const pullRequest = `${path}/pullrequests/${input.number}`;
725 return readPage({
726 operation: "getPullRequest",
727 url: pullRequest,
728 decode: decodePullRequestJson,
729 }).pipe(
730 Effect.flatMap((current) => {
731 // Bitbucket has no endpoint that adds or removes one reviewer: the pull request's
732 // `reviewers` is written whole, so the set that is already there is read first and
733 // the change applied to it.
734 const uuids = new Set(current.reviewerIds);
735 for (const reviewer of input.reviewers) {
736 if (input.requested) uuids.add(reviewer.id);
737 else uuids.delete(reviewer.id);
738 }
739 return bitbucket.request({
740 method: "PUT",
741 url: pullRequest,
742 body: JSON.stringify({ reviewers: [...uuids].map((uuid) => ({ uuid })) }),
743 });
744 }),
745 Effect.asVoid,
746 );
747 }),
748
749 runAction: (input) =>
750 withRepository(input.repository, (path) => {
751 const pullRequest = `${path}/pullrequests/${input.number}`;
752 if (input.action === "merge") {
753 return bitbucket
754 .request({
755 method: "POST",
756 url: `${pullRequest}/merge`,
757 body: JSON.stringify({ merge_strategy: mergeStrategy(input.mergeMethod) }),
758 })
759 .pipe(Effect.asVoid);
760 }
761 return bitbucket
762 .request({ method: "POST", url: `${pullRequest}/decline` })
763 .pipe(Effect.asVoid);
764 }),
765
766 updateChangeRequest: (input) =>
767 withRepository(input.repository, (path) =>
768 // Only the words this call rewrites travel in the body: as `setReviewerRequest` above
769 // relies on, Bitbucket's PUT is a partial update, so any field left out is left as it
770 // was — sending `reviewers` back here would overwrite a change another user made to it
771 // between this call being issued and the request landing.
772 bitbucket
773 .request({
774 method: "PUT",
775 url: `${path}/pullrequests/${input.number}`,
776 body: JSON.stringify({
777 ...(input.title === undefined ? {} : { title: input.title }),
778 ...(input.body === undefined ? {} : { description: input.body }),
779 }),
780 })
781 .pipe(Effect.asVoid),
782 ),
783
784 comment: (input) =>
785 withRepository(input.repository, (path) =>
786 bitbucket
787 .request({
788 method: "POST",
789 url: `${path}/pullrequests/${input.number}/comments`,
790 body: JSON.stringify({ content: { raw: input.body } }),
791 })
792 .pipe(Effect.asVoid),
793 ),
794
795 updateComment: (input) =>
796 withRepository(input.repository, (path) =>
797 bitbucket
798 .request({
799 method: "PUT",
800 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
801 input.commentId,
802 )}`,
803 body: JSON.stringify({ content: { raw: input.body } }),
804 })
805 .pipe(Effect.asVoid),
806 ),
807
808 submitReview: (input) =>
809 withRepository(input.repository, (path) =>
810 Effect.gen(function* () {
811 const pullRequest = `${path}/pullrequests/${input.number}`;
812 // Bitbucket has no pending review, so a review is replayed as the requests it is
813 // made of: the line comments, then the summary, then the verdict. The verdict goes
814 // last so a review that fails part-way is never left standing as an approval.
815 yield* Effect.forEach(
816 input.comments,
817 (comment) =>
818 bitbucket.request({
819 method: "POST",
820 url: `${pullRequest}/comments`,
821 body: JSON.stringify({
822 content: { raw: comment.body },
823 inline: {
824 path: comment.path,
825 ...bitbucketReviewPosition(comment.position),
826 },
827 }),
828 }),
829 { discard: true },
830 );
831 if (input.body.trim().length > 0) {
832 yield* bitbucket.request({
833 method: "POST",
834 url: `${pullRequest}/comments`,
835 // @effect-diagnostics-next-line preferSchemaOverJson:off
836 body: JSON.stringify({ content: { raw: input.body } }),
837 });
838 }
839 if (input.verdict === "approve") {
840 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/approve` });
841 }
842 if (input.verdict === "request-changes") {
843 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/request-changes` });
844 }
845 }),
846 ),
847
848 replyToComment: (input) =>
849 withRepository(input.repository, (path) =>
850 bitbucket
851 .request({
852 method: "POST",
853 url: `${path}/pullrequests/${input.number}/comments`,
854 body: JSON.stringify({
855 content: { raw: input.body },
856 parent: { id: Number(input.commentId) },
857 }),
858 })
859 .pipe(Effect.asVoid),
860 ),
861
862 setCommentResolution: (input) =>
863 withRepository(input.repository, (path) =>
864 bitbucket
865 .request({
866 method: input.resolved ? "POST" : "DELETE",
867 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
868 input.commentId,
869 )}/resolve`,
870 })
871 .pipe(Effect.asVoid),
872 ),
873 });
874});
875
876export const layer = Layer.effect(BitbucketPullRequestApi, make);