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