Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BitbucketApi.ts

1,173 lines39.2 KB

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