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

BitbucketApi.ts

1,096 lines36.4 KB

1import * as Config from "effect/Config";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import {
9 NonNegativeInt,
10 TrimmedNonEmptyString,
11 type SourceControlProviderAuth,
12 type SourceControlRepositoryCloneUrls,
13 type SourceControlRepositoryVisibility,
14} from "@t3tools/contracts";
15import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
16import { sanitizeBranchFragment } from "@t3tools/shared/git";
17import {
18 detectSourceControlProviderFromRemoteUrl,
19 isSshRemoteUrl,
20} from "@t3tools/shared/sourceControl";
21​
22import {
23 BitbucketPullRequestListSchema,
24 BitbucketPullRequestSchema,
25 normalizeBitbucketPullRequestRecord,
26 type NormalizedBitbucketPullRequestRecord,
27} from "./bitbucketPullRequests.ts";
28import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
29import * as SourceControlProvider from "./SourceControlProvider.ts";
30import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
31import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
32​
33const DEFAULT_API_BASE_URL = "https://api.bitbucket.org/2.0";
34/** A response body past this is cut short, so one huge diff cannot exhaust the server. */
35const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
36/** Bitbucket redirects a diff once; this leaves room without following a chain forever. */
37const MAX_REDIRECTS = 3;
38​
39const BitbucketApiEnvConfig = Config.all({
40 baseUrl: Config.string("T3CODE_BITBUCKET_API_BASE_URL").pipe(
41 Config.withDefault(DEFAULT_API_BASE_URL),
42 ),
43 accessToken: Config.string("T3CODE_BITBUCKET_ACCESS_TOKEN").pipe(Config.option),
44 email: Config.string("T3CODE_BITBUCKET_EMAIL").pipe(Config.option),
45 apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
46});
47​
48const BitbucketApiOperation = Schema.Literals([
49 "resolveRepository",
50 "getRepository",
51 "getBranchingModel",
52 "getPullRequest",
53 "listPullRequests",
54 "createRepository",
55 "createPullRequest",
56 "probeAuth",
57 "checkoutPullRequest",
58 // The raw escape hatch. Callers name their own operation in their own error, the way the
59 // pull request wrappers do on top of `gh` and `glab`.
60 "request",
61]);
62type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
63​
64export class BitbucketRepositoryLocatorError extends Schema.TaggedErrorClass<BitbucketRepositoryLocatorError>()(
65 "BitbucketRepositoryLocatorError",
66 {
67 repository: Schema.String,
68 },
69) {
70 get detail(): string {
71 return "Bitbucket repositories must be specified as workspace/repository.";
72 }
73​
74 override get message(): string {
75 return `Bitbucket API failed in createRepository: ${this.detail}`;
76 }
78​
79export class BitbucketRequestError extends Schema.TaggedErrorClass<BitbucketRequestError>()(
80 "BitbucketRequestError",
81 {
82 operation: BitbucketApiOperation,
83 cause: Schema.Defect(),
84 },
85) {
86 get detail(): string {
87 return "Failed to send the Bitbucket request.";
88 }
89​
90 override get message(): string {
91 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
92 }
94​
95export class BitbucketResponseError extends Schema.TaggedErrorClass<BitbucketResponseError>()(
96 "BitbucketResponseError",
97 {
98 operation: BitbucketApiOperation,
99 status: Schema.Int,
100 responseBodyLength: NonNegativeInt,
101 },
102) {
103 get detail(): string {
104 return `Bitbucket returned HTTP ${this.status}.`;
105 }
106​
107 override get message(): string {
108 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
109 }
111​
112export class BitbucketResponseBodyReadError extends Schema.TaggedErrorClass<BitbucketResponseBodyReadError>()(
113 "BitbucketResponseBodyReadError",
114 {
115 operation: BitbucketApiOperation,
116 status: Schema.Int,
117 cause: Schema.Defect(),
118 },
119) {
120 get detail(): string {
121 return `Bitbucket returned HTTP ${this.status}.`;
122 }
123​
124 override get message(): string {
125 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
126 }
128​
129export class BitbucketResponseDecodeError extends Schema.TaggedErrorClass<BitbucketResponseDecodeError>()(
130 "BitbucketResponseDecodeError",
131 {
132 operation: BitbucketApiOperation,
133 status: Schema.Int,
134 cause: Schema.Defect(),
135 },
136) {
137 get detail(): string {
138 return "Bitbucket returned invalid JSON for the requested resource.";
139 }
140​
141 override get message(): string {
142 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
143 }
145​
146export class BitbucketRepositoryVcsResolveError extends Schema.TaggedErrorClass<BitbucketRepositoryVcsResolveError>()(
147 "BitbucketRepositoryVcsResolveError",
148 {
149 cwd: Schema.String,
150 cause: Schema.Defect(),
151 },
152) {
153 get detail(): string {
154 return `Failed to resolve VCS repository for ${this.cwd}.`;
155 }
156​
157 override get message(): string {
158 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
159 }
161​
162export class BitbucketRepositoryRemotesListError extends Schema.TaggedErrorClass<BitbucketRepositoryRemotesListError>()(
163 "BitbucketRepositoryRemotesListError",
164 {
165 cwd: Schema.String,
166 cause: Schema.Defect(),
167 },
168) {
169 get detail(): string {
170 return `Failed to list remotes for ${this.cwd}.`;
171 }
172​
173 override get message(): string {
174 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
175 }
177​
178export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedErrorClass<BitbucketRepositoryRemoteNotFoundError>()(
179 "BitbucketRepositoryRemoteNotFoundError",
180 {
181 cwd: Schema.String,
182 },
183) {
184 get detail(): string {
185 return `No Bitbucket repository remote was detected for ${this.cwd}.`;
186 }
187​
188 override get message(): string {
189 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
190 }
192​
193export class BitbucketPullRequestBodyReadError extends Schema.TaggedErrorClass<BitbucketPullRequestBodyReadError>()(
194 "BitbucketPullRequestBodyReadError",
195 {
196 cwd: Schema.String,
197 bodyFile: Schema.String,
198 cause: Schema.Defect(),
199 },
200) {
201 get detail(): string {
202 return `Failed to read pull request body file ${this.bodyFile}.`;
203 }
204​
205 override get message(): string {
206 return `Bitbucket API failed in createPullRequest: ${this.detail}`;
207 }
209​
210export class BitbucketCheckoutError extends Schema.TaggedErrorClass<BitbucketCheckoutError>()(
211 "BitbucketCheckoutError",
212 {
213 cwd: Schema.String,
214 reference: Schema.String,
215 cause: Schema.Defect(),
216 },
217) {
218 get detail(): string {
219 return "Failed to check out the Bitbucket pull request.";
220 }
221​
222 override get message(): string {
223 return `Bitbucket API failed in checkoutPullRequest: ${this.detail}`;
224 }
226​
227/**
228 * A url that does not belong to the configured Bitbucket. Refused rather than followed, because
229 * the request carries the account's credentials and a url that came back in a response — a
230 * pagination cursor, or the target of a redirect — is not this server's to trust.
231 */
232export class BitbucketUntrustedUrlError extends Schema.TaggedErrorClass<BitbucketUntrustedUrlError>()(
233 "BitbucketUntrustedUrlError",
234 {
235 /** The host only. A rejected hop is often a signed url, whose query carries a credential. */
236 host: Schema.String,
237 },
238) {
239 get detail(): string {
240 return `The response pointed at ${this.host}, outside the configured Bitbucket.`;
241 }
242​
243 override get message(): string {
244 return `Bitbucket API failed in request: ${this.detail}`;
245 }
247​
248export const BitbucketApiError = Schema.Union([
249 BitbucketUntrustedUrlError,
250 BitbucketRepositoryLocatorError,
251 BitbucketRequestError,
252 BitbucketResponseError,
253 BitbucketResponseBodyReadError,
254 BitbucketResponseDecodeError,
255 BitbucketRepositoryVcsResolveError,
256 BitbucketRepositoryRemotesListError,
257 BitbucketRepositoryRemoteNotFoundError,
258 BitbucketPullRequestBodyReadError,
259 BitbucketCheckoutError,
260]);
261export type BitbucketApiError = typeof BitbucketApiError.Type;
262export const isBitbucketApiError = Schema.is(BitbucketApiError);
263​
264const RawBitbucketRepositorySchema = Schema.Struct({
265 full_name: TrimmedNonEmptyString,
266 links: Schema.Struct({
267 html: Schema.optional(
268 Schema.Struct({
269 href: TrimmedNonEmptyString,
270 }),
271 ),
272 clone: Schema.optional(
273 Schema.Array(
274 Schema.Struct({
275 name: TrimmedNonEmptyString,
276 href: TrimmedNonEmptyString,
277 }),
278 ),
279 ),
280 }),
281 mainbranch: Schema.optional(
282 Schema.NullOr(
283 Schema.Struct({
284 name: TrimmedNonEmptyString,
285 }),
286 ),
287 ),
288});
289​
290const RawBitbucketBranchingModelSchema = Schema.Struct({
291 development: Schema.optional(
292 Schema.Struct({
293 branch: Schema.optional(
294 Schema.NullOr(
295 Schema.Struct({
296 name: Schema.optional(TrimmedNonEmptyString),
297 }),
298 ),
299 ),
300 is_valid: Schema.optional(Schema.Boolean),
301 name: Schema.optional(Schema.NullOr(Schema.String)),
302 use_mainbranch: Schema.optional(Schema.Boolean),
303 }),
304 ),
305});
306​
307const BitbucketUserSchema = Schema.Struct({
308 username: Schema.optional(TrimmedNonEmptyString),
309 display_name: Schema.optional(TrimmedNonEmptyString),
310 account_id: Schema.optional(TrimmedNonEmptyString),
311});
312​
313export interface BitbucketRepositoryLocator {
314 readonly workspace: string;
315 readonly repoSlug: string;
317​
318export class BitbucketApi extends Context.Service<
319 BitbucketApi,
320 {
321 readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
322​
323 /**
324 * One authenticated request, returning the body verbatim. Bitbucket answers most endpoints
325 * with JSON and a few — a pull request diff, for one — with plain text, so the body is
326 * handed back undecoded for the caller to read as it sees fit.
327 */
328 readonly request: (input: {
329 readonly method: "GET" | "POST" | "PUT" | "DELETE";
330 /**
331 * A path below the API base, or a whole URL as a paged response reports its next page.
332 * A whole URL is refused unless it belongs to the configured Bitbucket.
333 */
334 readonly url: string;
335 /** A JSON document, for the endpoints that take one. */
336 readonly body?: string;
337 /** Response bytes to keep; past this the body comes back cut short and marked. */
338 readonly maxBytes?: number;
339 }) => Effect.Effect<{ readonly body: string; readonly truncated: boolean }, BitbucketApiError>;
340 readonly listPullRequests: (input: {
341 readonly cwd: string;
342 readonly context?: SourceControlProvider.SourceControlProviderContext;
343 readonly headSelector: string;
344 readonly source?: SourceControlProvider.SourceControlRefSelector;
345 readonly state: "open" | "closed" | "merged" | "all";
346 readonly limit?: number;
347 }) => Effect.Effect<ReadonlyArray<NormalizedBitbucketPullRequestRecord>, BitbucketApiError>;
348 readonly getPullRequest: (input: {
349 readonly cwd: string;
350 readonly context?: SourceControlProvider.SourceControlProviderContext;
351 readonly reference: string;
352 }) => Effect.Effect<NormalizedBitbucketPullRequestRecord, BitbucketApiError>;
353 readonly getRepositoryCloneUrls: (input: {
354 readonly cwd: string;
355 readonly context?: SourceControlProvider.SourceControlProviderContext;
356 readonly repository: string;
357 }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
358 readonly createRepository: (input: {
359 readonly cwd: string;
360 readonly repository: string;
361 readonly visibility: SourceControlRepositoryVisibility;
362 }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
363 readonly createPullRequest: (input: {
364 readonly cwd: string;
365 readonly context?: SourceControlProvider.SourceControlProviderContext;
366 readonly baseBranch: string;
367 readonly headSelector: string;
368 readonly source?: SourceControlProvider.SourceControlRefSelector;
369 readonly target?: SourceControlProvider.SourceControlRefSelector;
370 readonly title: string;
371 readonly bodyFile: string;
372 }) => Effect.Effect<void, BitbucketApiError>;
373 readonly getDefaultBranch: (input: {
374 readonly cwd: string;
375 readonly context?: SourceControlProvider.SourceControlProviderContext;
376 }) => Effect.Effect<string | null, BitbucketApiError>;
377 readonly checkoutPullRequest: (input: {
378 readonly cwd: string;
379 readonly context?: SourceControlProvider.SourceControlProviderContext;
380 readonly reference: string;
381 readonly force?: boolean;
382 }) => Effect.Effect<void, BitbucketApiError>;
383 }
384>()("t3/sourceControl/BitbucketApi") {}
385​
386function nonEmpty(value: string | undefined): Option.Option<string> {
387 const trimmed = value?.trim();
388 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
390​
391function normalizeChangeRequestId(reference: string): string {
392 const trimmed = reference.trim().replace(/^#/, "");
393 const urlMatch = /(?:pull-requests|pullrequests|pull-request|pull|pr)\/(\d+)(?:\D.*)?$/i.exec(
394 trimmed,
395 );
396 return urlMatch?.[1] ?? trimmed;
398​
399function sourceWorkspace(input: {
400 readonly headSelector: string;
401 readonly source?: SourceControlProvider.SourceControlRefSelector;
402}): string | undefined {
403 if (input.source?.owner) return input.source.owner;
404 return SourceControlProvider.parseSourceControlOwnerRef(input.headSelector)?.owner;
406​
407function toBitbucketStates(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
408 switch (state) {
409 case "open":
410 return ["OPEN"];
411 case "closed":
412 return ["DECLINED", "SUPERSEDED"];
413 case "merged":
414 return ["MERGED"];
415 case "all":
416 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
417 }
419​
420function bitbucketQueryString(filters: ReadonlyArray<string>): string {
421 return filters.join(" AND ");
423​
424function bitbucketStateFilter(states: ReadonlyArray<string>): string {
425 return states.length === 1
426 ? `state = "${states[0]}"`
427 : `(${states.map((state) => `state = "${state}"`).join(" OR ")})`;
429​
430function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator | null {
431 const normalized = value.trim().replace(/\.git$/u, "");
432 const parts = normalized.split("/").filter((part) => part.length > 0);
433 if (parts.length < 2) return null;
434 const workspace = parts.at(-2);
435 const repoSlug = parts.at(-1);
436 return workspace && repoSlug ? { workspace, repoSlug } : null;
438​
439function requireRepositoryLocator(
440 repository: string,
441): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
442 const locator = parseBitbucketRepositorySlug(repository);
443 return locator
444 ? Effect.succeed(locator)
445 : Effect.fail(
446 new BitbucketRepositoryLocatorError({
447 repository,
448 }),
449 );
451​
452function parseBitbucketRemoteUrl(remoteUrl: string): BitbucketRepositoryLocator | null {
453 const trimmed = remoteUrl.trim();
454 const scpMatch = /^[a-zA-Z0-9._-]+@[^:/]+:(.+)$/.exec(trimmed);
455 if (scpMatch?.[1]) {
456 return parseBitbucketRepositorySlug(scpMatch[1]);
457 }
458​
459 try {
460 return parseBitbucketRepositorySlug(new URL(trimmed).pathname);
461 } catch {
462 return null;
463 }
465​
466function normalizeRepositoryCloneUrls(
467 raw: typeof RawBitbucketRepositorySchema.Type,
468): SourceControlRepositoryCloneUrls {
469 const httpClone =
470 raw.links.clone?.find((entry) => entry.name.toLowerCase() === "https")?.href ??
471 raw.links.html?.href;
472 const sshClone = raw.links.clone?.find((entry) => entry.name.toLowerCase() === "ssh")?.href;
473​
474 return {
475 nameWithOwner: raw.full_name,
476 url: httpClone ?? raw.links.html?.href ?? raw.full_name,
477 sshUrl: sshClone ?? httpClone ?? raw.full_name,
478 };
480​
481function defaultChangeRequestTargetBranch(input: {
482 readonly repository: typeof RawBitbucketRepositorySchema.Type;
483 readonly branchingModel: typeof RawBitbucketBranchingModelSchema.Type | null;
484}): string | null {
485 const repositoryMainBranch = input.repository.mainbranch?.name ?? null;
486 const development = input.branchingModel?.development;
487 if (!development || development.use_mainbranch === true || development.is_valid === false) {
488 return repositoryMainBranch;
489 }
490​
491 const developmentBranch = development.branch?.name?.trim() ?? development.name?.trim() ?? "";
492 if (developmentBranch.length === 0 || developmentBranch === "null") {
493 return repositoryMainBranch;
494 }
495​
496 return developmentBranch;
498​
499function shouldPreferSshRemote(originRemoteUrl: string | null): boolean {
500 if (!originRemoteUrl) return false;
501 return isSshRemoteUrl(originRemoteUrl);
503​
504function selectCloneUrl(input: {
505 readonly cloneUrls: SourceControlRepositoryCloneUrls;
506 readonly originRemoteUrl: string | null;
507}): string {
508 return shouldPreferSshRemote(input.originRemoteUrl)
509 ? input.cloneUrls.sshUrl
510 : input.cloneUrls.url;
512​
513function checkoutBranchName(input: {
514 readonly pullRequestId: number;
515 readonly headBranch: string;
516 readonly isCrossRepository: boolean;
517}): string {
518 if (!input.isCrossRepository) {
519 return input.headBranch;
520 }
521​
522 return `t3code/pr-${input.pullRequestId}/${sanitizeBranchFragment(input.headBranch)}`;
524​
525function repositoryNameWithOwner(
526 repository: Schema.Schema.Type<typeof BitbucketPullRequestSchema>["source"]["repository"],
527): string | null {
528 const fullName = repository?.full_name?.trim() ?? "";
529 return fullName.length > 0 ? fullName : null;
531​
532function repositoryOwnerName(repositoryName: string): string {
533 return repositoryName.split("/")[0]?.trim() || "bitbucket";
535​
536function authFromConfig(
537 config: Config.Success<typeof BitbucketApiEnvConfig>,
538): SourceControlProviderAuth {
539 if (Option.isSome(config.accessToken)) {
540 return {
541 status: "unknown",
542 account: Option.none(),
543 host: Option.some("bitbucket.org"),
544 detail: Option.some("Bitbucket access token is configured."),
545 };
546 }
547​
548 if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
549 return {
550 status: "unknown",
551 account: config.email,
552 host: Option.some("bitbucket.org"),
553 detail: Option.some("Bitbucket API token is configured."),
554 };
555 }
556​
557 return {
558 status: "unauthenticated",
559 account: Option.none(),
560 host: Option.some("bitbucket.org"),
561 detail: Option.some(
562 "Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.",
563 ),
564 };
566​
567/** Null for anything that is not a url at all, which is never the configured Bitbucket. */
568function originOf(value: string): string | null {
569 try {
570 return new URL(value).origin;
571 } catch {
572 return null;
573 }
575​
576function responseError(
577 operation: BitbucketApiOperation,
578 response: HttpClientResponse.HttpClientResponse,
579): Effect.Effect<never, BitbucketApiError> {
580 // Bounded like any other body: an error response is no smaller than a successful one, and
581 // only its length is reported anyway.
582 return collectUint8StreamText({
583 stream: response.stream,
584 maxBytes: DEFAULT_MAX_RESPONSE_BYTES,
585 }).pipe(
586 Effect.mapError(
587 (cause) =>
588 new BitbucketResponseBodyReadError({
589 operation,
590 status: response.status,
591 cause,
592 }),
593 ),
594 Effect.flatMap((collected) =>
595 Effect.fail(
596 new BitbucketResponseError({
597 operation,
598 status: response.status,
599 responseBodyLength: collected.text.length,
600 }),
601 ),
602 ),
603 );
605​
606export const make = Effect.gen(function* () {
607 const config = yield* BitbucketApiEnvConfig;
608 const httpClient = yield* HttpClient.HttpClient;
609 const fileSystem = yield* FileSystem.FileSystem;
610 const git = yield* GitVcsDriver.GitVcsDriver;
611 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
612​
613 const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
614​
615 const withAuth = (request: HttpClientRequest.HttpClientRequest) => {
616 if (Option.isSome(config.accessToken)) {
617 return request.pipe(HttpClientRequest.bearerToken(config.accessToken.value));
618 }
619 if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
620 return request.pipe(HttpClientRequest.basicAuth(config.email.value, config.apiToken.value));
621 }
622 return request;
623 };
624​
625 const decodeResponse = <S extends Schema.Top>(
626 operation: BitbucketApiOperation,
627 schema: S,
628 response: HttpClientResponse.HttpClientResponse,
629 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
630 HttpClientResponse.matchStatus({
631 "2xx": (success) =>
632 HttpClientResponse.schemaBodyJson(schema)(success).pipe(
633 Effect.mapError(
634 (cause) =>
635 new BitbucketResponseDecodeError({
636 operation,
637 status: success.status,
638 cause,
639 }),
640 ),
641 ),
642 orElse: (failed) => responseError(operation, failed),
643 })(response);
644​
645 const executeJson = <S extends Schema.Top>(
646 operation: BitbucketApiOperation,
647 request: HttpClientRequest.HttpClientRequest,
648 schema: S,
649 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
650 httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
651 Effect.mapError(
652 (cause) =>
653 new BitbucketRequestError({
654 operation,
655 cause,
656 }),
657 ),
658 Effect.flatMap((response) => decodeResponse(operation, schema, response)),
659 );
660​
661 const resolveRepository = Effect.fn("BitbucketApi.resolveRepository")(function* (input: {
662 readonly cwd: string;
663 readonly context?: SourceControlProvider.SourceControlProviderContext;
664 readonly repository?: string;
665 }) {
666 const fromRepository =
667 input.repository !== undefined ? parseBitbucketRepositorySlug(input.repository) : null;
668 if (fromRepository) return fromRepository;
669​
670 const fromContext =
671 input.context?.provider.kind === "bitbucket"
672 ? parseBitbucketRemoteUrl(input.context.remoteUrl)
673 : null;
674 if (fromContext) return fromContext;
675​
676 const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
677 Effect.mapError(
678 (cause) =>
679 new BitbucketRepositoryVcsResolveError({
680 cwd: input.cwd,
681 cause,
682 }),
683 ),
684 );
685 const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
686 Effect.mapError(
687 (cause) =>
688 new BitbucketRepositoryRemotesListError({
689 cwd: input.cwd,
690 cause,
691 }),
692 ),
693 );
694​
695 for (const remote of remotes.remotes) {
696 if (detectSourceControlProviderFromRemoteUrl(remote.url)?.kind !== "bitbucket") continue;
697 const parsed = parseBitbucketRemoteUrl(remote.url);
698 if (parsed) return parsed;
699 }
700​
701 return yield* new BitbucketRepositoryRemoteNotFoundError({
702 cwd: input.cwd,
703 });
704 });
705​
706 const getRepositoryFromLocator = (repository: BitbucketRepositoryLocator) =>
707 executeJson(
708 "getRepository",
709 HttpClientRequest.get(
710 apiUrl(
711 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
712 ),
713 ),
714 RawBitbucketRepositorySchema,
715 );
716​
717 const getRepository = (input: {
718 readonly cwd: string;
719 readonly context?: SourceControlProvider.SourceControlProviderContext;
720 readonly repository?: string;
721 }) => resolveRepository(input).pipe(Effect.flatMap(getRepositoryFromLocator));
722​
723 const getBranchingModelFromLocator = (repository: BitbucketRepositoryLocator) =>
724 executeJson(
725 "getBranchingModel",
726 HttpClientRequest.get(
727 apiUrl(
728 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/branching-model`,
729 ),
730 ),
731 RawBitbucketBranchingModelSchema,
732 );
733​
734 const getRawPullRequestFromRepository = (
735 repository: BitbucketRepositoryLocator,
736 reference: string,
737 ) =>
738 executeJson(
739 "getPullRequest",
740 HttpClientRequest.get(
741 apiUrl(
742 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests/${encodeURIComponent(normalizeChangeRequestId(reference))}`,
743 ),
744 ),
745 BitbucketPullRequestSchema,
746 );
747​
748 const getRawPullRequest = (input: {
749 readonly cwd: string;
750 readonly context?: SourceControlProvider.SourceControlProviderContext;
751 readonly reference: string;
752 }) =>
753 resolveRepository(input).pipe(
754 Effect.flatMap((repository) => getRawPullRequestFromRepository(repository, input.reference)),
755 );
756​
757 const readConfigValueNullable = (cwd: string, key: string) =>
758 git.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
759​
760 const resolveCheckoutRemote = Effect.fn("BitbucketApi.resolveCheckoutRemote")(function* (input: {
761 readonly cwd: string;
762 readonly context?: SourceControlProvider.SourceControlProviderContext;
763 readonly destinationRepository: BitbucketRepositoryLocator;
764 readonly sourceRepositoryName: string;
765 readonly isCrossRepository: boolean;
766 }) {
767 if (
768 input.context?.provider.kind === "bitbucket" &&
769 !input.isCrossRepository &&
770 parseBitbucketRemoteUrl(input.context.remoteUrl) !== null
771 ) {
772 return input.context.remoteName;
773 }
774​
775 if (!input.isCrossRepository) {
776 const remoteName = yield* git
777 .resolvePrimaryRemoteName(input.cwd)
778 .pipe(Effect.orElseSucceed(() => null));
779 if (remoteName) return remoteName;
780 }
781​
782 const cloneUrls = yield* getRepository({
783 cwd: input.cwd,
784 repository: input.sourceRepositoryName,
785 ...(input.context ? { context: input.context } : {}),
786 }).pipe(Effect.map(normalizeRepositoryCloneUrls));
787 const originRemoteUrl = yield* readConfigValueNullable(input.cwd, "remote.origin.url");
788 return yield* git.ensureRemote({
789 cwd: input.cwd,
790 preferredName: input.isCrossRepository
791 ? repositoryOwnerName(input.sourceRepositoryName)
792 : input.destinationRepository.workspace,
793 url: selectCloneUrl({ cloneUrls, originRemoteUrl }),
794 });
795 });
796​
797 // A pull request's diff, diffstat and conflicts are served as redirects to a commit-range
798 // URL, and the client does not follow redirects unless asked. The hop stays on the same host,
799 // so the credentials travel with it.
800 /**
801 * The one host these credentials may be sent to. A url that came back inside a response — a
802 * pagination cursor, or the target of a redirect — is data, not instruction, so it is checked
803 * against this before the account's token travels with it.
804 */
805 const apiOrigin = originOf(config.baseUrl);
806​
807 const trustedUrl = (value: string): string | null => {
808 if (!/^https?:\/\//u.test(value)) return apiUrl(value);
809 const origin = originOf(value);
810 return origin !== null && origin === apiOrigin ? value : null;
811 };
812​
813 /**
814 * Redirects are followed here rather than by the client, which forwards every header to
815 * whatever host it is sent to. A pull request diff, diffstat and conflicts are all served as
816 * redirects, so they have to be followed — but only back to the same Bitbucket.
817 */
818 const send = (input: {
819 readonly method: "GET" | "POST" | "PUT" | "DELETE";
820 readonly url: string;
821 readonly body?: string;
822 readonly redirects: number;
823 }): Effect.Effect<HttpClientResponse.HttpClientResponse, BitbucketApiError> => {
824 const url = trustedUrl(input.url);
825 if (url === null) {
826 return Effect.fail(
827 new BitbucketUntrustedUrlError({ host: originOf(input.url) ?? "an unreadable url" }),
828 );
829 }
830 const base =
831 input.method === "GET"
832 ? HttpClientRequest.get(url)
833 : input.method === "POST"
834 ? HttpClientRequest.post(url)
835 : input.method === "DELETE"
836 ? HttpClientRequest.make("DELETE")(url)
837 : HttpClientRequest.put(url);
838 // No `Accept: application/json`: the diff endpoints answer with a patch, not JSON.
839 const withBody =
840 input.body === undefined
841 ? base
842 : base.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
843 return httpClient.execute(withAuth(withBody)).pipe(
844 Effect.mapError(
845 (cause): BitbucketApiError => new BitbucketRequestError({ operation: "request", cause }),
846 ),
847 Effect.flatMap((response) => {
848 const location = response.headers.location;
849 if (
850 response.status >= 300 &&
851 response.status < 400 &&
852 location !== undefined &&
853 input.redirects < MAX_REDIRECTS
854 ) {
855 return send({
856 ...input,
857 url: new URL(location, url).toString(),
858 redirects: input.redirects + 1,
859 });
860 }
861 return Effect.succeed(response);
862 }),
863 );
864 };
865​
866 const request: BitbucketApi["Service"]["request"] = (input) =>
867 send({ ...input, redirects: 0 }).pipe(
868 Effect.flatMap((response) =>
869 HttpClientResponse.matchStatus({
870 // Read through the body stream rather than `text`, so an oversized diff is stopped
871 // as it arrives instead of being materialized whole and then cut. The same collector
872 // the process runner bounds command output with.
873 "2xx": (success) =>
874 collectUint8StreamText({
875 stream: success.stream,
876 maxBytes: input.maxBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
877 }).pipe(
878 Effect.mapError(
879 (cause) =>
880 new BitbucketResponseBodyReadError({
881 operation: "request",
882 status: success.status,
883 cause,
884 }),
885 ),
886 Effect.map((collected) => ({
887 body: collected.text,
888 truncated: collected.truncated,
889 })),
890 ),
891 orElse: (failed) => responseError("request", failed),
892 })(response),
893 ),
894 );
895​
896 return BitbucketApi.of({
897 request,
898 probeAuth: executeJson(
899 "probeAuth",
900 HttpClientRequest.get(apiUrl("/user")),
901 BitbucketUserSchema,
902 ).pipe(
903 Effect.map((user) => ({
904 status: "authenticated" as const,
905 account: nonEmpty(user.username ?? user.display_name ?? user.account_id),
906 host: Option.some("bitbucket.org"),
907 detail: Option.none<string>(),
908 })),
909 Effect.orElseSucceed(() => authFromConfig(config)),
910 ),
911 listPullRequests: (input) =>
912 resolveRepository(input).pipe(
913 Effect.flatMap((repository) => {
914 const states = toBitbucketStates(input.state);
915 const query: Record<string, string | ReadonlyArray<string>> = {
916 pagelen: String(Math.max(1, Math.min(input.limit ?? 20, 50))),
917 sort: "-updated_on",
918 q: bitbucketQueryString([
919 `source.branch.name = "${SourceControlProvider.sourceBranch(input).replaceAll('"', '\\"')}"`,
920 bitbucketStateFilter(states),
921 ]),
922 state: states,
923 };
924​
925 return executeJson(
926 "listPullRequests",
927 HttpClientRequest.get(
928 apiUrl(
929 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
930 ),
931 { urlParams: query },
932 ),
933 BitbucketPullRequestListSchema,
934 );
935 }),
936 Effect.map((list) => list.values.map(normalizeBitbucketPullRequestRecord)),
937 ),
938 getPullRequest: (input) =>
939 getRawPullRequest(input).pipe(Effect.map(normalizeBitbucketPullRequestRecord)),
940 getRepositoryCloneUrls: (input) =>
941 getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
942 createRepository: (input) =>
943 requireRepositoryLocator(input.repository).pipe(
944 Effect.flatMap((repository) =>
945 executeJson(
946 "createRepository",
947 HttpClientRequest.post(
948 apiUrl(
949 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
950 ),
951 ).pipe(
952 HttpClientRequest.bodyJsonUnsafe({
953 scm: "git",
954 is_private: input.visibility === "private",
955 }),
956 ),
957 RawBitbucketRepositorySchema,
958 ),
959 ),
960 Effect.map(normalizeRepositoryCloneUrls),
961 ),
962 createPullRequest: (input) =>
963 Effect.gen(function* () {
964 const repository = yield* resolveRepository(input);
965 const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
966 Effect.mapError(
967 (cause) =>
968 new BitbucketPullRequestBodyReadError({
969 cwd: input.cwd,
970 bodyFile: input.bodyFile,
971 cause,
972 }),
973 ),
974 );
975 const sourceOwner = sourceWorkspace(input);
976 const body = {
977 title: input.title,
978 description,
979 source: {
980 branch: {
981 name: SourceControlProvider.sourceBranch(input),
982 },
983 ...(sourceOwner
984 ? {
985 repository: {
986 full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,
987 },
988 }
989 : {}),
990 },
991 destination: {
992 branch: {
993 name: input.target?.refName ?? input.baseBranch,
994 },
995 },
996 };
997​
998 yield* executeJson(
999 "createPullRequest",
1000 HttpClientRequest.post(
1001 apiUrl(
1002 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
1003 ),
1004 ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
1005 BitbucketPullRequestSchema,
1006 );
1007 }),
1008 getDefaultBranch: (input) =>
1009 resolveRepository(input).pipe(
1010 Effect.flatMap((locator) =>
1011 Effect.all(
1013 repository: getRepositoryFromLocator(locator),
1014 branchingModel: getBranchingModelFromLocator(locator).pipe(
1015 Effect.orElseSucceed(
1016 (): typeof RawBitbucketBranchingModelSchema.Type | null => null,
1017 ),
1018 ),
1019 },
1020 { concurrency: "unbounded" },
1021 ),
1022 ),
1023 Effect.map(defaultChangeRequestTargetBranch),
1024 ),
1025 // Bitbucket Cloud pull requests are Git-backed and Bitbucket does not provide
1026 // an official checkout CLI. This provider-local path uses GitVcsDriver as a
1027 // narrow escape hatch to materialize Bitbucket PR refs. Do not generalize this
1028 // as the source-control provider model: if we support non-Git-compatible
1029 // hosting providers or native JJ/Sapling checkout flows, move this into a
1030 // VCS-specific change-request checkout capability.
1031 checkoutPullRequest: (input) =>
1032 Effect.gen(function* () {
1033 const destinationRepository = yield* resolveRepository(input);
1034 const pullRequest = yield* getRawPullRequestFromRepository(
1035 destinationRepository,
1036 input.reference,
1037 );
1038 const destinationRepositoryName =
1039 repositoryNameWithOwner(pullRequest.destination.repository) ??
1040 `${destinationRepository.workspace}/${destinationRepository.repoSlug}`;
1041 const sourceRepositoryName =
1042 repositoryNameWithOwner(pullRequest.source.repository) ?? destinationRepositoryName;
1043 const isCrossRepository = sourceRepositoryName !== destinationRepositoryName;
1044 const remoteName = yield* resolveCheckoutRemote({
1045 cwd: input.cwd,
1046 destinationRepository,
1047 sourceRepositoryName,
1048 isCrossRepository,
1049 ...(input.context ? { context: input.context } : {}),
1050 });
1051 const remoteBranch = pullRequest.source.branch.name;
1052 const localBranch = checkoutBranchName({
1053 pullRequestId: pullRequest.id,
1054 headBranch: remoteBranch,
1055 isCrossRepository,
1056 });
1057 const localBranchNames = yield* git.listLocalBranchNames(input.cwd);
1058 const localBranchExists = localBranchNames.includes(localBranch);
1059​
1060 if (input.force === true || !localBranchExists) {
1061 yield* git.fetchRemoteBranch({
1062 cwd: input.cwd,
1063 remoteName,
1064 remoteBranch,
1065 localBranch,
1066 });
1067 } else {
1068 yield* git.fetchRemoteTrackingBranch({
1069 cwd: input.cwd,
1070 remoteName,
1071 remoteBranch,
1072 });
1074​
1075 yield* git.setBranchUpstream({
1076 cwd: input.cwd,
1077 branch: localBranch,
1078 remoteName,
1079 remoteBranch,
1080 });
1081 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
1082 }).pipe(
1083 Effect.mapError((cause) =>
1084 isBitbucketApiError(cause)
1085 ? cause
1086 : new BitbucketCheckoutError({
1087 cwd: input.cwd,
1088 reference: input.reference,
1089 cause,
1090 }),
1091 ),
1092 ),
1093 });
1094});
1095​
1096export const layer = Layer.effect(BitbucketApi, make);