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