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

bitbucketPullRequestJson.ts

562 lines19.4 KB

1import * as Cause from "effect/Cause";
2import * as DateTime from "effect/DateTime";
3import * as Exit from "effect/Exit";
4import * as Option from "effect/Option";
5import * as Result from "effect/Result";
6import * as Schema from "effect/Schema";
7import type {
8 PullRequestActor,
9 PullRequestCheck,
10 PullRequestCheckStatus,
11 PullRequestComment,
12 PullRequestCommit,
13 PullRequestMergeability,
14 PullRequestReviewThread,
15 PullRequestReviewerCandidate,
16 PullRequestState,
17} from "@t3tools/contracts";
18import { TrimmedNonEmptyString } from "@t3tools/contracts";
19import { decodeJsonResult } from "@t3tools/shared/schemaJson";
20​
21import { dedupeChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
22​
23/** Unknown enum values must not fail the whole payload. */
24const RawUserSchema = Schema.Struct({
25 /** Reviewer writes require UUIDs, not displayed handles. */
26 uuid: Schema.optional(Schema.NullOr(Schema.String)),
27 /** App accounts omit this; use `display_name`. */
28 nickname: Schema.optional(Schema.NullOr(Schema.String)),
29 display_name: Schema.optional(Schema.NullOr(Schema.String)),
30 links: Schema.optional(
31 Schema.NullOr(
32 Schema.Struct({
33 avatar: Schema.optional(
34 Schema.NullOr(Schema.Struct({ href: Schema.optional(Schema.String) })),
35 ),
36 }),
37 ),
38 ),
39});
40​
41const RawBranchSchema = Schema.Struct({
42 branch: Schema.Struct({ name: TrimmedNonEmptyString }),
43 commit: Schema.optional(
44 Schema.NullOr(Schema.Struct({ hash: Schema.optional(Schema.NullOr(Schema.String)) })),
45 ),
46 repository: Schema.optional(Schema.NullOr(Schema.Struct({ full_name: TrimmedNonEmptyString }))),
47});
48​
49const RawLinkSchema = Schema.Struct({ href: Schema.optional(Schema.String) });
50​
51const RawPullRequestSchema = Schema.Struct({
52 id: Schema.Int,
53 title: Schema.String,
54 description: Schema.optional(Schema.NullOr(Schema.String)),
55 state: Schema.optional(Schema.NullOr(Schema.String)),
56 draft: Schema.optional(Schema.Boolean),
57 author: Schema.optional(Schema.NullOr(RawUserSchema)),
58 source: RawBranchSchema,
59 destination: RawBranchSchema,
60 created_on: Schema.String,
61 updated_on: Schema.String,
62 /** Only sent when asked for with `fields=+closed_on`; null while the request is open. */
63 closed_on: Schema.optional(Schema.NullOr(Schema.String)),
64 reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))),
65 participants: Schema.optional(
66 Schema.NullOr(
67 Schema.Array(
68 Schema.Struct({
69 user: Schema.optional(Schema.NullOr(RawUserSchema)),
70 role: Schema.optional(Schema.NullOr(Schema.String)),
71 approved: Schema.optional(Schema.Boolean),
72 state: Schema.optional(Schema.NullOr(Schema.String)),
73 participated_on: Schema.optional(Schema.NullOr(Schema.String)),
74 }),
75 ),
76 ),
77 ),
78 links: Schema.Struct({ html: Schema.Struct({ href: TrimmedNonEmptyString }) }),
79});
80​
81const RawPageSchema = Schema.Struct({
82 values: Schema.Array(Schema.Unknown),
83 size: Schema.optional(Schema.NullOr(Schema.Int)),
84 next: Schema.optional(Schema.NullOr(Schema.String)),
85});
86​
87const RawCommentSchema = Schema.Struct({
88 id: Schema.Int,
89 content: Schema.optional(Schema.NullOr(Schema.Struct({ raw: Schema.optional(Schema.String) }))),
90 user: Schema.optional(Schema.NullOr(RawUserSchema)),
91 created_on: Schema.String,
92 deleted: Schema.optional(Schema.Boolean),
93 pending: Schema.optional(Schema.Boolean),
94 parent: Schema.optional(Schema.NullOr(Schema.Struct({ id: Schema.Int }))),
95 inline: Schema.optional(
96 Schema.NullOr(
97 Schema.Struct({
98 path: Schema.optional(Schema.NullOr(Schema.String)),
99 from: Schema.optional(Schema.NullOr(Schema.Int)),
100 to: Schema.optional(Schema.NullOr(Schema.Int)),
101 outdated: Schema.optional(Schema.NullOr(Schema.Boolean)),
102 }),
103 ),
104 ),
105 resolution: Schema.optional(Schema.NullOr(Schema.Unknown)),
106 links: Schema.optional(
107 Schema.NullOr(Schema.Struct({ html: Schema.optional(Schema.NullOr(RawLinkSchema)) })),
108 ),
109});
110​
111const RawCommitSchema = Schema.Struct({
112 hash: TrimmedNonEmptyString,
113 message: Schema.optional(Schema.NullOr(Schema.String)),
114 date: Schema.optional(Schema.NullOr(Schema.String)),
115 author: Schema.optional(
116 Schema.NullOr(
117 Schema.Struct({
118 raw: Schema.optional(Schema.NullOr(Schema.String)),
119 user: Schema.optional(Schema.NullOr(RawUserSchema)),
120 }),
121 ),
122 ),
123});
124​
125const RawStatusSchema = Schema.Struct({
126 key: Schema.optional(Schema.NullOr(Schema.String)),
127 name: Schema.optional(Schema.NullOr(Schema.String)),
128 state: Schema.optional(Schema.NullOr(Schema.String)),
129 description: Schema.optional(Schema.NullOr(Schema.String)),
130 url: Schema.optional(Schema.NullOr(Schema.String)),
131});
132​
133const RawDiffstatSchema = Schema.Struct({
134 lines_added: Schema.optional(Schema.NullOr(Schema.Int)),
135 lines_removed: Schema.optional(Schema.NullOr(Schema.Int)),
136});
137​
138const RawMemberSchema = Schema.Struct({
139 user: Schema.optional(Schema.NullOr(RawUserSchema)),
140});
141​
142const RawViewerSchema = Schema.Struct({
143 nickname: Schema.optional(Schema.NullOr(Schema.String)),
144 display_name: Schema.optional(Schema.NullOr(Schema.String)),
145});
146​
147const RawRepositoryPermissionsSchema = Schema.Struct({
148 values: Schema.optional(
149 Schema.NullOr(
150 Schema.Array(Schema.Struct({ permission: Schema.optional(Schema.NullOr(Schema.String)) })),
151 ),
152 ),
153});
154​
155export interface BitbucketPullRequest {
156 readonly number: number;
157 readonly title: string;
158 readonly url: string;
159 readonly author: PullRequestActor | null;
160 readonly headBranch: string;
161 readonly headSha: string | null;
162 readonly headRepositoryNameWithOwner: string | null;
163 readonly baseBranch: string;
164 readonly state: PullRequestState;
165 readonly isDraft: boolean;
166 /** Listings omit conflict state; detail reads use the conflicts endpoint. */
167 readonly mergeability: PullRequestMergeability;
168 readonly createdAt: string;
169 readonly updatedAt: string;
170 /** Merge/decline time; later comments move `updatedAt`. */
171 readonly closedAt: string | null;
172 readonly body: string;
173 readonly reviewRequestLogins: ReadonlyArray<string>;
174 readonly reviewers: ReadonlyArray<PullRequestActor>;
175 readonly reviewerIds: ReadonlyArray<string>;
176 readonly reviews: ReadonlyArray<PullRequestComment>;
178​
179function trimmed(value: string | null | undefined): string | null {
180 const text = value?.trim() ?? "";
181 return text.length > 0 ? text : null;
183​
184/** Normalize Bitbucket's microsecond `+00:00` timestamps to `Z` for cross-host string sorting. */
185function toIsoUtc(value: string): string {
186 return Option.match(DateTime.make(value), {
187 onNone: () => value,
188 onSome: DateTime.formatIso,
189 });
191​
192function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefined) {
193 const login = trimmed(raw?.nickname) ?? trimmed(raw?.display_name);
194 return login === null
195 ? null
196 : {
197 login,
198 name: trimmed(raw?.display_name),
199 avatarUrl: trimmed(raw?.links?.avatar?.href),
200 };
202​
203function toState(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): PullRequestState {
204 switch (raw.state?.trim().toUpperCase()) {
205 case "MERGED":
206 return "merged";
207 case "DECLINED":
208 case "SUPERSEDED":
209 return "closed";
210 default:
211 return "open";
212 }
214​
215function toBuildStatus(value: string | null | undefined): PullRequestCheckStatus {
216 switch (value?.trim().toUpperCase()) {
217 case "SUCCESSFUL":
218 return "success";
219 case "FAILED":
220 return "failure";
221 case "STOPPED":
222 return "cancelled";
223 case "INPROGRESS":
224 return "pending";
225 default:
226 return "neutral";
227 }
229​
230function toReviews(
231 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
232): ReadonlyArray<PullRequestComment> {
233 return (raw.participants ?? []).flatMap((participant): ReadonlyArray<PullRequestComment> => {
234 const author = toActor(participant.user);
235 const votedAt = trimmed(participant.participated_on);
236 const reviewState =
237 trimmed(participant.state) ?? (participant.approved === true ? "approved" : null);
238 if (author === null || votedAt === null || reviewState === null) return [];
239 return [
240 {
241 id: `${raw.id}:${author.login}`,
242 kind: "review",
243 author,
244 body: "",
245 createdAt: toIsoUtc(votedAt),
246 url: null,
247 path: null,
248 reviewState,
249 },
250 ];
251 });
253​
254function toPullRequest(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): BitbucketPullRequest {
255 const reviewers = (raw.reviewers ?? []).flatMap((reviewer) => {
256 const actor = toActor(reviewer);
257 return actor === null ? [] : [actor];
258 });
259 return {
260 number: raw.id,
261 title: raw.title,
262 url: raw.links.html.href,
263 author: toActor(raw.author),
264 headBranch: raw.source.branch.name,
265 headSha: trimmed(raw.source.commit?.hash),
266 headRepositoryNameWithOwner: raw.source.repository?.full_name ?? null,
267 baseBranch: raw.destination.branch.name,
268 state: toState(raw),
269 isDraft: raw.draft ?? false,
270 mergeability: "unknown",
271 createdAt: toIsoUtc(raw.created_on),
272 updatedAt: toIsoUtc(raw.updated_on),
273 closedAt: raw.closed_on == null ? null : toIsoUtc(raw.closed_on),
274 body: raw.description ?? "",
275 reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),
276 reviewers,
277 reviewerIds: (raw.reviewers ?? []).flatMap((reviewer) => trimmed(reviewer.uuid) ?? []),
278 reviews: toReviews(raw),
279 };
281​
282const decodePage = decodeJsonResult(RawPageSchema);
283const decodePullRequestEntry = Schema.decodeUnknownExit(RawPullRequestSchema);
284const decodePullRequest = decodeJsonResult(RawPullRequestSchema);
285const decodeCommentEntry = Schema.decodeUnknownExit(RawCommentSchema);
286const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema);
287const decodeStatusEntry = Schema.decodeUnknownExit(RawStatusSchema);
288const decodeDiffstatEntry = Schema.decodeUnknownExit(RawDiffstatSchema);
289const decodeMemberEntry = Schema.decodeUnknownExit(RawMemberSchema);
290const decodeViewer = decodeJsonResult(RawViewerSchema);
291const decodeConflicts = decodeJsonResult(RawPageSchema);
292const decodeRepositoryPermissions = decodeJsonResult(RawRepositoryPermissionsSchema);
293​
294type DecodeFailure = Cause.Cause<Schema.SchemaError>;
295​
296export interface BitbucketPage<A> {
297 readonly items: ReadonlyArray<A>;
298 readonly next: string | null;
300​
301export function decodePullRequestPageJson(
302 raw: string,
303): Result.Result<BitbucketPage<BitbucketPullRequest>, DecodeFailure> {
304 const decoded = decodePage(raw);
305 if (!Result.isSuccess(decoded)) {
306 return Result.fail(decoded.failure);
307 }
308 const items: BitbucketPullRequest[] = [];
309 for (const entry of decoded.success.values) {
310 const item = decodePullRequestEntry(entry);
311 if (Exit.isSuccess(item)) {
312 items.push(toPullRequest(item.value));
313 }
314 }
315 return Result.succeed({ items, next: trimmed(decoded.success.next) });
317​
318export function decodePullRequestJson(
319 raw: string,
320): Result.Result<BitbucketPullRequest, DecodeFailure> {
321 const decoded = decodePullRequest(raw);
322 return Result.isSuccess(decoded)
323 ? Result.succeed(toPullRequest(decoded.success))
324 : Result.fail(decoded.failure);
326​
327export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
328 const decoded = decodeViewer(raw);
329 return Result.isSuccess(decoded)
330 ? Result.succeed(trimmed(decoded.success.nickname) ?? trimmed(decoded.success.display_name))
331 : Result.fail(decoded.failure);
333​
334export function decodeRepositoryPermissionJson(raw: string): Result.Result<boolean, DecodeFailure> {
335 const decoded = decodeRepositoryPermissions(raw);
336 if (!Result.isSuccess(decoded)) {
337 return Result.fail(decoded.failure);
338 }
339 const permission = trimmed(decoded.success.values?.[0]?.permission)?.toLowerCase() ?? null;
340 return Result.succeed(permission === null || permission === "admin" || permission === "write");
342​
343/** Repository membership requires admin access; reviews can target any workspace member. */
344export function decodeWorkspaceMembersJson(
345 raw: string,
346): Result.Result<BitbucketPage<PullRequestReviewerCandidate>, DecodeFailure> {
347 const decoded = decodePage(raw);
348 if (!Result.isSuccess(decoded)) {
349 return Result.fail(decoded.failure);
350 }
351 const items: PullRequestReviewerCandidate[] = [];
352 for (const entry of decoded.success.values) {
353 const member = decodeMemberEntry(entry);
354 if (Exit.isFailure(member)) continue;
355 const uuid = trimmed(member.value.user?.uuid);
356 const actor = toActor(member.value.user);
357 if (uuid === null || actor === null) continue;
358 items.push({ ...actor, id: uuid, kind: "user", isRequested: false });
359 }
360 return Result.succeed({ items, next: trimmed(decoded.success.next) });
362​
363export type BitbucketRawComment = Schema.Schema.Type<typeof RawCommentSchema>;
364​
365export interface BitbucketComments {
366 readonly comments: ReadonlyArray<PullRequestComment>;
367 /** Raw entries for thread assembly across page boundaries. */
368 readonly entries: ReadonlyArray<BitbucketRawComment>;
369 readonly next: string | null;
371​
372export function buildReviewThreads(
373 comments: ReadonlyArray<BitbucketRawComment>,
374): ReadonlyArray<PullRequestReviewThread> {
375 const byId = new Map(comments.map((comment) => [comment.id, comment]));
376 const rootOf = (comment: Schema.Schema.Type<typeof RawCommentSchema>) => {
377 let current = comment;
378 for (let step = 0; step < byId.size; step += 1) {
379 const parent = current.parent === null ? undefined : byId.get(current.parent?.id ?? -1);
380 if (parent === undefined) return current;
381 current = parent;
382 }
383 return current;
384 };
385​
386 const threads = new Map<number, PullRequestReviewThread>();
387 const replies = new Map<number, Array<Schema.Schema.Type<typeof RawCommentSchema>>>();
388 for (const comment of comments) {
389 const root = rootOf(comment);
390 const inline = root.inline;
391 const path = trimmed(inline?.path);
392 if (path === null) continue;
393 if (root.id === comment.id) {
394 const side = inline?.to === null || inline?.to === undefined ? "left" : "right";
395 const line = side === "left" ? inline?.from : inline?.to;
396 threads.set(root.id, {
397 id: String(root.id),
398 path,
399 line: typeof line === "number" && line > 0 ? line : null,
400 side,
401 isResolved: root.resolution !== null && root.resolution !== undefined,
402 isOutdated: inline?.outdated === true,
403 comments: [],
404 });
405 }
406 const bucket = replies.get(root.id);
407 if (bucket === undefined) replies.set(root.id, [comment]);
408 else bucket.push(comment);
409 }
410​
411 return [...threads.values()].flatMap((thread) => {
412 const entries = (replies.get(Number(thread.id)) ?? [])
413 .toSorted((left, right) => left.created_on.localeCompare(right.created_on))
414 .map((comment) => ({
415 id: String(comment.id),
416 author: toActor(comment.user),
417 body: comment.content?.raw ?? "",
418 createdAt: toIsoUtc(comment.created_on),
419 url: trimmed(comment.links?.html?.href),
420 }));
421 return entries.length === 0 ? [] : [{ ...thread, comments: entries }];
422 });
424​
425export function decodeCommentsJson(raw: string): Result.Result<BitbucketComments, DecodeFailure> {
426 const decoded = decodePage(raw);
427 if (!Result.isSuccess(decoded)) {
428 return Result.fail(decoded.failure);
429 }
430 const comments: PullRequestComment[] = [];
431 const kept: Array<BitbucketRawComment> = [];
432 for (const entry of decoded.success.values) {
433 const decodedComment = decodeCommentEntry(entry);
434 if (Exit.isFailure(decodedComment)) continue;
435 const comment = decodedComment.value;
436 if (comment.deleted === true || comment.pending === true) continue;
437 const body = comment.content?.raw ?? "";
438 if (body.trim().length === 0) continue;
439 kept.push(comment);
440 const path = trimmed(comment.inline?.path);
441 comments.push({
442 id: String(comment.id),
443 kind: path === null ? "issue-comment" : "review-comment",
444 author: toActor(comment.user),
445 body,
446 createdAt: toIsoUtc(comment.created_on),
447 url: trimmed(comment.links?.html?.href),
448 path,
449 reviewState: null,
450 });
451 }
452 return Result.succeed({ comments, entries: kept, next: trimmed(decoded.success.next) });
454​
455export function decodeCommitsJson(
456 raw: string,
457): Result.Result<BitbucketPage<PullRequestCommit>, DecodeFailure> {
458 const decoded = decodePage(raw);
459 if (!Result.isSuccess(decoded)) {
460 return Result.fail(decoded.failure);
461 }
462 const commits: PullRequestCommit[] = [];
463 for (const entry of decoded.success.values) {
464 const decodedCommit = decodeCommitEntry(entry);
465 if (Exit.isFailure(decodedCommit)) continue;
466 const commit = decodedCommit.value;
467 const committedDate = trimmed(commit.date);
468 if (committedDate === null) continue;
469 const linkedAuthor = toActor(commit.author?.user);
470 const rawAuthor = trimmed(commit.author?.raw);
471 commits.push({
472 oid: commit.hash,
473 messageHeadline: (commit.message ?? "").split("\n")[0] ?? "",
474 committedDate: toIsoUtc(committedDate),
475 authors:
476 linkedAuthor !== null
477 ? [linkedAuthor]
478 : rawAuthor === null
479 ? []
480 : [{ login: rawAuthor, name: rawAuthor, avatarUrl: null }],
481 });
482 }
483 // Bitbucket lists a pull request's commits newest first; the timeline reads oldest first.
484 return Result.succeed({ items: commits.toReversed(), next: trimmed(decoded.success.next) });
486​
487export function decodeStatusesJson(
488 raw: string,
489): Result.Result<BitbucketPage<PullRequestCheck>, DecodeFailure> {
490 const decoded = decodePage(raw);
491 if (!Result.isSuccess(decoded)) {
492 return Result.fail(decoded.failure);
493 }
494 const checks: Array<{
495 readonly check: PullRequestCheck;
496 readonly workflowName: string | null;
497 readonly at: string | null;
498 }> = [];
499 for (const entry of decoded.success.values) {
500 const decodedStatus = decodeStatusEntry(entry);
501 if (Exit.isFailure(decodedStatus)) continue;
502 const status = decodedStatus.value;
503 const name = trimmed(status.name) ?? trimmed(status.key);
504 if (name === null) continue;
505 // Reruns reuse keys; later entries win. Keys distinguish same-named pipelines.
506 checks.push({
507 check: {
508 name,
509 status: toBuildStatus(status.state),
510 description: trimmed(status.description),
511 url: trimmed(status.url),
512 },
513 workflowName: trimmed(status.key),
514 at: null,
515 });
516 }
517 return Result.succeed({ items: dedupeChecks(checks), next: trimmed(decoded.success.next) });
519​
520export interface BitbucketDiffStat {
521 readonly additions: number;
522 readonly deletions: number;
523 readonly changedFiles: number;
525​
526export interface BitbucketDiffStatPage extends BitbucketDiffStat {
527 readonly next: string | null;
529​
530export function decodeDiffstatJson(
531 raw: string,
532): Result.Result<BitbucketDiffStatPage, DecodeFailure> {
533 const decoded = decodePage(raw);
534 if (!Result.isSuccess(decoded)) {
535 return Result.fail(decoded.failure);
536 }
537 let additions = 0;
538 let deletions = 0;
539 let changedFiles = 0;
540 for (const entry of decoded.success.values) {
541 const decodedStat = decodeDiffstatEntry(entry);
542 if (Exit.isFailure(decodedStat)) continue;
543 additions += decodedStat.value.lines_added ?? 0;
544 deletions += decodedStat.value.lines_removed ?? 0;
545 changedFiles += 1;
546 }
547 return Result.succeed({
548 additions,
549 deletions,
550 changedFiles,
551 next: trimmed(decoded.success.next),
552 });
554​
555export function decodeConflictsJson(
556 raw: string,
557): Result.Result<PullRequestMergeability, DecodeFailure> {
558 const decoded = decodeConflicts(raw);
559 return Result.isSuccess(decoded)
560 ? Result.succeed(decoded.success.values.length === 0 ? "mergeable" : "conflicting")
561 : Result.fail(decoded.failure);