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