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