Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BitbucketPullRequestApi.ts

785 lines29.1 KB

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