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