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 * as Semaphore from "effect/Semaphore";
10import {
11 NonNegativeInt,
12 SourceControlProviderKind,
13 TrimmedNonEmptyString,
14 type SourceControlProviderAuth,
15 type SourceControlProviderInfo,
16 type SourceControlRepositoryCloneUrls,
17 type SourceControlRepositoryVisibility,
18} from "@t3tools/contracts";
19import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
20import { sanitizeBranchFragment } from "@t3tools/shared/git";
21import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
22import { recognizeRemoteWith } from "@t3tools/source-control-core/shared/definition";
23import { definition } from "../shared/definition.ts";
24
25import {
26 BitbucketPullRequestListSchema,
27 BitbucketPullRequestSchema,
28 normalizeBitbucketPullRequestRecord,
29 type NormalizedBitbucketPullRequestRecord,
30} from "./bitbucketPullRequests.ts";
31import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
32import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
33import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
34import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
35
36import * as BitbucketClient from "../shared/definition.ts";
37import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
38
39const DEFAULT_API_BASE_URL = "https://api.bitbucket.org/2.0";
40const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
41const MAX_REDIRECTS = 3;
42const BITBUCKET_API_REQUEST_TIMEOUT = "30 seconds";
43/** A sweep over many branches would otherwise reach Bitbucket as one burst of lookups. */
44const CONCURRENCY = 4;
45
46const BitbucketApiEnvConfig = Config.all({
47 baseUrl: Config.String("T3CODE_BITBUCKET_API_BASE_URL").pipe(
48 Config.withDefault(DEFAULT_API_BASE_URL),
49 ),
50 accessToken: Config.String("T3CODE_BITBUCKET_ACCESS_TOKEN").pipe(Config.option),
51 email: Config.String("T3CODE_BITBUCKET_EMAIL").pipe(Config.option),
52 apiToken: Config.String("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
53});
54
55// Server and Data Center use a different API; a custom Cloud endpoint must be explicit.
56export const BitbucketServesHost = Config.String("T3CODE_BITBUCKET_API_BASE_URL").pipe(
57 Config.option,
58 Config.map(
59 (baseUrl) => (host: string) =>
60 Option.isSome(baseUrl) || host === "bitbucket.org" || host.endsWith(".bitbucket.org"),
61 ),
62);
63
64const BitbucketApiOperation = Schema.Literals([
65 "resolveRepository",
66 "getRepository",
67 "getBranchingModel",
68 "getPullRequest",
69 "listPullRequests",
70 "createRepository",
71 "createPullRequest",
72 "probeAuth",
73 "checkoutPullRequest",
74 "request",
75]);
76type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
77
78export class BitbucketRepositoryLocatorError extends Schema.TaggedError<BitbucketRepositoryLocatorError>()(
79 "BitbucketRepositoryLocatorError",
80 {
81 repository: Schema.String,
82 },
83) {
84 static readonly detail = "Bitbucket repositories must be specified as workspace/repository.";
85
86 get detail(): string {
87 return BitbucketRepositoryLocatorError.detail;
88 }
89
90 get userFacingDetail(): string {
91 return BitbucketRepositoryLocatorError.detail;
92 }
93
94 override get message(): string {
95 return `Bitbucket API failed: ${this.detail}`;
96 }
97}
98
99export class BitbucketRequestError extends Schema.TaggedError<BitbucketRequestError>()(
100 "BitbucketRequestError",
101 {
102 operation: BitbucketApiOperation,
103 cause: Schema.Defect(),
104 },
105) {
106 get detail(): string {
107 return "Failed to send the Bitbucket request.";
108 }
109
110 override get message(): string {
111 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
112 }
113}
114
115export class BitbucketResponseError extends Schema.TaggedError<BitbucketResponseError>()(
116 "BitbucketResponseError",
117 {
118 operation: BitbucketApiOperation,
119 status: Schema.Int,
120 responseBodyLength: NonNegativeInt,
121 retryAt: Schema.optional(Schema.Number),
122 },
123) {
124 get detail(): string {
125 return `Bitbucket returned HTTP ${this.status}.`;
126 }
127
128 override get message(): string {
129 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
130 }
131}
132
133export class BitbucketResponseBodyReadError extends Schema.TaggedError<BitbucketResponseBodyReadError>()(
134 "BitbucketResponseBodyReadError",
135 {
136 operation: BitbucketApiOperation,
137 status: Schema.Int,
138 retryAt: Schema.optional(Schema.Number),
139 cause: Schema.Defect(),
140 },
141) {
142 get detail(): string {
143 return `Bitbucket returned HTTP ${this.status}.`;
144 }
145
146 override get message(): string {
147 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
148 }
149}
150
151export class BitbucketResponseDecodeError extends Schema.TaggedError<BitbucketResponseDecodeError>()(
152 "BitbucketResponseDecodeError",
153 {
154 operation: BitbucketApiOperation,
155 status: Schema.Int,
156 cause: Schema.Defect(),
157 },
158) {
159 get detail(): string {
160 return "Bitbucket returned invalid JSON for the requested resource.";
161 }
162
163 override get message(): string {
164 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
165 }
166}
167
168export class BitbucketRepositoryVcsResolveError extends Schema.TaggedError<BitbucketRepositoryVcsResolveError>()(
169 "BitbucketRepositoryVcsResolveError",
170 {
171 cwd: Schema.String,
172 cause: Schema.Defect(),
173 },
174) {
175 get detail(): string {
176 return `Failed to resolve VCS repository for ${this.cwd}.`;
177 }
178
179 override get message(): string {
180 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
181 }
182}
183
184export class BitbucketRepositoryRemotesListError extends Schema.TaggedError<BitbucketRepositoryRemotesListError>()(
185 "BitbucketRepositoryRemotesListError",
186 {
187 cwd: Schema.String,
188 cause: Schema.Defect(),
189 },
190) {
191 get detail(): string {
192 return `Failed to list remotes for ${this.cwd}.`;
193 }
194
195 override get message(): string {
196 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
197 }
198}
199
200export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedError<BitbucketRepositoryRemoteNotFoundError>()(
201 "BitbucketRepositoryRemoteNotFoundError",
202 {
203 cwd: Schema.String,
204 },
205) {
206 get detail(): string {
207 return `No Bitbucket repository remote was detected for ${this.cwd}.`;
208 }
209
210 override get message(): string {
211 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
212 }
213}
214
215export class BitbucketPullRequestBodyReadError extends Schema.TaggedError<BitbucketPullRequestBodyReadError>()(
216 "BitbucketPullRequestBodyReadError",
217 {
218 cwd: Schema.String,
219 bodyFile: Schema.String,
220 cause: Schema.Defect(),
221 },
222) {
223 get detail(): string {
224 return `Failed to read pull request body file ${this.bodyFile}.`;
225 }
226
227 override get message(): string {
228 return `Bitbucket API failed in createPullRequest: ${this.detail}`;
229 }
230}
231
232export class BitbucketCheckoutError extends Schema.TaggedError<BitbucketCheckoutError>()(
233 "BitbucketCheckoutError",
234 {
235 cwd: Schema.String,
236 reference: Schema.String,
237 cause: Schema.Defect(),
238 },
239) {
240 get detail(): string {
241 return "Failed to check out the Bitbucket pull request.";
242 }
243
244 override get message(): string {
245 return `Bitbucket API failed in checkoutPullRequest: ${this.detail}`;
246 }
247}
248
249/** Reject response-supplied URLs that could leak credentials. */
250export class BitbucketUntrustedUrlError extends Schema.TaggedError<BitbucketUntrustedUrlError>()(
251 "BitbucketUntrustedUrlError",
252 {
253 /** Host only; signed URL queries can contain credentials. */
254 host: Schema.String,
255 },
256) {
257 get detail(): string {
258 return `The response pointed at ${this.host}, outside the configured Bitbucket.`;
259 }
260
261 override get message(): string {
262 return `Bitbucket API failed in request: ${this.detail}`;
263 }
264}
265
266export const BitbucketApiError = Schema.Union([
267 BitbucketUntrustedUrlError,
268 BitbucketRepositoryLocatorError,
269 BitbucketRequestError,
270 BitbucketResponseError,
271 BitbucketResponseBodyReadError,
272 BitbucketResponseDecodeError,
273 BitbucketRepositoryVcsResolveError,
274 BitbucketRepositoryRemotesListError,
275 BitbucketRepositoryRemoteNotFoundError,
276 BitbucketPullRequestBodyReadError,
277 BitbucketCheckoutError,
278 SourceControlRateLimit.SourceControlRateLimitPausedError,
279]);
280export type BitbucketApiError = typeof BitbucketApiError.Type;
281const isBitbucketApiError = Schema.is(BitbucketApiError);
282
283const RawBitbucketRepositorySchema = Schema.Struct({
284 full_name: TrimmedNonEmptyString,
285 links: Schema.Struct({
286 html: Schema.optional(
287 Schema.Struct({
288 href: TrimmedNonEmptyString,
289 }),
290 ),
291 clone: Schema.optional(
292 Schema.Array(
293 Schema.Struct({
294 name: TrimmedNonEmptyString,
295 href: TrimmedNonEmptyString,
296 }),
297 ),
298 ),
299 }),
300 mainbranch: Schema.optional(
301 Schema.NullOr(
302 Schema.Struct({
303 name: TrimmedNonEmptyString,
304 }),
305 ),
306 ),
307});
308
309const RawBitbucketBranchingModelSchema = Schema.Struct({
310 development: Schema.optional(
311 Schema.Struct({
312 branch: Schema.optional(
313 Schema.NullOr(
314 Schema.Struct({
315 name: Schema.optional(TrimmedNonEmptyString),
316 }),
317 ),
318 ),
319 is_valid: Schema.optional(Schema.Boolean),
320 name: Schema.optional(Schema.NullOr(Schema.String)),
321 use_mainbranch: Schema.optional(Schema.Boolean),
322 }),
323 ),
324});
325
326const BitbucketUserSchema = Schema.Struct({
327 username: Schema.optional(TrimmedNonEmptyString),
328 display_name: Schema.optional(TrimmedNonEmptyString),
329 account_id: Schema.optional(TrimmedNonEmptyString),
330});
331
332export interface BitbucketRepositoryLocator {
333 readonly workspace: string;
334 readonly repoSlug: string;
335}
336
337export class BitbucketApi extends Context.Service<
338 BitbucketApi,
339 {
340 readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
341
342 readonly request: (input: {
343 readonly method: "GET" | "POST" | "PUT" | "DELETE";
344 readonly url: string;
345 readonly body?: string;
346 readonly maxBytes?: number;
347 }) => Effect.Effect<{ readonly body: string; readonly truncated: boolean }, BitbucketApiError>;
348 readonly listPullRequests: (input: {
349 readonly cwd: string;
350 readonly context?: SourceControlProvider.SourceControlProviderContext;
351 readonly headSelector: string;
352 readonly source?: SourceControlProvider.SourceControlRefSelector;
353 readonly state: "open" | "closed" | "merged" | "all";
354 readonly limit?: number;
355 }) => Effect.Effect<ReadonlyArray<NormalizedBitbucketPullRequestRecord>, BitbucketApiError>;
356 readonly getPullRequest: (input: {
357 readonly cwd: string;
358 readonly context?: SourceControlProvider.SourceControlProviderContext;
359 readonly reference: string;
360 }) => Effect.Effect<NormalizedBitbucketPullRequestRecord, BitbucketApiError>;
361 readonly getRepositoryCloneUrls: (input: {
362 readonly cwd: string;
363 readonly context?: SourceControlProvider.SourceControlProviderContext;
364 readonly repository: string;
365 }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
366 readonly createRepository: (input: {
367 readonly cwd: string;
368 readonly repository: string;
369 readonly visibility: SourceControlRepositoryVisibility;
370 }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
371 readonly createPullRequest: (input: {
372 readonly cwd: string;
373 readonly context?: SourceControlProvider.SourceControlProviderContext;
374 readonly baseBranch: string;
375 readonly headSelector: string;
376 readonly source?: SourceControlProvider.SourceControlRefSelector;
377 readonly target?: SourceControlProvider.SourceControlRefSelector;
378 readonly title: string;
379 readonly bodyFile: string;
380 }) => Effect.Effect<void, BitbucketApiError>;
381 readonly getDefaultBranch: (input: {
382 readonly cwd: string;
383 readonly context?: SourceControlProvider.SourceControlProviderContext;
384 }) => Effect.Effect<string | null, BitbucketApiError>;
385 readonly checkoutPullRequest: (input: {
386 readonly cwd: string;
387 readonly context?: SourceControlProvider.SourceControlProviderContext;
388 readonly reference: string;
389 readonly force?: boolean;
390 }) => Effect.Effect<void, BitbucketApiError>;
391 }
392>()("@t3tools/source-control-bitbucket/server/BitbucketApi") {}
393
394function nonEmpty(value: string | undefined): Option.Option<string> {
395 const trimmed = value?.trim();
396 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
397}
398
399function normalizeChangeRequestId(reference: string): string {
400 const trimmed = reference.trim().replace(/^#/, "");
401 const urlMatch = /(?:pull-requests|pullrequests|pull-request|pull|pr)\/(\d+)(?:\D.*)?$/i.exec(
402 trimmed,
403 );
404 return urlMatch?.[1] ?? trimmed;
405}
406
407function sourceWorkspace(input: {
408 readonly headSelector: string;
409 readonly source?: SourceControlProvider.SourceControlRefSelector;
410}): string | undefined {
411 if (input.source?.owner) return input.source.owner;
412 return SourceControlProvider.parseSourceControlOwnerRef(input.headSelector)?.owner;
413}
414
415function toBitbucketStates(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
416 switch (state) {
417 case "open":
418 return ["OPEN"];
419 case "closed":
420 return ["DECLINED", "SUPERSEDED"];
421 case "merged":
422 return ["MERGED"];
423 case "all":
424 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
425 }
426}
427
428function bitbucketQueryString(filters: ReadonlyArray<string>): string {
429 return filters.join(" AND ");
430}
431
432function bitbucketStateFilter(states: ReadonlyArray<string>): string {
433 return states.length === 1
434 ? `state = "${states[0]}"`
435 : `(${states.map((state) => `state = "${state}"`).join(" OR ")})`;
436}
437
438function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator | null {
439 const normalized = value.trim().replace(/\.git$/u, "");
440 const parts = normalized.split("/").filter((part) => part.length > 0);
441 if (parts.length < 2) return null;
442 const workspace = parts.at(-2);
443 const repoSlug = parts.at(-1);
444 return workspace && repoSlug ? { workspace, repoSlug } : null;
445}
446
447function requireRepositoryLocator(
448 repository: string,
449): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
450 const locator = parseBitbucketRepositorySlug(repository);
451 return locator
452 ? Effect.succeed(locator)
453 : Effect.fail(
454 new BitbucketRepositoryLocatorError({
455 repository,
456 }),
457 );
458}
459
460function parseBitbucketRemoteUrl(remoteUrl: string): BitbucketRepositoryLocator | null {
461 const trimmed = remoteUrl.trim();
462 const scpMatch = /^[a-zA-Z0-9._-]+@[^:/]+:(.+)$/.exec(trimmed);
463 if (scpMatch?.[1]) {
464 return parseBitbucketRepositorySlug(scpMatch[1]);
465 }
466
467 try {
468 return parseBitbucketRepositorySlug(new URL(trimmed).pathname);
469 } catch {
470 return null;
471 }
472}
473
474function normalizeRepositoryCloneUrls(
475 raw: typeof RawBitbucketRepositorySchema.Type,
476): SourceControlRepositoryCloneUrls {
477 const httpClone =
478 raw.links.clone?.find((entry) => entry.name.toLowerCase() === "https")?.href ??
479 raw.links.html?.href;
480 const sshClone = raw.links.clone?.find((entry) => entry.name.toLowerCase() === "ssh")?.href;
481
482 return {
483 nameWithOwner: raw.full_name,
484 url: httpClone ?? raw.links.html?.href ?? raw.full_name,
485 sshUrl: sshClone ?? httpClone ?? raw.full_name,
486 };
487}
488
489function defaultChangeRequestTargetBranch(input: {
490 readonly repository: typeof RawBitbucketRepositorySchema.Type;
491 readonly branchingModel: typeof RawBitbucketBranchingModelSchema.Type | null;
492}): string | null {
493 const repositoryMainBranch = input.repository.mainbranch?.name ?? null;
494 const development = input.branchingModel?.development;
495 if (!development || development.use_mainbranch === true || development.is_valid === false) {
496 return repositoryMainBranch;
497 }
498
499 const developmentBranch = development.branch?.name?.trim() ?? development.name?.trim() ?? "";
500 if (developmentBranch.length === 0 || developmentBranch === "null") {
501 return repositoryMainBranch;
502 }
503
504 return developmentBranch;
505}
506
507function shouldPreferSshRemote(originRemoteUrl: string | null): boolean {
508 if (!originRemoteUrl) return false;
509 return isSshRemoteUrl(originRemoteUrl);
510}
511
512function selectCloneUrl(input: {
513 readonly cloneUrls: SourceControlRepositoryCloneUrls;
514 readonly originRemoteUrl: string | null;
515}): string {
516 return shouldPreferSshRemote(input.originRemoteUrl)
517 ? input.cloneUrls.sshUrl
518 : input.cloneUrls.url;
519}
520
521function checkoutBranchName(input: {
522 readonly pullRequestId: number;
523 readonly headBranch: string;
524 readonly isCrossRepository: boolean;
525}): string {
526 if (!input.isCrossRepository) {
527 return input.headBranch;
528 }
529
530 return `t3code/pr-${input.pullRequestId}/${sanitizeBranchFragment(input.headBranch)}`;
531}
532
533function repositoryNameWithOwner(
534 repository: Schema.Schema.Type<typeof BitbucketPullRequestSchema>["source"]["repository"],
535): string | null {
536 const fullName = repository?.full_name?.trim() ?? "";
537 return fullName.length > 0 ? fullName : null;
538}
539
540function repositoryOwnerName(repositoryName: string): string {
541 return repositoryName.split("/")[0]?.trim() || "bitbucket";
542}
543
544type BitbucketCredential =
545 | { readonly kind: "access-token"; readonly accessToken: string }
546 | { readonly kind: "api-token"; readonly email: string; readonly apiToken: string };
547
548/** Invalid header values can throw errors containing credentials; treat them as unset. */
549const HEADER_SAFE = /^[\x21-\x7e]+$/u;
550
551function credentialFrom(input: {
552 readonly accessToken: string;
553 readonly email: string;
554 readonly apiToken: string;
555}): BitbucketCredential | null {
556 if (HEADER_SAFE.test(input.accessToken)) {
557 return { kind: "access-token", accessToken: input.accessToken };
558 }
559 if (HEADER_SAFE.test(input.email) && HEADER_SAFE.test(input.apiToken)) {
560 return { kind: "api-token", email: input.email, apiToken: input.apiToken };
561 }
562 return null;
563}
564
565function resolveCredential(
566 settings: BitbucketClient.BitbucketSettings,
567 env: Config.Success<typeof BitbucketApiEnvConfig>,
568): BitbucketCredential | null {
569 return (
570 credentialFrom(settings) ??
571 credentialFrom({
572 accessToken: Option.getOrElse(env.accessToken, () => ""),
573 email: Option.getOrElse(env.email, () => ""),
574 apiToken: Option.getOrElse(env.apiToken, () => ""),
575 })
576 );
577}
578
579function authFromCredential(credential: BitbucketCredential | null): SourceControlProviderAuth {
580 if (credential?.kind === "access-token") {
581 return {
582 status: "unknown",
583 account: Option.none(),
584 host: Option.some("bitbucket.org"),
585 detail: Option.some("An access token is configured."),
586 };
587 }
588
589 if (credential?.kind === "api-token") {
590 return {
591 status: "unknown",
592 account: Option.some(credential.email),
593 host: Option.some("bitbucket.org"),
594 detail: Option.some("An API token is configured."),
595 };
596 }
597
598 return {
599 status: "unauthenticated",
600 account: Option.none(),
601 host: Option.some("bitbucket.org"),
602 detail: Option.some(
603 "Add a Bitbucket token in Settings → Source Control, or set the T3CODE_BITBUCKET_* environment variables on the server.",
604 ),
605 };
606}
607
608function originOf(value: string): string | null {
609 try {
610 return new URL(value).origin;
611 } catch {
612 return null;
613 }
614}
615
616const responseError = Effect.fn("BitbucketApi.responseError")(function* (
617 operation: BitbucketApiOperation,
618 response: HttpClientResponse.HttpClientResponse,
619): Effect.fn.Return<never, BitbucketApiError> {
620 const now = yield* Clock.currentTimeMillis;
621 const retryAt = SourceControlRateLimit.retryAtFromHeader(response.headers["retry-after"], now);
622 const collected = yield* collectUint8StreamText({
623 stream: response.stream,
624 maxBytes: DEFAULT_MAX_RESPONSE_BYTES,
625 }).pipe(
626 Effect.mapError(
627 (cause) =>
628 new BitbucketResponseBodyReadError({
629 operation,
630 status: response.status,
631 retryAt,
632 cause,
633 }),
634 ),
635 );
636 return yield* new BitbucketResponseError({
637 operation,
638 status: response.status,
639 responseBodyLength: collected.text.length,
640 retryAt,
641 });
642});
643
644/** @public */
645export const make = Effect.gen(function* () {
646 const config = yield* BitbucketApiEnvConfig;
647 const host = yield* SourceControlHost.SourceControlHost;
648 const git = host.git;
649 const httpClient = yield* HttpClient.HttpClient;
650 const fileSystem = yield* FileSystem.FileSystem;
651 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
652 const slots = yield* Semaphore.make(CONCURRENCY);
653 // The repository host PullRequestService keys its own backoff under, so both share one pause.
654 const rateLimitKey = {
655 provider: SourceControlProviderKind.make("bitbucket"),
656 host: "bitbucket.org",
657 };
658
659 const servesHost = yield* BitbucketServesHost;
660
661 const servesProvider = (provider: SourceControlProviderInfo | null) =>
662 provider?.kind === "bitbucket" && servesHost(URL.parse(provider.baseUrl)?.hostname ?? "");
663
664 const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
665
666 const currentCredential = host.settings.get.pipe(
667 Effect.map((settings) =>
668 resolveCredential(
669 readSourceControlHostSettings(
670 BitbucketClient.settings,
671 settings.sourceControlHosts[BitbucketClient.definition.kind],
672 ),
673 config,
674 ),
675 ),
676 Effect.catch((error) =>
677 // No cause: a settings decode error can quote a hand-edited token.
678 Effect.logWarning("failed to read Bitbucket credentials from settings", {
679 operation: error.operation,
680 }).pipe(
681 Effect.as(
682 resolveCredential(readSourceControlHostSettings(BitbucketClient.settings, {}), config),
683 ),
684 ),
685 ),
686 );
687
688 const withAuth = (request: HttpClientRequest.HttpClientRequest) =>
689 currentCredential.pipe(
690 Effect.map((credential) =>
691 credential === null
692 ? request
693 : credential.kind === "access-token"
694 ? request.pipe(HttpClientRequest.bearerToken(credential.accessToken))
695 : request.pipe(HttpClientRequest.basicAuth(credential.email, credential.apiToken)),
696 ),
697 );
698
699 /**
700 * Every request waits for one of the shared slots, then honors the pause a 429 starts for the
701 * whole host. Each queued lookup would otherwise spend its own 429 and keep the quota exhausted.
702 * Background reads fail at once while paused; a write or an interactive read has a user waiting
703 * on it, so it still goes out.
704 */
705 const throttled = Effect.fn("BitbucketApi.throttled")(
706 function* <A, R>(method: string, effect: Effect.Effect<A, BitbucketApiError, R>) {
707 const interactive = yield* SourceControlRateLimit.Interactive;
708 const lease = yield* limits.check(
709 rateLimitKey,
710 interactive || method !== "GET" ? { allowPaused: true } : undefined,
711 );
712 return yield* effect.pipe(
713 Effect.tap(() => limits.recordSuccess({ ...rateLimitKey, lease })),
714 Effect.tapError((error) =>
715 (error._tag === "BitbucketResponseError" ||
716 error._tag === "BitbucketResponseBodyReadError") &&
717 error.status === 429
718 ? limits.recordRateLimit({ ...rateLimitKey, lease, retryAt: error.retryAt })
719 : Effect.void,
720 ),
721 );
722 },
723 (effect) => slots.withPermit(effect),
724 );
725
726 const decodeResponse = <S extends Schema.Top>(
727 operation: BitbucketApiOperation,
728 schema: S,
729 response: HttpClientResponse.HttpClientResponse,
730 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
731 HttpClientResponse.matchStatus({
732 "2xx": (success) =>
733 HttpClientResponse.schemaBodyJson(schema)(success).pipe(
734 Effect.mapError(
735 (cause) =>
736 new BitbucketResponseDecodeError({
737 operation,
738 status: success.status,
739 cause,
740 }),
741 ),
742 ),
743 orElse: (failed) => responseError(operation, failed),
744 })(response);
745
746 const executeJson = <S extends Schema.Top>(
747 operation: BitbucketApiOperation,
748 request: HttpClientRequest.HttpClientRequest,
749 schema: S,
750 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
751 throttled(
752 request.method,
753 withAuth(request.pipe(HttpClientRequest.acceptJson)).pipe(
754 Effect.flatMap(httpClient.execute),
755 Effect.mapError(
756 (cause) =>
757 new BitbucketRequestError({
758 operation,
759 cause,
760 }),
761 ),
762 Effect.flatMap((response) => decodeResponse(operation, schema, response)),
763 Effect.timeout(BITBUCKET_API_REQUEST_TIMEOUT),
764 Effect.catchTags({
765 TimeoutError: (cause) => Effect.fail(new BitbucketRequestError({ operation, cause })),
766 }),
767 ),
768 );
769
770 const resolveRepository = Effect.fn("BitbucketApi.resolveRepository")(function* (input: {
771 readonly cwd: string;
772 readonly context?: SourceControlProvider.SourceControlProviderContext;
773 readonly repository?: string;
774 }) {
775 if (input.context?.provider.kind === "bitbucket" && !servesProvider(input.context.provider)) {
776 // Falling back to another remote could act on a different repository.
777 return yield* new BitbucketRepositoryRemoteNotFoundError({ cwd: input.cwd });
778 }
779 if (input.repository !== undefined) {
780 return yield* requireRepositoryLocator(input.repository);
781 }
782
783 const fromContext =
784 input.context?.provider.kind === "bitbucket"
785 ? parseBitbucketRemoteUrl(input.context.remoteUrl)
786 : null;
787 if (fromContext) return fromContext;
788
789 const listRemotes = yield* git.remotes(input.cwd).pipe(
790 Effect.mapError(
791 (cause) =>
792 new BitbucketRepositoryVcsResolveError({
793 cwd: input.cwd,
794 cause,
795 }),
796 ),
797 );
798 const remotes = yield* listRemotes.pipe(
799 Effect.mapError(
800 (cause) =>
801 new BitbucketRepositoryRemotesListError({
802 cwd: input.cwd,
803 cause,
804 }),
805 ),
806 );
807
808 for (const remote of remotes.remotes) {
809 if (!servesProvider(recognizeRemoteWith(definition, remote.url))) continue;
810 const parsed = parseBitbucketRemoteUrl(remote.url);
811 if (parsed) return parsed;
812 }
813
814 return yield* new BitbucketRepositoryRemoteNotFoundError({
815 cwd: input.cwd,
816 });
817 });
818
819 const getRepositoryFromLocator = (repository: BitbucketRepositoryLocator) =>
820 executeJson(
821 "getRepository",
822 HttpClientRequest.get(
823 apiUrl(
824 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
825 ),
826 ),
827 RawBitbucketRepositorySchema,
828 );
829
830 const getRepository = (input: {
831 readonly cwd: string;
832 readonly context?: SourceControlProvider.SourceControlProviderContext;
833 readonly repository?: string;
834 }) => resolveRepository(input).pipe(Effect.flatMap(getRepositoryFromLocator));
835
836 const getBranchingModelFromLocator = (repository: BitbucketRepositoryLocator) =>
837 executeJson(
838 "getBranchingModel",
839 HttpClientRequest.get(
840 apiUrl(
841 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/branching-model`,
842 ),
843 ),
844 RawBitbucketBranchingModelSchema,
845 );
846
847 const getRawPullRequestFromRepository = (
848 repository: BitbucketRepositoryLocator,
849 reference: string,
850 ) =>
851 executeJson(
852 "getPullRequest",
853 HttpClientRequest.get(
854 apiUrl(
855 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests/${encodeURIComponent(normalizeChangeRequestId(reference))}`,
856 ),
857 ),
858 BitbucketPullRequestSchema,
859 );
860
861 const getRawPullRequest = (input: {
862 readonly cwd: string;
863 readonly context?: SourceControlProvider.SourceControlProviderContext;
864 readonly reference: string;
865 }) =>
866 resolveRepository(input).pipe(
867 Effect.flatMap((repository) => getRawPullRequestFromRepository(repository, input.reference)),
868 );
869
870 const readConfigValueNullable = (cwd: string, key: string) =>
871 git.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
872
873 const resolveCheckoutRemote = Effect.fn("BitbucketApi.resolveCheckoutRemote")(function* (input: {
874 readonly cwd: string;
875 readonly context?: SourceControlProvider.SourceControlProviderContext;
876 readonly destinationRepository: BitbucketRepositoryLocator;
877 readonly sourceRepositoryName: string;
878 readonly isCrossRepository: boolean;
879 }) {
880 if (
881 input.context?.provider.kind === "bitbucket" &&
882 !input.isCrossRepository &&
883 parseBitbucketRemoteUrl(input.context.remoteUrl) !== null
884 ) {
885 return input.context.remoteName;
886 }
887
888 if (!input.isCrossRepository) {
889 const remoteName = yield* git
890 .resolvePrimaryRemoteName(input.cwd)
891 .pipe(Effect.orElseSucceed(() => null));
892 if (remoteName) return remoteName;
893 }
894
895 const cloneUrls = yield* getRepository({
896 cwd: input.cwd,
897 repository: input.sourceRepositoryName,
898 ...(input.context ? { context: input.context } : {}),
899 }).pipe(Effect.map(normalizeRepositoryCloneUrls));
900 const originRemoteUrl = yield* readConfigValueNullable(input.cwd, "remote.origin.url");
901 return yield* git.ensureRemote({
902 cwd: input.cwd,
903 preferredName: input.isCrossRepository
904 ? repositoryOwnerName(input.sourceRepositoryName)
905 : input.destinationRepository.workspace,
906 url: selectCloneUrl({ cloneUrls, originRemoteUrl }),
907 });
908 });
909
910 const apiOrigin = originOf(config.baseUrl);
911
912 const trustedUrl = (value: string): string | null => {
913 if (!/^https?:\/\//u.test(value)) return apiUrl(value);
914 const origin = originOf(value);
915 return origin !== null && origin === apiOrigin ? value : null;
916 };
917
918 /** Redirects forward auth headers; restrict them to the configured Bitbucket. */
919 const send = (input: {
920 readonly method: "GET" | "POST" | "PUT" | "DELETE";
921 readonly url: string;
922 readonly body?: string;
923 readonly redirects: number;
924 }): Effect.Effect<HttpClientResponse.HttpClientResponse, BitbucketApiError> => {
925 const url = trustedUrl(input.url);
926 if (url === null) {
927 return Effect.fail(
928 new BitbucketUntrustedUrlError({ host: originOf(input.url) ?? "an unreadable url" }),
929 );
930 }
931 const base =
932 input.method === "GET"
933 ? HttpClientRequest.get(url)
934 : input.method === "POST"
935 ? HttpClientRequest.post(url)
936 : input.method === "DELETE"
937 ? HttpClientRequest.make("DELETE")(url)
938 : HttpClientRequest.put(url);
939 // Diff endpoints return patches, not JSON.
940 const withBody =
941 input.body === undefined
942 ? base
943 : base.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
944 return withAuth(withBody).pipe(
945 Effect.flatMap(httpClient.execute),
946 Effect.mapError(
947 (cause): BitbucketApiError => new BitbucketRequestError({ operation: "request", cause }),
948 ),
949 Effect.flatMap((response) => {
950 const location = response.headers.location;
951 if (
952 response.status >= 300 &&
953 response.status < 400 &&
954 location !== undefined &&
955 input.redirects < MAX_REDIRECTS
956 ) {
957 return send({
958 ...input,
959 url: new URL(location, url).toString(),
960 redirects: input.redirects + 1,
961 });
962 }
963 return Effect.succeed(response);
964 }),
965 );
966 };
967
968 const request: BitbucketApi["Service"]["request"] = (input) =>
969 throttled(
970 input.method,
971 send({ ...input, redirects: 0 }).pipe(
972 Effect.flatMap((response) =>
973 HttpClientResponse.matchStatus({
974 // Read through the body stream rather than `text`, so an oversized diff is stopped as
975 // it arrives instead of being materialized whole and then cut.
976 "2xx": (success) =>
977 collectUint8StreamText({
978 stream: success.stream,
979 maxBytes: input.maxBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
980 }).pipe(
981 Effect.mapError(
982 (cause) =>
983 new BitbucketResponseBodyReadError({
984 operation: "request",
985 status: success.status,
986 cause,
987 }),
988 ),
989 Effect.map((collected) => ({
990 body: collected.text,
991 truncated: collected.truncated,
992 })),
993 ),
994 orElse: (failed) => responseError("request", failed),
995 })(response),
996 ),
997 // This also caps redirect hops: no request can finish headers then stall its body forever.
998 Effect.timeout(BITBUCKET_API_REQUEST_TIMEOUT),
999 Effect.catchTags({
1000 TimeoutError: (cause) =>
1001 Effect.fail(new BitbucketRequestError({ operation: "request", cause })),
1002 }),
1003 ),
1004 );
1005
1006 return BitbucketApi.of({
1007 request,
1008 probeAuth: executeJson(
1009 "probeAuth",
1010 HttpClientRequest.get(apiUrl("/user")),
1011 BitbucketUserSchema,
1012 ).pipe(
1013 Effect.map((user) => ({
1014 status: "authenticated" as const,
1015 account: nonEmpty(user.username ?? user.display_name ?? user.account_id),
1016 host: Option.some("bitbucket.org"),
1017 detail: Option.none<string>(),
1018 })),
1019 Effect.catch(() => currentCredential.pipe(Effect.map(authFromCredential))),
1020 ),
1021 listPullRequests: Effect.fn("BitbucketApi.listPullRequests")(function (input) {
1022 return resolveRepository(input).pipe(
1023 Effect.flatMap((repository) => {
1024 const states = toBitbucketStates(input.state);
1025 const query: Record<string, string | ReadonlyArray<string>> = {
1026 pagelen: String(Math.max(1, Math.min(input.limit ?? 20, 50))),
1027 sort: "-updated_on",
1028 q: bitbucketQueryString([
1029 `source.branch.name = "${SourceControlProvider.sourceBranch(input).replaceAll('"', '\\"')}"`,
1030 bitbucketStateFilter(states),
1031 ]),
1032 state: states,
1033 };
1034
1035 return executeJson(
1036 "listPullRequests",
1037 HttpClientRequest.get(
1038 apiUrl(
1039 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
1040 ),
1041 { urlParams: query },
1042 ),
1043 BitbucketPullRequestListSchema,
1044 );
1045 }),
1046 Effect.map((list) => list.values.map(normalizeBitbucketPullRequestRecord)),
1047 );
1048 }),
1049 getPullRequest: Effect.fn("BitbucketApi.getPullRequest")(function (input) {
1050 return getRawPullRequest(input).pipe(Effect.map(normalizeBitbucketPullRequestRecord));
1051 }),
1052 getRepositoryCloneUrls: Effect.fn("BitbucketApi.getRepositoryCloneUrls")(function (input) {
1053 return getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls));
1054 }),
1055 createRepository: Effect.fn("BitbucketApi.createRepository")(function (input) {
1056 return requireRepositoryLocator(input.repository).pipe(
1057 Effect.flatMap((repository) =>
1058 executeJson(
1059 "createRepository",
1060 HttpClientRequest.post(
1061 apiUrl(
1062 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
1063 ),
1064 ).pipe(
1065 HttpClientRequest.bodyJsonUnsafe({
1066 scm: "git",
1067 is_private: input.visibility === "private",
1068 }),
1069 ),
1070 RawBitbucketRepositorySchema,
1071 ),
1072 ),
1073 Effect.map(normalizeRepositoryCloneUrls),
1074 );
1075 }),
1076 createPullRequest: Effect.fn("BitbucketApi.createPullRequest")(function* (input) {
1077 const repository = yield* resolveRepository(input);
1078 const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
1079 Effect.mapError(
1080 (cause) =>
1081 new BitbucketPullRequestBodyReadError({
1082 cwd: input.cwd,
1083 bodyFile: input.bodyFile,
1084 cause,
1085 }),
1086 ),
1087 );
1088 const sourceOwner = sourceWorkspace(input);
1089 const body = {
1090 title: input.title,
1091 description,
1092 source: {
1093 branch: {
1094 name: SourceControlProvider.sourceBranch(input),
1095 },
1096 ...(sourceOwner
1097 ? {
1098 repository: {
1099 full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,
1100 },
1101 }
1102 : {}),
1103 },
1104 destination: {
1105 branch: {
1106 name: input.target?.refName ?? input.baseBranch,
1107 },
1108 },
1109 };
1110
1111 yield* executeJson(
1112 "createPullRequest",
1113 HttpClientRequest.post(
1114 apiUrl(
1115 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
1116 ),
1117 ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
1118 BitbucketPullRequestSchema,
1119 );
1120 }),
1121 getDefaultBranch: Effect.fn("BitbucketApi.getDefaultBranch")(function (input) {
1122 return resolveRepository(input).pipe(
1123 Effect.flatMap((locator) =>
1124 Effect.all(
1125 {
1126 repository: getRepositoryFromLocator(locator),
1127 branchingModel: getBranchingModelFromLocator(locator).pipe(
1128 Effect.orElseSucceed(
1129 (): typeof RawBitbucketBranchingModelSchema.Type | null => null,
1130 ),
1131 ),
1132 },
1133 { concurrency: "unbounded" },
1134 ),
1135 ),
1136 Effect.map(defaultChangeRequestTargetBranch),
1137 );
1138 }),
1139 checkoutPullRequest: Effect.fn("BitbucketApi.checkoutPullRequest")(
1140 function* (input) {
1141 const destinationRepository = yield* resolveRepository(input);
1142 const pullRequest = yield* getRawPullRequestFromRepository(
1143 destinationRepository,
1144 input.reference,
1145 );
1146 const destinationRepositoryName =
1147 repositoryNameWithOwner(pullRequest.destination.repository) ??
1148 `${destinationRepository.workspace}/${destinationRepository.repoSlug}`;
1149 const sourceRepositoryName =
1150 repositoryNameWithOwner(pullRequest.source.repository) ?? destinationRepositoryName;
1151 const isCrossRepository = sourceRepositoryName !== destinationRepositoryName;
1152 const remoteName = yield* resolveCheckoutRemote({
1153 cwd: input.cwd,
1154 destinationRepository,
1155 sourceRepositoryName,
1156 isCrossRepository,
1157 ...(input.context ? { context: input.context } : {}),
1158 });
1159 const remoteBranch = pullRequest.source.branch.name;
1160 const localBranch = checkoutBranchName({
1161 pullRequestId: pullRequest.id,
1162 headBranch: remoteBranch,
1163 isCrossRepository,
1164 });
1165 const localBranchNames = yield* git.listLocalBranchNames(input.cwd);
1166 const localBranchExists = localBranchNames.includes(localBranch);
1167
1168 if (input.force === true || !localBranchExists) {
1169 yield* git.fetchRemoteBranch({
1170 cwd: input.cwd,
1171 remoteName,
1172 remoteBranch,
1173 localBranch,
1174 });
1175 } else {
1176 yield* git.fetchRemoteTrackingBranch({
1177 cwd: input.cwd,
1178 remoteName,
1179 remoteBranch,
1180 });
1181 }
1182
1183 yield* git.setBranchUpstream({
1184 cwd: input.cwd,
1185 branch: localBranch,
1186 remoteName,
1187 remoteBranch,
1188 });
1189 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
1190 },
1191 (effect, input) =>
1192 effect.pipe(
1193 Effect.mapError((cause) =>
1194 isBitbucketApiError(cause)
1195 ? cause
1196 : new BitbucketCheckoutError({
1197 cwd: input.cwd,
1198 reference: input.reference,
1199 cause,
1200 }),
1201 ),
1202 ),
1203 ),
1204 });
1205});
1206
1207export const layer = Layer.effect(BitbucketApi, make);