Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import type {
7 PullRequestAction,
8 PullRequestCheck,
9 PullRequestComment,
10 PullRequestCommit,
11 PullRequestListState,
12 PullRequestMergeMethod,
13 PullRequestMergeability,
14 PullRequestReviewCommentDraft,
15 PullRequestReviewPosition,
16 PullRequestReviewThread,
17 PullRequestReviewVerdict,
18 PullRequestReviewerCandidateList,
19} from "@t3tools/contracts";
20
21import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
22import {
23 buildReviewThreads,
24 decodeCommentsJson,
25 decodeCommitsJson,
26 decodeConflictsJson,
27 decodeDiffstatJson,
28 decodePullRequestJson,
29 decodePullRequestPageJson,
30 decodeRepositoryPermissionJson,
31 decodeStatusesJson,
32 decodeViewerJson,
33 decodeWorkspaceMembersJson,
34 type BitbucketDiffStat,
35 type BitbucketPullRequest,
36 type BitbucketRawComment,
37} from "./bitbucketPullRequestJson.ts";
38import type { ProviderListCursor } from "./PullRequestProvider.ts";
39
40/**
41 * Names the read that produced unusable output, so a failure reports the call it came from
42 * rather than borrowing another operation's message.
43 */
44export class BitbucketPullRequestReadError extends Schema.TaggedErrorClass<BitbucketPullRequestReadError>()(
45 "BitbucketPullRequestReadError",
46 {
47 operation: Schema.String,
48 cause: Schema.Defect(),
49 },
50) {
51 get detail(): string {
52 return `Bitbucket returned an unreadable ${this.operation} response.`;
53 }
54
55 override get message(): string {
56 return `Bitbucket failed in ${this.operation}: ${this.detail}`;
57 }
58}
59
60/** Not a decode failure: Bitbucket answered, the account it answered for just has no handle. */
61export class BitbucketViewerUnavailableError extends Schema.TaggedErrorClass<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
74/** A repository that is not `workspace/slug`, which is the only form Bitbucket addresses. */
75export class BitbucketRepositoryUnsupportedError extends Schema.TaggedErrorClass<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
90/** Not a decode failure: the reader named a commit that is not a sha this repository could hold. */
91export class BitbucketDiffCommitError extends Schema.TaggedErrorClass<BitbucketDiffCommitError>()(
92 "BitbucketDiffCommitError",
93 {},
94) {
95 get detail(): string {
96 return "The named commit was not a commit sha.";
97 }
98
99 override get message(): string {
100 return `Bitbucket failed in getPullRequestDiff: ${this.detail}`;
101 }
102}
103
104export type BitbucketPullRequestApiError =
105 | BitbucketApi.BitbucketApiError
106 | BitbucketPullRequestReadError
107 | BitbucketViewerUnavailableError
108 | BitbucketRepositoryUnsupportedError
109 | BitbucketDiffCommitError;
110
111/**
112 * Bitbucket's own ceiling. Asking for more does not fail — it answers with an empty page and no
113 * error at all, so this is a number to respect rather than to push against.
114 */
115const MAX_PAGE_SIZE = 50;
116/** Pages to walk before a listing is reported as truncated. */
117const MAX_LIST_PAGES = 10;
118/** The page size for pull request conversations, commits, and checks. */
119const CONVERSATION_PAGE_SIZE = 50;
120/**
121 * Pages of the conversation to follow before it is reported as truncated. Bitbucket serves
122 * fifty comments a page, so this is five hundred — beyond any pull request a person is reading,
123 * and an end to a walk whose only other stop is Bitbucket running out.
124 */
125const CONVERSATION_PAGES = 10;
126/** The same ceiling the gh and glab diff reads use. */
127const DIFF_MAX_BYTES = 8 * 1024 * 1024;
128
129export interface BitbucketPullRequestBatch {
130 readonly items: ReadonlyArray<BitbucketPullRequest>;
131 readonly truncated: boolean;
132}
133
134export class BitbucketPullRequestApi extends Context.Service<
135 BitbucketPullRequestApi,
136 {
137 /** A function rather than a value, so the request is built per call and not at layer time. */
138 readonly getViewer: () => Effect.Effect<string, BitbucketPullRequestApiError>;
139
140 readonly listPullRequests: (input: {
141 readonly repository: string;
142 readonly state: PullRequestListState;
143 readonly limit: number;
144 /** Free text, matched against a pull request's title and description. */
145 readonly query?: string | undefined;
146 /** Where to carry on from, as a predicate on `updated_on` beside any other. */
147 readonly cursor?: ProviderListCursor | undefined;
148 }) => Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError>;
149
150 readonly getPullRequest: (input: {
151 readonly repository: string;
152 readonly number: number;
153 }) => Effect.Effect<BitbucketPullRequest, BitbucketPullRequestApiError>;
154
155 /** True where the credentials can write to the repository, which is what merging needs. */
156 readonly getRepositoryPermission: (input: {
157 readonly repository: string;
158 }) => Effect.Effect<boolean, BitbucketPullRequestApiError>;
159
160 readonly getPullRequestDiff: (input: {
161 readonly repository: string;
162 readonly number: number;
163 /** One commit's own changes, rather than everything the pull request carries. */
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 readonly getMergeability: (input: {
176 readonly repository: string;
177 readonly number: number;
178 }) => Effect.Effect<PullRequestMergeability, BitbucketPullRequestApiError>;
179
180 readonly listComments: (input: {
181 readonly repository: string;
182 readonly number: number;
183 }) => Effect.Effect<
184 {
185 readonly comments: ReadonlyArray<PullRequestComment>;
186 readonly threads: ReadonlyArray<PullRequestReviewThread>;
187 readonly truncated: boolean;
188 },
189 BitbucketPullRequestApiError
190 >;
191
192 readonly listCommits: (input: {
193 readonly repository: string;
194 readonly number: number;
195 }) => Effect.Effect<ReadonlyArray<PullRequestCommit>, BitbucketPullRequestApiError>;
196
197 readonly listChecks: (input: {
198 readonly repository: string;
199 readonly number: number;
200 }) => Effect.Effect<ReadonlyArray<PullRequestCheck>, BitbucketPullRequestApiError>;
201
202 /**
203 * Who this pull request may be sent to, and who it has already been sent to. Two reads at
204 * once, because Bitbucket keeps the people on the workspace and the reviewers on the pull
205 * request, and neither answers for the other.
206 */
207 readonly listReviewerCandidates: (input: {
208 readonly repository: string;
209 readonly number: number;
210 }) => Effect.Effect<PullRequestReviewerCandidateList, BitbucketPullRequestApiError>;
211
212 readonly setReviewerRequest: (input: {
213 readonly repository: string;
214 readonly number: number;
215 readonly reviewers: ReadonlyArray<{ readonly id: string }>;
216 readonly requested: boolean;
217 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
218
219 readonly runAction: (input: {
220 readonly repository: string;
221 readonly number: number;
222 readonly action: PullRequestAction;
223 readonly mergeMethod?: PullRequestMergeMethod;
224 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
225
226 readonly updateChangeRequest: (input: {
227 readonly repository: string;
228 readonly number: number;
229 readonly title?: string | undefined;
230 readonly body?: string | undefined;
231 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
232
233 readonly comment: (input: {
234 readonly repository: string;
235 readonly number: number;
236 readonly body: string;
237 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
238
239 readonly updateComment: (input: {
240 readonly repository: string;
241 readonly number: number;
242 readonly commentId: string;
243 readonly body: string;
244 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
245
246 readonly submitReview: (input: {
247 readonly repository: string;
248 readonly number: number;
249 readonly verdict: PullRequestReviewVerdict;
250 readonly body: string;
251 readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
252 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
253
254 readonly replyToComment: (input: {
255 readonly repository: string;
256 readonly number: number;
257 readonly commentId: string;
258 readonly body: string;
259 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
260
261 readonly setCommentResolution: (input: {
262 readonly repository: string;
263 readonly number: number;
264 readonly commentId: string;
265 readonly resolved: boolean;
266 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
267 }
268>()("t3/pullRequest/BitbucketPullRequestApi") {}
269
270/** `workspace/slug`; Bitbucket has no deeper nesting to address. */
271function repositorySegments(
272 repository: string,
273): Result.Result<
274 { readonly workspace: string; readonly slug: string },
275 BitbucketRepositoryUnsupportedError
276> {
277 const segments = repository
278 .split("/")
279 .map((segment) => segment.trim())
280 .filter((segment) => segment.length > 0);
281 const [workspace, slug] = segments;
282 if (segments.length !== 2 || workspace === undefined || slug === undefined) {
283 return Result.fail(new BitbucketRepositoryUnsupportedError({ repository }));
284 }
285 return Result.succeed({ workspace, slug });
286}
287
288function repositoryPathOf(segments: { readonly workspace: string; readonly slug: string }): string {
289 return `/repositories/${encodeURIComponent(segments.workspace)}/${encodeURIComponent(
290 segments.slug,
291 )}`;
292}
293
294/**
295 * A commit sha arrives from the reader and goes straight into a request path, so it is checked
296 * rather than trusted: hexadecimal only, from the shortest abbreviation a host prints up to a
297 * whole sha.
298 */
299function isCommitSha(value: string): boolean {
300 return /^[0-9a-f]{7,64}$/i.test(value);
301}
302
303/**
304 * Bitbucket unions repeated `state` parameters, so a tab that spans several of its states asks
305 * for each. It separates a declined pull request from one superseded by another, and both read
306 * as closed here.
307 */
308function stateParams(state: PullRequestListState): ReadonlyArray<string> {
309 switch (state) {
310 case "open":
311 return ["OPEN"];
312 case "merged":
313 return ["MERGED"];
314 case "closed":
315 return ["DECLINED", "SUPERSEDED"];
316 case "all":
317 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
318 }
319}
320
321/**
322 * Bitbucket has no search term, only a filter expression, so free text becomes one: a
323 * case-insensitive contains against the two fields a pull request carries words in. The
324 * parentheses matter, because the expression is ANDed with the state filter beside it and an
325 * unbracketed `OR` would swallow it.
326 *
327 * A string literal in that grammar is delimited by double quotes, so the reader's text is
328 * escaped before it goes inside one — a quote would otherwise end the literal and leave the
329 * rest of the text standing as filter syntax. The whole expression is then URL-encoded, so
330 * nothing in it reaches the query string as a parameter of its own.
331 */
332function searchFilter(query: string): string {
333 const literal = filterLiteral(query);
334 return `(title ~ "${literal}" OR description ~ "${literal}")`;
335}
336
337/**
338 * Text as a string literal of Bitbucket's filter grammar. The backslash is escaped first, or
339 * escaping the quote would only produce a literal backslash followed by a live quote.
340 */
341function filterLiteral(value: string): string {
342 return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
343}
344
345/** Bitbucket's merge strategies, named differently from the three the contract carries. */
346function mergeStrategy(method: PullRequestMergeMethod | undefined): string {
347 switch (method) {
348 case "squash":
349 return "squash";
350 case "rebase":
351 // The linear history GitHub calls "rebase and merge".
352 return "rebase_fast_forward";
353 default:
354 return "merge_commit";
355 }
356}
357
358function bitbucketReviewPosition(
359 position: PullRequestReviewPosition,
360): { readonly from: number } | { readonly to: number } {
361 switch (position.kind) {
362 case "added":
363 return { to: position.newLine };
364 case "deleted":
365 return { from: position.oldLine };
366 case "context":
367 return position.side === "left" ? { from: position.oldLine } : { to: position.newLine };
368 }
369}
370
371export const make = Effect.gen(function* () {
372 const bitbucket = yield* BitbucketApi.BitbucketApi;
373
374 /**
375 * The repository's own path, and the workspace above it — which the people who may review are
376 * kept on rather than on the repository, so both are handed over at once.
377 */
378 const withRepository = <A>(
379 repository: string,
380 use: (path: string, workspace: string) => Effect.Effect<A, BitbucketPullRequestApiError>,
381 ): Effect.Effect<A, BitbucketPullRequestApiError> => {
382 const segments = repositorySegments(repository);
383 return Result.isSuccess(segments)
384 ? use(repositoryPathOf(segments.success), segments.success.workspace)
385 : Effect.fail(segments.failure);
386 };
387
388 /**
389 * Bitbucket pages with a cursor rather than an offset, so the walk follows the `next` URL it
390 * sends. It stops once the caller's page is filled, when Bitbucket reports no next page, or at
391 * the page cap — and anything but running out of pages means there is more to be had.
392 */
393 const listPage = (input: {
394 readonly url: string;
395 readonly limit: number;
396 readonly page: number;
397 readonly collected: ReadonlyArray<BitbucketPullRequest>;
398 }): Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError> =>
399 bitbucket.request({ method: "GET", url: input.url }).pipe(
400 Effect.flatMap((response) => {
401 const decoded = decodePullRequestPageJson(response.body);
402 if (!Result.isSuccess(decoded)) {
403 return Effect.fail(
404 new BitbucketPullRequestReadError({
405 operation: "listPullRequests",
406 cause: decoded.failure,
407 }),
408 );
409 }
410 const collected = [...input.collected, ...decoded.success.items];
411 const next = decoded.success.next;
412 if (next === null || collected.length >= input.limit || input.page >= MAX_LIST_PAGES) {
413 return Effect.succeed({
414 items: collected.slice(0, input.limit),
415 // Bitbucket pages in fifties whatever was asked for, so a walk that stopped on the
416 // count rather than on the last page is holding rows it is about to drop. Those are
417 // more results just as surely as another page would be.
418 truncated: next !== null || collected.length > input.limit,
419 });
420 }
421 return listPage({ ...input, url: next, page: input.page + 1, collected });
422 }),
423 );
424
425 const readPage = <A>(input: {
426 readonly operation: string;
427 readonly url: string;
428 readonly decode: (body: string) => Result.Result<A, unknown>;
429 }): Effect.Effect<A, BitbucketPullRequestApiError> =>
430 bitbucket.request({ method: "GET", url: input.url }).pipe(
431 Effect.flatMap((response) => {
432 const decoded = input.decode(response.body);
433 return Result.isSuccess(decoded)
434 ? Effect.succeed(decoded.success)
435 : Effect.fail(
436 new BitbucketPullRequestReadError({
437 operation: input.operation,
438 cause: decoded.failure,
439 }),
440 );
441 }),
442 );
443
444 /**
445 * The conversation, following the `next` Bitbucket sends until it sends none. Threads are
446 * assembled once at the end rather than per page, because a reply and the remark it answers
447 * can land either side of a page boundary.
448 */
449 const commentsPage = (input: {
450 readonly url: string;
451 readonly page: number;
452 readonly comments: ReadonlyArray<PullRequestComment>;
453 readonly entries: ReadonlyArray<BitbucketRawComment>;
454 }): Effect.Effect<
455 {
456 readonly comments: ReadonlyArray<PullRequestComment>;
457 readonly threads: ReadonlyArray<PullRequestReviewThread>;
458 readonly truncated: boolean;
459 },
460 BitbucketPullRequestApiError
461 > =>
462 readPage({ operation: "listComments", url: input.url, decode: decodeCommentsJson }).pipe(
463 Effect.flatMap((page) => {
464 const comments = [...input.comments, ...page.comments];
465 const entries = [...input.entries, ...page.entries];
466 if (page.next !== null && input.page < CONVERSATION_PAGES) {
467 return commentsPage({ url: page.next, page: input.page + 1, comments, entries });
468 }
469 return Effect.succeed({
470 comments,
471 threads: buildReviewThreads(entries),
472 truncated: page.next !== null,
473 });
474 }),
475 );
476
477 /** Walks a Bitbucket cursor to its end and combines every decoded item. */
478 const itemPages = <A>(input: {
479 readonly operation: string;
480 readonly url: string;
481 readonly decode: (
482 body: string,
483 ) => Result.Result<{ readonly items: ReadonlyArray<A>; readonly next: string | null }, unknown>;
484 readonly items: ReadonlyArray<A>;
485 /** Commit pages are individually oldest-first, so older pages are prepended. */
486 readonly prepend: boolean;
487 }): Effect.Effect<ReadonlyArray<A>, BitbucketPullRequestApiError> =>
488 readPage({ operation: input.operation, url: input.url, decode: input.decode }).pipe(
489 Effect.flatMap((page) => {
490 const items = input.prepend
491 ? [...page.items, ...input.items]
492 : [...input.items, ...page.items];
493 return page.next === null
494 ? Effect.succeed(items)
495 : itemPages({ ...input, url: page.next, items });
496 }),
497 );
498
499 /** Diffstat has one aggregate per page, so its totals are folded while following `next`. */
500 const diffStatPages = (input: {
501 readonly url: string;
502 readonly totals: BitbucketDiffStat;
503 }): Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError> =>
504 readPage({ operation: "getDiffStat", url: input.url, decode: decodeDiffstatJson }).pipe(
505 Effect.flatMap((page) => {
506 const totals = {
507 additions: input.totals.additions + page.additions,
508 deletions: input.totals.deletions + page.deletions,
509 changedFiles: input.totals.changedFiles + page.changedFiles,
510 };
511 return page.next === null
512 ? Effect.succeed(totals)
513 : diffStatPages({ url: page.next, totals });
514 }),
515 );
516
517 return BitbucketPullRequestApi.of({
518 getViewer: () =>
519 bitbucket.request({ method: "GET", url: "/user" }).pipe(
520 Effect.flatMap((response): Effect.Effect<string, BitbucketPullRequestApiError> => {
521 const decoded = decodeViewerJson(response.body);
522 if (!Result.isSuccess(decoded)) {
523 return Effect.fail(
524 new BitbucketPullRequestReadError({ operation: "getViewer", cause: decoded.failure }),
525 );
526 }
527 return decoded.success === null
528 ? Effect.fail(new BitbucketViewerUnavailableError())
529 : Effect.succeed(decoded.success);
530 }),
531 ),
532
533 listPullRequests: (input) =>
534 withRepository(input.repository, (path) => {
535 const search = input.query?.trim() ?? "";
536 // Both narrowings share the one `q` Bitbucket takes, so they are ANDed rather than one
537 // replacing the other. The boundary instant is read inclusively — the rows already sent
538 // at it come back and the caller drops them, which is what keeps their neighbours at the
539 // same instant from being skipped. A date is a bare literal in this grammar, and this one
540 // was checked against a timestamp's shape before it got here.
541 const predicates = [
542 ...(search.length === 0 ? [] : [searchFilter(search)]),
543 ...(input.cursor === undefined ? [] : [`updated_on <= ${input.cursor.updatedBefore}`]),
544 ];
545 return listPage({
546 // Reviewers are not on a listing by default, and `viewerReviewRequested` needs them.
547 url: `${path}/pullrequests?${stateParams(input.state)
548 .map((state) => `state=${state}`)
549 .join("&")}&pagelen=${MAX_PAGE_SIZE}&sort=-updated_on&fields=%2Bvalues.reviewers${
550 predicates.length === 0 ? "" : `&q=${encodeURIComponent(predicates.join(" AND "))}`
551 }`,
552 limit: input.limit,
553 page: 1,
554 collected: [],
555 });
556 }),
557
558 getPullRequest: (input) =>
559 withRepository(input.repository, (path) =>
560 readPage({
561 operation: "getPullRequest",
562 url: `${path}/pullrequests/${input.number}`,
563 decode: decodePullRequestJson,
564 }),
565 ),
566
567 // Nothing on the repository, the pull request or the workspace states what the credentials
568 // may do, so this endpoint is the one request Bitbucket makes unavoidable. It is asked
569 // alongside the reads the detail was already making, so it costs no round trip of its own.
570 getRepositoryPermission: (input) =>
571 withRepository(input.repository, () =>
572 readPage({
573 operation: "getRepositoryPermission",
574 url: `/user/permissions/repositories?q=${encodeURIComponent(
575 `repository.full_name="${filterLiteral(input.repository.trim())}"`,
576 )}`,
577 decode: decodeRepositoryPermissionJson,
578 }),
579 ),
580
581 getPullRequestDiff: (input) =>
582 input.commit !== undefined && !isCommitSha(input.commit)
583 ? Effect.fail(new BitbucketDiffCommitError())
584 : withRepository(input.repository, (path) =>
585 // Already a unified patch, so it needs no decoding at all — only a bound, which a
586 // diff of any size would otherwise ignore. A commit's own patch sits beside the pull
587 // request's at `/diff/{sha}` and reads the same way.
588 bitbucket
589 .request({
590 method: "GET",
591 url:
592 input.commit === undefined
593 ? `${path}/pullrequests/${input.number}/diff`
594 : `${path}/diff/${input.commit}`,
595 maxBytes: DIFF_MAX_BYTES,
596 })
597 .pipe(
598 Effect.map((response) => ({ patch: response.body, truncated: response.truncated })),
599 ),
600 ),
601
602 getDiffStat: (input) =>
603 withRepository(input.repository, (path) =>
604 diffStatPages({
605 url: `${path}/pullrequests/${input.number}/diffstat?pagelen=${MAX_PAGE_SIZE}`,
606 totals: { additions: 0, deletions: 0, changedFiles: 0 },
607 }),
608 ),
609
610 getMergeability: (input) =>
611 withRepository(input.repository, (path) =>
612 readPage({
613 operation: "getMergeability",
614 url: `${path}/pullrequests/${input.number}/conflicts`,
615 decode: decodeConflictsJson,
616 }),
617 ),
618
619 listComments: (input) =>
620 withRepository(input.repository, (path) =>
621 commentsPage({
622 url: `${path}/pullrequests/${input.number}/comments?pagelen=${CONVERSATION_PAGE_SIZE}`,
623 page: 1,
624 comments: [],
625 entries: [],
626 }),
627 ),
628
629 listCommits: (input) =>
630 withRepository(input.repository, (path) =>
631 itemPages({
632 operation: "listCommits",
633 url: `${path}/pullrequests/${input.number}/commits?pagelen=${CONVERSATION_PAGE_SIZE}`,
634 decode: decodeCommitsJson,
635 items: [],
636 prepend: true,
637 }),
638 ),
639
640 listChecks: (input) =>
641 withRepository(input.repository, (path) =>
642 itemPages({
643 operation: "listChecks",
644 url: `${path}/pullrequests/${input.number}/statuses?pagelen=${CONVERSATION_PAGE_SIZE}`,
645 decode: decodeStatusesJson,
646 items: [],
647 prepend: false,
648 }),
649 ),
650
651 listReviewerCandidates: (input) =>
652 withRepository(input.repository, (path, workspace) =>
653 Effect.all(
654 [
655 readPage({
656 operation: "getPullRequest",
657 url: `${path}/pullrequests/${input.number}`,
658 decode: decodePullRequestJson,
659 }),
660 readPage({
661 operation: "listReviewerCandidates",
662 url: `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`,
663 decode: decodeWorkspaceMembersJson,
664 }),
665 ],
666 { concurrency: 2 },
667 ).pipe(
668 Effect.map(([pullRequest, members]) => {
669 const requested = new Set(pullRequest.reviewerIds);
670 const author = pullRequest.author?.login;
671 return {
672 // The author is dropped rather than shown unusable: Bitbucket refuses to make the
673 // person who opened a pull request its reviewer.
674 candidates: members.items.flatMap((candidate) =>
675 candidate.login === author
676 ? []
677 : [{ ...candidate, isRequested: requested.has(candidate.id) }],
678 ),
679 truncated: members.next !== null,
680 };
681 }),
682 ),
683 ),
684
685 setReviewerRequest: (input) =>
686 withRepository(input.repository, (path) => {
687 const pullRequest = `${path}/pullrequests/${input.number}`;
688 return readPage({
689 operation: "getPullRequest",
690 url: pullRequest,
691 decode: decodePullRequestJson,
692 }).pipe(
693 Effect.flatMap((current) => {
694 // Bitbucket has no endpoint that adds or removes one reviewer: the pull request's
695 // `reviewers` is written whole, so the set that is already there is read first and
696 // the change applied to it. Everything else about the pull request is left out of
697 // the body, which leaves it as it was.
698 const uuids = new Set(current.reviewerIds);
699 for (const reviewer of input.reviewers) {
700 if (input.requested) uuids.add(reviewer.id);
701 else uuids.delete(reviewer.id);
702 }
703 return bitbucket.request({
704 method: "PUT",
705 url: pullRequest,
706 body: JSON.stringify({ reviewers: [...uuids].map((uuid) => ({ uuid })) }),
707 });
708 }),
709 Effect.asVoid,
710 );
711 }),
712
713 runAction: (input) =>
714 withRepository(input.repository, (path) => {
715 const pullRequest = `${path}/pullrequests/${input.number}`;
716 // Only merge and close reach here: the provider declares the others unsupported, so the
717 // surface never offers them.
718 if (input.action === "merge") {
719 return bitbucket
720 .request({
721 method: "POST",
722 url: `${pullRequest}/merge`,
723 body: JSON.stringify({ merge_strategy: mergeStrategy(input.mergeMethod) }),
724 })
725 .pipe(Effect.asVoid);
726 }
727 return bitbucket
728 .request({ method: "POST", url: `${pullRequest}/decline` })
729 .pipe(Effect.asVoid);
730 }),
731
732 updateChangeRequest: (input) =>
733 withRepository(input.repository, (path) =>
734 // Only the words this call rewrites travel in the body: as `setReviewerRequest` above
735 // relies on, Bitbucket's PUT is a partial update, so any field left out is left as it
736 // was — sending `reviewers` back here would overwrite a change another user made to it
737 // between this call being issued and the request landing.
738 bitbucket
739 .request({
740 method: "PUT",
741 url: `${path}/pullrequests/${input.number}`,
742 body: JSON.stringify({
743 ...(input.title === undefined ? {} : { title: input.title }),
744 ...(input.body === undefined ? {} : { description: input.body }),
745 }),
746 })
747 .pipe(Effect.asVoid),
748 ),
749
750 comment: (input) =>
751 withRepository(input.repository, (path) =>
752 bitbucket
753 .request({
754 method: "POST",
755 url: `${path}/pullrequests/${input.number}/comments`,
756 // A JSON document rather than a form field, so the body stays text whatever it says.
757 body: JSON.stringify({ content: { raw: input.body } }),
758 })
759 .pipe(Effect.asVoid),
760 ),
761
762 updateComment: (input) =>
763 withRepository(input.repository, (path) =>
764 bitbucket
765 .request({
766 // Bitbucket keeps a pull request's remarks and its line comments in the one
767 // collection, so this endpoint rewrites either kind.
768 method: "PUT",
769 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
770 input.commentId,
771 )}`,
772 body: JSON.stringify({ content: { raw: input.body } }),
773 })
774 .pipe(Effect.asVoid),
775 ),
776
777 submitReview: (input) =>
778 withRepository(input.repository, (path) =>
779 Effect.gen(function* () {
780 const pullRequest = `${path}/pullrequests/${input.number}`;
781 // Bitbucket has no pending review, so a review is replayed as the requests it is
782 // made of: the line comments, then the summary, then the verdict. The verdict goes
783 // last so a review that fails part-way is never left standing as an approval.
784 yield* Effect.forEach(
785 input.comments,
786 (comment) =>
787 bitbucket.request({
788 method: "POST",
789 url: `${pullRequest}/comments`,
790 body: JSON.stringify({
791 content: { raw: comment.body },
792 inline: {
793 path: comment.path,
794 ...bitbucketReviewPosition(comment.position),
795 },
796 }),
797 }),
798 { discard: true },
799 );
800 if (input.body.trim().length > 0) {
801 yield* bitbucket.request({
802 method: "POST",
803 url: `${pullRequest}/comments`,
804 // @effect-diagnostics-next-line preferSchemaOverJson:off
805 body: JSON.stringify({ content: { raw: input.body } }),
806 });
807 }
808 if (input.verdict === "approve") {
809 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/approve` });
810 }
811 if (input.verdict === "request-changes") {
812 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/request-changes` });
813 }
814 }),
815 ),
816
817 replyToComment: (input) =>
818 withRepository(input.repository, (path) =>
819 bitbucket
820 .request({
821 method: "POST",
822 url: `${path}/pullrequests/${input.number}/comments`,
823 body: JSON.stringify({
824 content: { raw: input.body },
825 parent: { id: Number(input.commentId) },
826 }),
827 })
828 .pipe(Effect.asVoid),
829 ),
830
831 setCommentResolution: (input) =>
832 withRepository(input.repository, (path) =>
833 bitbucket
834 .request({
835 // Resolving is a sub-resource that is created and deleted, rather than a field.
836 method: input.resolved ? "POST" : "DELETE",
837 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
838 input.commentId,
839 )}/resolve`,
840 })
841 .pipe(Effect.asVoid),
842 ),
843 });
844});
845
846export const layer = Layer.effect(BitbucketPullRequestApi, make);