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