The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { trimOptionalString as trimmed } from "@t3tools/source-control-core/server/pullRequestUtils"; |
| 2 | import * as Cause from "effect/Cause"; |
| 3 | import * as Exit from "effect/Exit"; |
| 4 | import * as Result from "effect/Result"; |
| 5 | import * as Schema from "effect/Schema"; |
| 6 | import { GraphQL } from "effect/graphql"; |
| 7 | import type { |
| 8 | PullRequestStackMembership, |
| 9 | PullRequestActor, |
| 10 | PullRequestReferenceCandidate, |
| 11 | PullRequestPreview, |
| 12 | PullRequestCheck, |
| 13 | PullRequestCheckStatus, |
| 14 | PullRequestChecksState, |
| 15 | PullRequestComment, |
| 16 | PullRequestCommit, |
| 17 | PullRequestFileViewedState, |
| 18 | PullRequestLabel, |
| 19 | PullRequestMergeCapabilities, |
| 20 | PullRequestMergeMethod, |
| 21 | PullRequestMergeQueueRemoval, |
| 22 | PullRequestOmittedFileStat, |
| 23 | PullRequestMergeability, |
| 24 | PullRequestReaction, |
| 25 | PullRequestReactionContent, |
| 26 | PullRequestReviewCommentDraft, |
| 27 | PullRequestReviewDecision, |
| 28 | PullRequestReviewPosition, |
| 29 | PullRequestReviewThread, |
| 30 | PullRequestReviewVerdict, |
| 31 | PullRequestReviewerCandidate, |
| 32 | PullRequestReviewerCandidateList, |
| 33 | PullRequestReviewerKind, |
| 34 | PullRequestLabelCandidate, |
| 35 | PullRequestLabelCandidateList, |
| 36 | PullRequestState, |
| 37 | PullRequestThreadComment, |
| 38 | } from "@t3tools/contracts"; |
| 39 | import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath"; |
| 40 | import { decodeJsonResult } from "@t3tools/shared/schemaJson"; |
| 41 | import { |
| 42 | dedupeChecks, |
| 43 | rollupCheckStatuses, |
| 44 | } from "@t3tools/source-control-core/server/pullRequestChecks"; |
| 45 | import type { ProviderChangeRequestSummary } from "@t3tools/source-control-core/server/PullRequestProvider"; |
| 46 | |
| 47 | import type * as GitHubSchema from "../../schema/github.graphql.ts"; |
| 48 | import type { |
| 49 | PullRequestSummaryRepositoryPullRequestPullRequest as SummarizedPullRequest, |
| 50 | PullRequestWatchFingerprintRepositoryPullRequestPullRequest as WatchedPullRequest, |
| 51 | } from "./pullRequestBatches.graphql.ts"; |
| 52 | import { |
| 53 | PageInfo as ListingPageInfo, |
| 54 | PullRequestList, |
| 55 | PullRequestRow, |
| 56 | PullRequestSearch, |
| 57 | } from "./pullRequestListings.graphql.ts"; |
| 58 | import type { PullRequestActionSummary } from "./pullRequestMutations.graphql.ts"; |
| 59 | import type { |
| 60 | CheckContext, |
| 61 | LabelCandidates, |
| 62 | PullRequestActivity, |
| 63 | PullRequestCommitStats, |
| 64 | PullRequestCheckContexts, |
| 65 | PullRequestCore, |
| 66 | PullRequestFilesViewed, |
| 67 | PullRequestFileStats, |
| 68 | PullRequestHeads, |
| 69 | PullRequestPreview as PullRequestPreviewQuery, |
| 70 | PullRequestSubject, |
| 71 | RepositoryAuthors, |
| 72 | RepositoryLabels, |
| 73 | RepositoryReferences, |
| 74 | ReferenceCandidate, |
| 75 | ReviewerCandidates, |
| 76 | ViewerPermissions, |
| 77 | } from "./pullRequestReads.graphql.ts"; |
| 78 | import type { |
| 79 | ReactionGroup, |
| 80 | ReviewDismissals, |
| 81 | ReviewThreadComments, |
| 82 | ReviewThreadPage, |
| 83 | ReviewThreadPages, |
| 84 | ReviewThreads, |
| 85 | ThreadComment, |
| 86 | } from "./pullRequestReviews.graphql.ts"; |
| 87 | |
| 88 | interface ActorFields { |
| 89 | readonly __typename?: string | undefined; |
| 90 | readonly login?: string | null | undefined; |
| 91 | readonly name?: string | null | undefined; |
| 92 | readonly avatarUrl?: string | null | undefined; |
| 93 | } |
| 94 | |
| 95 | interface ListItemFields { |
| 96 | readonly number: number; |
| 97 | readonly title: string; |
| 98 | readonly url: string; |
| 99 | readonly author?: ActorFields | null | undefined; |
| 100 | readonly headRefName: string; |
| 101 | readonly baseRefName: string; |
| 102 | readonly state?: string | null | undefined; |
| 103 | readonly isDraft?: boolean | undefined; |
| 104 | readonly mergeable?: string | null | undefined; |
| 105 | readonly reviewDecision?: string | null | undefined; |
| 106 | readonly additions?: number | undefined; |
| 107 | readonly deletions?: number | undefined; |
| 108 | readonly createdAt: string; |
| 109 | readonly updatedAt: string; |
| 110 | readonly mergedAt?: string | null | undefined; |
| 111 | readonly reviewRequests?: ReadonlyArray<ReviewRequestFields> | undefined; |
| 112 | readonly latestReviews?: ReadonlyArray<LatestReviewFields> | undefined; |
| 113 | readonly labels?: ReadonlyArray<LabelFields> | undefined; |
| 114 | readonly statusCheckRollup?: ReadonlyArray<CheckFields> | null | undefined; |
| 115 | } |
| 116 | |
| 117 | interface LabelFields { |
| 118 | readonly name: string; |
| 119 | readonly color?: string | null | undefined; |
| 120 | readonly description?: string | null | undefined; |
| 121 | } |
| 122 | |
| 123 | interface ReviewRequestFields { |
| 124 | readonly login?: string | null | undefined; |
| 125 | readonly slug?: string | null | undefined; |
| 126 | readonly name?: string | null | undefined; |
| 127 | } |
| 128 | |
| 129 | interface LatestReviewFields { |
| 130 | readonly state?: string | null | undefined; |
| 131 | readonly isMinimized?: boolean | undefined; |
| 132 | } |
| 133 | |
| 134 | /** Check runs use status/conclusion; commit statuses use a single state. */ |
| 135 | interface CheckFields { |
| 136 | readonly name?: string | null | undefined; |
| 137 | readonly context?: string | null | undefined; |
| 138 | readonly status?: string | null | undefined; |
| 139 | readonly conclusion?: string | null | undefined; |
| 140 | readonly state?: string | null | undefined; |
| 141 | readonly description?: string | null | undefined; |
| 142 | readonly detailsUrl?: string | null | undefined; |
| 143 | readonly targetUrl?: string | null | undefined; |
| 144 | /** Empty for app-owned runs; absent for commit statuses. */ |
| 145 | readonly workflowName?: string | null | undefined; |
| 146 | readonly startedAt?: string | null | undefined; |
| 147 | readonly completedAt?: string | null | undefined; |
| 148 | /** Branch protection requires this check; asked for on github.com only. */ |
| 149 | readonly isRequired?: boolean | null | undefined; |
| 150 | } |
| 151 | |
| 152 | interface PageInfoFields { |
| 153 | readonly hasNextPage?: boolean | undefined; |
| 154 | readonly endCursor?: string | null | undefined; |
| 155 | } |
| 156 | |
| 157 | function nodesOf<A>( |
| 158 | connection: { readonly nodes?: ReadonlyArray<A | null> | null | undefined } | null | undefined, |
| 159 | ): ReadonlyArray<A> { |
| 160 | return (connection?.nodes ?? []).flatMap((node) => (node === null ? [] : [node])); |
| 161 | } |
| 162 | |
| 163 | const REACTION_CONTENT_BY_GITHUB: Readonly<Record<string, PullRequestReactionContent>> = { |
| 164 | THUMBS_UP: "thumbs-up", |
| 165 | THUMBS_DOWN: "thumbs-down", |
| 166 | LAUGH: "laugh", |
| 167 | HOORAY: "hooray", |
| 168 | CONFUSED: "confused", |
| 169 | HEART: "heart", |
| 170 | ROCKET: "rocket", |
| 171 | EYES: "eyes", |
| 172 | }; |
| 173 | |
| 174 | const GITHUB_REACTION_BY_CONTENT: Readonly< |
| 175 | Record<PullRequestReactionContent, GitHubSchema.ReactionContent> |
| 176 | > = { |
| 177 | "thumbs-up": "THUMBS_UP", |
| 178 | "thumbs-down": "THUMBS_DOWN", |
| 179 | laugh: "LAUGH", |
| 180 | hooray: "HOORAY", |
| 181 | confused: "CONFUSED", |
| 182 | heart: "HEART", |
| 183 | rocket: "ROCKET", |
| 184 | eyes: "EYES", |
| 185 | }; |
| 186 | |
| 187 | export function gitHubReactionContent( |
| 188 | content: PullRequestReactionContent, |
| 189 | ): GitHubSchema.ReactionContent { |
| 190 | return GITHUB_REACTION_BY_CONTENT[content]; |
| 191 | } |
| 192 | |
| 193 | /** Keep the viewer in counts, not actors, to avoid duplicating 'You'. */ |
| 194 | export function toReactions( |
| 195 | groups: ReadonlyArray<ReactionGroup> | null | undefined, |
| 196 | viewer: string | null, |
| 197 | ): ReadonlyArray<PullRequestReaction> { |
| 198 | const normalizedViewer = viewer?.toLowerCase() ?? null; |
| 199 | const reactions: PullRequestReaction[] = []; |
| 200 | for (const group of groups ?? []) { |
| 201 | const content = REACTION_CONTENT_BY_GITHUB[trimmed(group.content)?.toUpperCase() ?? ""]; |
| 202 | if (content === undefined) continue; |
| 203 | const logins = nodesOf(group.reactors).flatMap((node) => |
| 204 | "login" in node ? (trimmed(node.login) ?? []) : [], |
| 205 | ); |
| 206 | const count = Math.max(group.reactors.totalCount, logins.length); |
| 207 | if (count <= 0) continue; |
| 208 | const actors = |
| 209 | normalizedViewer === null |
| 210 | ? logins |
| 211 | : logins.filter((login) => login.toLowerCase() !== normalizedViewer); |
| 212 | reactions.push({ content, count, actors, viewerHasReacted: group.viewerHasReacted }); |
| 213 | } |
| 214 | return reactions; |
| 215 | } |
| 216 | |
| 217 | const RawWorkflowRunsSchema = Schema.Struct({ |
| 218 | workflow_runs: Schema.Array( |
| 219 | Schema.Struct({ |
| 220 | id: Schema.Int, |
| 221 | name: Schema.optional(Schema.NullOr(Schema.String)), |
| 222 | html_url: Schema.optional(Schema.NullOr(Schema.String)), |
| 223 | status: Schema.optional(Schema.NullOr(Schema.String)), |
| 224 | }), |
| 225 | ), |
| 226 | }); |
| 227 | |
| 228 | const RawPullRequestFileSchema = Schema.Struct({ |
| 229 | filename: Schema.String, |
| 230 | status: Schema.optional(Schema.NullOr(Schema.String)), |
| 231 | previous_filename: Schema.optional(Schema.NullOr(Schema.String)), |
| 232 | patch: Schema.optional(Schema.NullOr(Schema.String)), |
| 233 | additions: Schema.optional(Schema.NullOr(Schema.Int)), |
| 234 | deletions: Schema.optional(Schema.NullOr(Schema.Int)), |
| 235 | }); |
| 236 | |
| 237 | export function toPullRequestPreview( |
| 238 | result: PullRequestPreviewQuery.Result, |
| 239 | ): Omit<PullRequestPreview, "projectId" | "repository"> | null { |
| 240 | const pullRequest = result.repository?.pullRequest; |
| 241 | if (pullRequest == null) return null; |
| 242 | return { |
| 243 | ...pullRequest, |
| 244 | author: toActor(pullRequest.author), |
| 245 | state: toState(pullRequest), |
| 246 | }; |
| 247 | } |
| 248 | |
| 249 | /** Search rejects first > 100 with EXCESSIVE_PAGINATION. */ |
| 250 | export const PULL_REQUEST_SEARCH_MAX_ROWS = 100; |
| 251 | |
| 252 | export function pageRows(rows: number): number { |
| 253 | return Math.min(Math.max(Math.trunc(rows), 1), PULL_REQUEST_SEARCH_MAX_ROWS); |
| 254 | } |
| 255 | |
| 256 | export function toPullRequestNodeId(result: { |
| 257 | readonly repository: { readonly pullRequest: { readonly id: string } | null } | null; |
| 258 | }): string | null { |
| 259 | return result.repository?.pullRequest?.id ?? null; |
| 260 | } |
| 261 | |
| 262 | export function isSubjectOfPullRequest(result: PullRequestSubject.Result): boolean { |
| 263 | const expected = result.repository?.pullRequest?.id ?? null; |
| 264 | const node = result.node; |
| 265 | const actual = |
| 266 | node === null |
| 267 | ? null |
| 268 | : node.__typename === "IssueComment" |
| 269 | ? (node.pullRequest?.id ?? null) |
| 270 | : node.__typename === "PullRequestReviewComment" |
| 271 | ? node.reviewCommentPullRequest.id |
| 272 | : node.__typename === "PullRequestReview" |
| 273 | ? node.reviewPullRequest.id |
| 274 | : node.id; |
| 275 | return expected !== null && actual !== null && expected === actual; |
| 276 | } |
| 277 | |
| 278 | const ReviewSubmissionSchema = Schema.Struct({ |
| 279 | event: Schema.Literals(["COMMENT", "APPROVE", "REQUEST_CHANGES"]), |
| 280 | body: Schema.String, |
| 281 | comments: Schema.Array( |
| 282 | Schema.Struct({ |
| 283 | path: Schema.String, |
| 284 | start_line: Schema.optional(Schema.Int), |
| 285 | start_side: Schema.optional(Schema.Literals(["LEFT", "RIGHT"])), |
| 286 | line: Schema.Int, |
| 287 | side: Schema.Literals(["LEFT", "RIGHT"]), |
| 288 | body: Schema.String, |
| 289 | }), |
| 290 | ), |
| 291 | }); |
| 292 | |
| 293 | const REVIEW_EVENTS: Record<PullRequestReviewVerdict, "COMMENT" | "APPROVE" | "REQUEST_CHANGES"> = { |
| 294 | comment: "COMMENT", |
| 295 | approve: "APPROVE", |
| 296 | "request-changes": "REQUEST_CHANGES", |
| 297 | }; |
| 298 | |
| 299 | function gitHubReviewPosition(position: PullRequestReviewPosition): { |
| 300 | readonly line: number; |
| 301 | readonly side: "LEFT" | "RIGHT"; |
| 302 | } { |
| 303 | switch (position.kind) { |
| 304 | case "added": |
| 305 | return { line: position.newLine, side: "RIGHT" }; |
| 306 | case "deleted": |
| 307 | return { line: position.oldLine, side: "LEFT" }; |
| 308 | case "context": |
| 309 | return position.side === "left" |
| 310 | ? { line: position.oldLine, side: "LEFT" } |
| 311 | : { line: position.newLine, side: "RIGHT" }; |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | export function buildReviewSubmission(input: { |
| 316 | readonly verdict: PullRequestReviewVerdict; |
| 317 | readonly body: string; |
| 318 | readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>; |
| 319 | }): typeof ReviewSubmissionSchema.Type { |
| 320 | return { |
| 321 | event: REVIEW_EVENTS[input.verdict], |
| 322 | body: input.body, |
| 323 | comments: input.comments.map((comment) => { |
| 324 | const end = gitHubReviewPosition(comment.position); |
| 325 | const start = |
| 326 | comment.startPosition === undefined ? null : gitHubReviewPosition(comment.startPosition); |
| 327 | // GitHub refuses a start that is the end itself, so a one-line range is sent as one line. |
| 328 | const ranged = start !== null && (start.line !== end.line || start.side !== end.side); |
| 329 | return { |
| 330 | path: comment.path, |
| 331 | ...(ranged ? { start_line: start.line, start_side: start.side } : {}), |
| 332 | ...end, |
| 333 | body: comment.body, |
| 334 | }; |
| 335 | }), |
| 336 | }; |
| 337 | } |
| 338 | |
| 339 | export interface GitHubPullRequestListItem { |
| 340 | readonly stack?: PullRequestStackMembership; |
| 341 | readonly number: number; |
| 342 | readonly title: string; |
| 343 | readonly url: string; |
| 344 | readonly author: PullRequestActor | null; |
| 345 | readonly headBranch: string; |
| 346 | readonly baseBranch: string; |
| 347 | readonly state: PullRequestState; |
| 348 | readonly isDraft: boolean; |
| 349 | readonly mergeability: PullRequestMergeability; |
| 350 | readonly reviewDecision: PullRequestReviewDecision | null; |
| 351 | readonly additions: number; |
| 352 | readonly deletions: number; |
| 353 | readonly createdAt: string; |
| 354 | readonly updatedAt: string; |
| 355 | readonly reviewRequestLogins: ReadonlyArray<string>; |
| 356 | readonly hasTeamReviewRequest: boolean; |
| 357 | readonly labels: ReadonlyArray<PullRequestLabel>; |
| 358 | readonly checksState: PullRequestChecksState | null; |
| 359 | } |
| 360 | |
| 361 | export interface GitHubPullRequestDetail extends GitHubPullRequestListItem { |
| 362 | readonly isCrossRepository?: boolean; |
| 363 | readonly headRepositoryOwner: string | null; |
| 364 | readonly headRepositoryNameWithOwner?: string | null; |
| 365 | readonly headSha?: string | null; |
| 366 | readonly body: string; |
| 367 | readonly changedFiles: number; |
| 368 | readonly mergedAt: string | null; |
| 369 | readonly closedAt: string | null; |
| 370 | readonly checks: ReadonlyArray<PullRequestCheck>; |
| 371 | readonly autoMergeEnabled?: boolean; |
| 372 | readonly autoMergeMethod?: PullRequestMergeMethod; |
| 373 | } |
| 374 | |
| 375 | export interface GitHubWorkflowRunApproval { |
| 376 | readonly id: number; |
| 377 | readonly name: string; |
| 378 | readonly url: string | null; |
| 379 | } |
| 380 | |
| 381 | export interface GitHubPullRequestHead { |
| 382 | readonly number: number; |
| 383 | readonly headSha: string; |
| 384 | readonly isCrossRepository?: boolean; |
| 385 | readonly headRepositoryOwner: string | null; |
| 386 | } |
| 387 | |
| 388 | export interface GitHubPullRequestActivity { |
| 389 | readonly author: PullRequestActor | null; |
| 390 | readonly comments: ReadonlyArray<PullRequestComment>; |
| 391 | readonly commits: ReadonlyArray<PullRequestCommit>; |
| 392 | readonly truncated: boolean; |
| 393 | } |
| 394 | |
| 395 | /** GitHub returns endCursor even on the last page; hasNextPage is authoritative. */ |
| 396 | function nextCursorOf(pageInfo: PageInfoFields | null | undefined): string | null { |
| 397 | return pageInfo?.hasNextPage === true ? trimmed(pageInfo.endCursor) : null; |
| 398 | } |
| 399 | |
| 400 | /** Defer unknown update access to the host; unknown authorship grants no author actions. */ |
| 401 | function toPullRequestViewerFields( |
| 402 | raw: |
| 403 | | { |
| 404 | readonly viewerCanUpdate?: boolean | undefined; |
| 405 | readonly viewerDidAuthor?: boolean | undefined; |
| 406 | } |
| 407 | | null |
| 408 | | undefined, |
| 409 | ): { readonly canUpdate: boolean; readonly didAuthor: boolean } { |
| 410 | return { canUpdate: raw?.viewerCanUpdate !== false, didAuthor: raw?.viewerDidAuthor === true }; |
| 411 | } |
| 412 | |
| 413 | function toActor(raw: ActorFields | null | undefined): PullRequestActor | null { |
| 414 | const login = trimmed(raw?.login); |
| 415 | return login === null |
| 416 | ? null |
| 417 | : { |
| 418 | login, |
| 419 | name: trimmed(raw?.name), |
| 420 | avatarUrl: trimmed(raw?.avatarUrl), |
| 421 | ...(raw?.__typename === "Bot" ? { isBot: true } : {}), |
| 422 | }; |
| 423 | } |
| 424 | |
| 425 | interface RequestedTeamFields { |
| 426 | readonly combinedSlug?: string | null | undefined; |
| 427 | readonly teamName?: string | null | undefined; |
| 428 | readonly teamAvatarUrl?: string | null | undefined; |
| 429 | } |
| 430 | |
| 431 | /** org/slug avoids collisions with user logins and verdicts. */ |
| 432 | function toRequestedTeam(raw: object | null | undefined): PullRequestActor | null { |
| 433 | if (raw == null || !("combinedSlug" in raw)) return null; |
| 434 | const team = raw as RequestedTeamFields; |
| 435 | const login = trimmed(team.combinedSlug); |
| 436 | return login === null |
| 437 | ? null |
| 438 | : { login, name: trimmed(team.teamName), avatarUrl: trimmed(team.teamAvatarUrl) }; |
| 439 | } |
| 440 | |
| 441 | function toCommitActor(raw: { |
| 442 | readonly email?: string | null | undefined; |
| 443 | readonly login?: string | null | undefined; |
| 444 | readonly name?: string | null | undefined; |
| 445 | }): PullRequestActor | null { |
| 446 | // Unlinked commit signatures have no login; preserve name/email so co-authors remain visible. |
| 447 | const login = trimmed(raw.login) ?? trimmed(raw.name) ?? trimmed(raw.email); |
| 448 | return login === null ? null : { login, name: trimmed(raw.name), avatarUrl: null }; |
| 449 | } |
| 450 | |
| 451 | function toGraphqlCommitActor(raw: { |
| 452 | readonly name?: string | null | undefined; |
| 453 | readonly avatarUrl?: string | null | undefined; |
| 454 | readonly user?: { readonly login?: string | null | undefined } | null | undefined; |
| 455 | }): PullRequestActor | null { |
| 456 | const login = trimmed(raw.user?.login) ?? trimmed(raw.name); |
| 457 | return login === null |
| 458 | ? null |
| 459 | : { login, name: trimmed(raw.name), avatarUrl: trimmed(raw.avatarUrl) }; |
| 460 | } |
| 461 | |
| 462 | function toState(raw: { |
| 463 | readonly state?: string | null | undefined; |
| 464 | readonly mergedAt?: string | null | undefined; |
| 465 | }): PullRequestState { |
| 466 | if (trimmed(raw.mergedAt) !== null) return "merged"; |
| 467 | const state = raw.state?.trim().toUpperCase(); |
| 468 | if (state === "MERGED") return "merged"; |
| 469 | if (state === "CLOSED") return "closed"; |
| 470 | return "open"; |
| 471 | } |
| 472 | |
| 473 | function toMergeability(value: string | null | undefined): PullRequestMergeability { |
| 474 | switch (value?.trim().toUpperCase()) { |
| 475 | case "MERGEABLE": |
| 476 | return "mergeable"; |
| 477 | case "CONFLICTING": |
| 478 | return "conflicting"; |
| 479 | default: |
| 480 | return "unknown"; |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | function toMergeMethod(value: string | null | undefined): PullRequestMergeMethod | undefined { |
| 485 | switch (value?.trim().toUpperCase()) { |
| 486 | case "MERGE": |
| 487 | return "merge"; |
| 488 | case "SQUASH": |
| 489 | return "squash"; |
| 490 | case "REBASE": |
| 491 | return "rebase"; |
| 492 | default: |
| 493 | return undefined; |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | export function toPullRequestActionSummary( |
| 498 | raw: PullRequestActionSummary | null | undefined, |
| 499 | ): ProviderChangeRequestSummary | undefined { |
| 500 | if (raw == null) return undefined; |
| 501 | const autoMergeMethod = toMergeMethod(raw.autoMergeRequest?.mergeMethod); |
| 502 | return { |
| 503 | number: raw.number, |
| 504 | title: raw.title, |
| 505 | url: raw.url, |
| 506 | headBranch: raw.headRefName, |
| 507 | baseBranch: raw.baseRefName, |
| 508 | state: toState(raw), |
| 509 | isDraft: raw.isDraft, |
| 510 | updatedAt: raw.updatedAt, |
| 511 | mergedAt: trimmed(raw.mergedAt), |
| 512 | closedAt: trimmed(raw.closedAt), |
| 513 | author: toActor(raw.author), |
| 514 | headSha: raw.headRefOid, |
| 515 | autoMergeEnabled: raw.autoMergeRequest !== null, |
| 516 | ...(autoMergeMethod === undefined ? {} : { autoMergeMethod }), |
| 517 | }; |
| 518 | } |
| 519 | |
| 520 | /** |
| 521 | * Prefer GitHub's reviewDecision; only use latest reviews when it is absent (e.g. bot approvals). |
| 522 | * A review a maintainer hid casts no verdict. |
| 523 | */ |
| 524 | function toReviewDecisionWithReviews( |
| 525 | value: string | null | undefined, |
| 526 | reviews: ReadonlyArray<LatestReviewFields> | undefined, |
| 527 | ): PullRequestReviewDecision | null { |
| 528 | const summarized = toReviewDecision(value); |
| 529 | if (summarized === "approved" || summarized === "changes-requested") return summarized; |
| 530 | const states = new Set( |
| 531 | (reviews ?? []) |
| 532 | .filter((review) => !review.isMinimized) |
| 533 | .map((review) => review.state?.trim().toUpperCase() ?? ""), |
| 534 | ); |
| 535 | if (states.has("CHANGES_REQUESTED")) return "changes-requested"; |
| 536 | if (summarized === null && states.has("APPROVED")) return "approved"; |
| 537 | return summarized; |
| 538 | } |
| 539 | |
| 540 | function toReviewDecision(value: string | null | undefined): PullRequestReviewDecision | null { |
| 541 | switch (value?.trim().toUpperCase()) { |
| 542 | case "APPROVED": |
| 543 | return "approved"; |
| 544 | case "CHANGES_REQUESTED": |
| 545 | return "changes-requested"; |
| 546 | case "REVIEW_REQUIRED": |
| 547 | return "review-required"; |
| 548 | default: |
| 549 | return null; |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | function toLabels(raw: ReadonlyArray<LabelFields> | undefined): ReadonlyArray<PullRequestLabel> { |
| 554 | return (raw ?? []).flatMap((label) => { |
| 555 | const name = trimmed(label.name); |
| 556 | return name === null |
| 557 | ? [] |
| 558 | : [{ name, color: trimmed(label.color), description: trimmed(label.description) }]; |
| 559 | }); |
| 560 | } |
| 561 | |
| 562 | function toReviewRequestLogins( |
| 563 | raw: ReadonlyArray<ReviewRequestFields> | undefined, |
| 564 | ): ReadonlyArray<string> { |
| 565 | return (raw ?? []).flatMap((request) => { |
| 566 | const login = trimmed(request.login); |
| 567 | return login === null ? [] : [login]; |
| 568 | }); |
| 569 | } |
| 570 | |
| 571 | function hasTeamReviewRequest(raw: ReadonlyArray<ReviewRequestFields> | undefined): boolean { |
| 572 | return (raw ?? []).some( |
| 573 | (request) => |
| 574 | trimmed(request.login) === null && |
| 575 | (trimmed(request.slug) !== null || trimmed(request.name) !== null), |
| 576 | ); |
| 577 | } |
| 578 | |
| 579 | function toCheckStatus(raw: CheckFields): PullRequestCheckStatus { |
| 580 | const status = raw.status?.trim().toUpperCase(); |
| 581 | if (status !== undefined && status !== "COMPLETED" && status !== "") { |
| 582 | return "pending"; |
| 583 | } |
| 584 | switch ((raw.conclusion ?? raw.state)?.trim().toUpperCase()) { |
| 585 | case "SUCCESS": |
| 586 | return "success"; |
| 587 | case "ACTION_REQUIRED": |
| 588 | return "action-required"; |
| 589 | case "FAILURE": |
| 590 | case "ERROR": |
| 591 | case "TIMED_OUT": |
| 592 | case "STARTUP_FAILURE": |
| 593 | return "failure"; |
| 594 | case "CANCELLED": |
| 595 | return "cancelled"; |
| 596 | case "SKIPPED": |
| 597 | return "skipped"; |
| 598 | case "PENDING": |
| 599 | case "EXPECTED": |
| 600 | return "pending"; |
| 601 | default: |
| 602 | return "neutral"; |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | /** GitHub's sentinel for timestamps not reached yet. */ |
| 607 | const UNSET_TIMESTAMP = "0001-01-01T00:00:00Z"; |
| 608 | |
| 609 | const STILL_RUNNING = "9999-12-31T23:59:59Z"; |
| 610 | |
| 611 | function realTimestamp(value: string | null | undefined): string | null { |
| 612 | const at = trimmed(value); |
| 613 | return at === null || at === UNSET_TIMESTAMP ? null : at; |
| 614 | } |
| 615 | |
| 616 | function isNamelessCheck(raw: CheckFields): boolean { |
| 617 | return trimmed(raw.name) === null && trimmed(raw.context) === null; |
| 618 | } |
| 619 | |
| 620 | /** Unfinished runs outrank finished runs of the same check across push/PR workflows. */ |
| 621 | function toCheckEntries(raw: ReadonlyArray<CheckFields> | null | undefined): ReadonlyArray<{ |
| 622 | readonly check: PullRequestCheck; |
| 623 | readonly workflowName: string | null; |
| 624 | readonly at: string | null; |
| 625 | }> { |
| 626 | return (raw ?? []).flatMap((check) => { |
| 627 | const name = trimmed(check.name) ?? trimmed(check.context); |
| 628 | if (name === null) return []; |
| 629 | const status = toCheckStatus(check); |
| 630 | return [ |
| 631 | { |
| 632 | check: { |
| 633 | name, |
| 634 | status, |
| 635 | description: trimmed(check.description), |
| 636 | url: trimmed(check.detailsUrl) ?? trimmed(check.targetUrl), |
| 637 | ...(typeof check.isRequired === "boolean" ? { required: check.isRequired } : {}), |
| 638 | }, |
| 639 | workflowName: trimmed(check.workflowName), |
| 640 | at: |
| 641 | status === "pending" |
| 642 | ? STILL_RUNNING |
| 643 | : (realTimestamp(check.completedAt) ?? realTimestamp(check.startedAt)), |
| 644 | }, |
| 645 | ]; |
| 646 | }); |
| 647 | } |
| 648 | |
| 649 | function rollupChecksState( |
| 650 | raw: ReadonlyArray<CheckFields> | null | undefined, |
| 651 | ): PullRequestChecksState | null { |
| 652 | return rollupCheckStatuses([ |
| 653 | ...toChecks(raw).map((check) => check.status), |
| 654 | ...(raw ?? []).filter(isNamelessCheck).map((check) => toCheckStatus(check)), |
| 655 | ]); |
| 656 | } |
| 657 | |
| 658 | function toChecks( |
| 659 | raw: ReadonlyArray<CheckFields> | null | undefined, |
| 660 | ): ReadonlyArray<PullRequestCheck> { |
| 661 | return dedupeChecks(toCheckEntries(raw)); |
| 662 | } |
| 663 | |
| 664 | function isReviewVerdict(reviewState: string | null): boolean { |
| 665 | switch (reviewState?.toUpperCase()) { |
| 666 | case "APPROVED": |
| 667 | case "CHANGES_REQUESTED": |
| 668 | case "DISMISSED": |
| 669 | return true; |
| 670 | default: |
| 671 | return false; |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | interface RemarkFields { |
| 676 | readonly id: string; |
| 677 | readonly lastEditedAt: string | null; |
| 678 | readonly author: ActorFields | null; |
| 679 | readonly body: string; |
| 680 | readonly url: string | null; |
| 681 | readonly isMinimized: boolean; |
| 682 | } |
| 683 | |
| 684 | // Hidden (minimized) remarks are left out, as github.com collapses them: a maintainer marked them |
| 685 | // spam, off-topic, or outdated, and they should not reach readers or agents. |
| 686 | function toComments(raw: { |
| 687 | readonly comments: ReadonlyArray<RemarkFields & { readonly createdAt: string }>; |
| 688 | readonly reviews: ReadonlyArray< |
| 689 | RemarkFields & { readonly state: string; readonly submittedAt: string | null } |
| 690 | >; |
| 691 | }): ReadonlyArray<PullRequestComment> { |
| 692 | const issueComments = raw.comments |
| 693 | .filter((comment) => !comment.isMinimized) |
| 694 | .map((comment): PullRequestComment => ({ |
| 695 | id: comment.id, |
| 696 | kind: "issue-comment", |
| 697 | author: toActor(comment.author), |
| 698 | body: comment.body ?? "", |
| 699 | createdAt: comment.createdAt, |
| 700 | editedAt: comment.lastEditedAt ?? null, |
| 701 | url: trimmed(comment.url), |
| 702 | path: null, |
| 703 | reviewState: null, |
| 704 | })); |
| 705 | // Bodiless COMMENTED reviews only hold line comments read separately. |
| 706 | const reviews = raw.reviews.flatMap((review): ReadonlyArray<PullRequestComment> => { |
| 707 | const submittedAt = trimmed(review.submittedAt); |
| 708 | const reviewState = trimmed(review.state); |
| 709 | if ( |
| 710 | review.isMinimized || |
| 711 | submittedAt === null || |
| 712 | ((review.body ?? "").trim().length === 0 && !isReviewVerdict(reviewState)) |
| 713 | ) { |
| 714 | return []; |
| 715 | } |
| 716 | return [ |
| 717 | { |
| 718 | id: review.id, |
| 719 | kind: "review", |
| 720 | author: toActor(review.author), |
| 721 | body: review.body ?? "", |
| 722 | createdAt: submittedAt, |
| 723 | editedAt: review.lastEditedAt ?? null, |
| 724 | url: trimmed(review.url), |
| 725 | path: null, |
| 726 | reviewState, |
| 727 | }, |
| 728 | ]; |
| 729 | }); |
| 730 | return [...issueComments, ...reviews].toSorted((left, right) => |
| 731 | left.createdAt.localeCompare(right.createdAt), |
| 732 | ); |
| 733 | } |
| 734 | |
| 735 | function toCommits( |
| 736 | commits: ReadonlyArray<{ |
| 737 | readonly oid: string; |
| 738 | readonly messageHeadline: string; |
| 739 | readonly committedDate: string; |
| 740 | readonly authors: ReadonlyArray<Parameters<typeof toCommitActor>[0]>; |
| 741 | }>, |
| 742 | ): ReadonlyArray<PullRequestCommit> { |
| 743 | return commits.map((commit) => ({ |
| 744 | oid: commit.oid, |
| 745 | messageHeadline: commit.messageHeadline, |
| 746 | committedDate: commit.committedDate, |
| 747 | authors: commit.authors.flatMap((author) => toCommitActor(author) ?? []), |
| 748 | })); |
| 749 | } |
| 750 | |
| 751 | function toListItem(raw: ListItemFields): GitHubPullRequestListItem { |
| 752 | return { |
| 753 | number: raw.number, |
| 754 | title: raw.title, |
| 755 | url: raw.url, |
| 756 | author: toActor(raw.author), |
| 757 | headBranch: raw.headRefName, |
| 758 | baseBranch: raw.baseRefName, |
| 759 | state: toState(raw), |
| 760 | isDraft: raw.isDraft ?? false, |
| 761 | mergeability: toMergeability(raw.mergeable), |
| 762 | reviewDecision: toReviewDecisionWithReviews(raw.reviewDecision, raw.latestReviews), |
| 763 | additions: raw.additions ?? 0, |
| 764 | deletions: raw.deletions ?? 0, |
| 765 | createdAt: raw.createdAt, |
| 766 | updatedAt: raw.updatedAt, |
| 767 | reviewRequestLogins: toReviewRequestLogins(raw.reviewRequests), |
| 768 | hasTeamReviewRequest: hasTeamReviewRequest(raw.reviewRequests), |
| 769 | labels: toLabels(raw.labels), |
| 770 | checksState: rollupChecksState(raw.statusCheckRollup), |
| 771 | }; |
| 772 | } |
| 773 | |
| 774 | interface DetailFields extends ListItemFields { |
| 775 | readonly isCrossRepository?: boolean | undefined; |
| 776 | readonly headRepositoryOwner?: { readonly login: string } | null | undefined; |
| 777 | readonly headRefOid?: string | null | undefined; |
| 778 | readonly body?: string | undefined; |
| 779 | readonly changedFiles?: number | undefined; |
| 780 | readonly closedAt?: string | null | undefined; |
| 781 | readonly autoMergeRequest?: |
| 782 | | { readonly mergeMethod?: string | null | undefined } |
| 783 | | null |
| 784 | | undefined; |
| 785 | } |
| 786 | |
| 787 | function toDetail(raw: DetailFields): GitHubPullRequestDetail { |
| 788 | const autoMergeMethod = toMergeMethod(raw.autoMergeRequest?.mergeMethod); |
| 789 | return { |
| 790 | ...toListItem(raw), |
| 791 | ...(typeof raw.isCrossRepository === "boolean" |
| 792 | ? { isCrossRepository: raw.isCrossRepository } |
| 793 | : {}), |
| 794 | headRepositoryOwner: trimmed(raw.headRepositoryOwner?.login), |
| 795 | headSha: trimmed(raw.headRefOid), |
| 796 | body: raw.body ?? "", |
| 797 | changedFiles: raw.changedFiles ?? 0, |
| 798 | mergedAt: trimmed(raw.mergedAt), |
| 799 | closedAt: trimmed(raw.closedAt), |
| 800 | checks: toChecks(raw.statusCheckRollup), |
| 801 | ...(raw.autoMergeRequest === undefined |
| 802 | ? {} |
| 803 | : { autoMergeEnabled: raw.autoMergeRequest !== null }), |
| 804 | ...(autoMergeMethod === undefined ? {} : { autoMergeMethod }), |
| 805 | }; |
| 806 | } |
| 807 | |
| 808 | const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown)); |
| 809 | const decodeWorkflowRuns = decodeJsonResult(RawWorkflowRunsSchema); |
| 810 | const decodeFileEntry = Schema.decodeUnknownExit(RawPullRequestFileSchema); |
| 811 | const decodeRow = Schema.decodeUnknownExit(PullRequestRow); |
| 812 | |
| 813 | /** Decode rows individually so one invalid node cannot blank the entire listing. */ |
| 814 | const LenientRows = Schema.Struct({ |
| 815 | pageInfo: ListingPageInfo, |
| 816 | nodes: Schema.NullOr(Schema.Array(Schema.Unknown)), |
| 817 | }); |
| 818 | |
| 819 | export const LenientPullRequestSearch = GraphQL.query(PullRequestSearch.name, { |
| 820 | document: PullRequestSearch.document, |
| 821 | variables: PullRequestSearch.variables, |
| 822 | result: Schema.Struct({ search: LenientRows }), |
| 823 | }); |
| 824 | |
| 825 | export const LenientPullRequestList = GraphQL.query(PullRequestList.name, { |
| 826 | document: PullRequestList.document, |
| 827 | variables: PullRequestList.variables, |
| 828 | result: Schema.Struct({ |
| 829 | repository: Schema.NullOr(Schema.Struct({ pullRequests: LenientRows })), |
| 830 | }), |
| 831 | }); |
| 832 | |
| 833 | type DecodeFailure = Cause.Cause<Schema.SchemaError>; |
| 834 | |
| 835 | /** Count skipped invalid rows in rawCount to avoid ending pagination early. */ |
| 836 | export function toPullRequestRows( |
| 837 | connection: |
| 838 | | { readonly pageInfo: PageInfoFields; readonly nodes: ReadonlyArray<unknown> | null } |
| 839 | | null |
| 840 | | undefined, |
| 841 | ): { |
| 842 | readonly rows: ReadonlyArray<{ |
| 843 | readonly item: GitHubPullRequestListItem; |
| 844 | readonly repository: string | null; |
| 845 | }>; |
| 846 | readonly rawCount: number; |
| 847 | readonly hasNextPage: boolean; |
| 848 | readonly endCursor: string | null; |
| 849 | } { |
| 850 | const nodes = connection?.nodes ?? []; |
| 851 | return { |
| 852 | rows: nodes.flatMap((entry) => toRow(entry) ?? []), |
| 853 | rawCount: nodes.length, |
| 854 | hasNextPage: connection?.pageInfo.hasNextPage === true, |
| 855 | endCursor: nextCursorOf(connection?.pageInfo), |
| 856 | }; |
| 857 | } |
| 858 | |
| 859 | function toRow( |
| 860 | entry: unknown, |
| 861 | ): { readonly item: GitHubPullRequestListItem; readonly repository: string | null } | null { |
| 862 | const decodedNode = decodeRow(entry); |
| 863 | if (!Exit.isSuccess(decodedNode)) return null; |
| 864 | const node = decodedNode.value; |
| 865 | const stack = toStackMembership(node); |
| 866 | const reviewRequests = nodesOf(node.reviewRequests).flatMap( |
| 867 | (request): ReadonlyArray<ReviewRequestFields> => { |
| 868 | const reviewer = request.requestedReviewer; |
| 869 | if (reviewer === null) return []; |
| 870 | const login = "login" in reviewer ? trimmed(reviewer.login) : null; |
| 871 | if (login !== null) return [{ login }]; |
| 872 | const slug = "slug" in reviewer ? trimmed(reviewer.slug) : null; |
| 873 | return slug === null ? [] : [{ slug }]; |
| 874 | }, |
| 875 | ); |
| 876 | return { |
| 877 | item: { |
| 878 | ...toListItem({ |
| 879 | ...node, |
| 880 | latestReviews: nodesOf(node.latestReviews), |
| 881 | reviewRequests, |
| 882 | labels: nodesOf(node.labels), |
| 883 | statusCheckRollup: rollupStates(node.commits), |
| 884 | }), |
| 885 | ...(stack === undefined ? {} : { stack }), |
| 886 | }, |
| 887 | repository: trimmed(node.repository.nameWithOwner), |
| 888 | }; |
| 889 | } |
| 890 | |
| 891 | function rollupStates(commits: { |
| 892 | readonly nodes: ReadonlyArray<{ |
| 893 | readonly commit: { readonly statusCheckRollup: { readonly state: string } | null }; |
| 894 | } | null> | null; |
| 895 | }): ReadonlyArray<CheckFields> { |
| 896 | return nodesOf(commits).flatMap((commitNode) => { |
| 897 | const state = trimmed(commitNode.commit.statusCheckRollup?.state); |
| 898 | return state === null ? [] : [{ state }]; |
| 899 | }); |
| 900 | } |
| 901 | |
| 902 | export interface GitHubPullRequestSearchItem extends GitHubPullRequestListItem { |
| 903 | readonly repository: string; |
| 904 | } |
| 905 | |
| 906 | export function toStackMembership(raw: { |
| 907 | readonly stack?: { |
| 908 | readonly number: number; |
| 909 | readonly size: number; |
| 910 | readonly baseRefName: string; |
| 911 | } | null; |
| 912 | readonly stackEntry?: { readonly position: number } | null; |
| 913 | }): PullRequestStackMembership | undefined { |
| 914 | return raw.stack && raw.stackEntry |
| 915 | ? { |
| 916 | number: raw.stack.number, |
| 917 | size: raw.stack.size, |
| 918 | base: raw.stack.baseRefName, |
| 919 | position: raw.stackEntry.position, |
| 920 | } |
| 921 | : undefined; |
| 922 | } |
| 923 | |
| 924 | const REPOSITORY_PART = /^[A-Za-z0-9._-]+$/; |
| 925 | |
| 926 | /** Invalid selectors can fail an entire aliased request, not just their own lookup. */ |
| 927 | export function pullRequestLookup(changeRequest: { |
| 928 | readonly repository: string; |
| 929 | readonly number: number; |
| 930 | }): { readonly owner: string; readonly name: string; readonly number: number } | null { |
| 931 | const [owner, name, ...rest] = changeRequest.repository.trim().split("/"); |
| 932 | if (rest.length > 0 || owner === undefined || name === undefined) return null; |
| 933 | if (!REPOSITORY_PART.test(owner) || !REPOSITORY_PART.test(name)) return null; |
| 934 | const { number } = changeRequest; |
| 935 | return Number.isSafeInteger(number) && number > 0 && number <= 2_147_483_647 |
| 936 | ? { owner, name, number } |
| 937 | : null; |
| 938 | } |
| 939 | |
| 940 | export interface GitHubPullRequestSummary { |
| 941 | readonly number: number; |
| 942 | readonly title: string; |
| 943 | readonly url: string; |
| 944 | readonly headBranch: string; |
| 945 | readonly baseBranch: string; |
| 946 | readonly state: PullRequestState; |
| 947 | readonly isDraft: boolean; |
| 948 | readonly closedAt: string | null; |
| 949 | readonly mergedAt: string | null; |
| 950 | readonly updatedAt: string; |
| 951 | readonly author: PullRequestActor | null; |
| 952 | readonly additions: number; |
| 953 | readonly deletions: number; |
| 954 | readonly changedFiles: number; |
| 955 | readonly reviewDecision: PullRequestReviewDecision | null; |
| 956 | readonly checksState: PullRequestChecksState | null; |
| 957 | readonly mergeability: PullRequestMergeability; |
| 958 | /** Null means no stack; absent means not requested. */ |
| 959 | readonly stack?: PullRequestStackMembership | null; |
| 960 | } |
| 961 | |
| 962 | export function toPullRequestSummary(pr: SummarizedPullRequest): GitHubPullRequestSummary { |
| 963 | return { |
| 964 | number: pr.number, |
| 965 | title: pr.title, |
| 966 | url: pr.url, |
| 967 | headBranch: pr.headRefName, |
| 968 | baseBranch: pr.baseRefName, |
| 969 | state: toState(pr), |
| 970 | isDraft: pr.isDraft, |
| 971 | closedAt: trimmed(pr.closedAt), |
| 972 | mergedAt: trimmed(pr.mergedAt), |
| 973 | updatedAt: pr.updatedAt, |
| 974 | author: toActor(pr.author), |
| 975 | additions: pr.additions, |
| 976 | deletions: pr.deletions, |
| 977 | changedFiles: pr.changedFiles, |
| 978 | reviewDecision: toReviewDecisionWithReviews(pr.reviewDecision, nodesOf(pr.latestReviews)), |
| 979 | checksState: rollupChecksState(rollupStates(pr.commits)), |
| 980 | mergeability: toMergeability(pr.mergeable), |
| 981 | ...(pr.stack === undefined ? {} : { stack: toStackMembership(pr) ?? null }), |
| 982 | }; |
| 983 | } |
| 984 | |
| 985 | export interface GitHubPullRequestWatchFingerprint { |
| 986 | readonly status: string; |
| 987 | readonly remarks: string; |
| 988 | } |
| 989 | |
| 990 | type EditedConnection = WatchedPullRequest["comments"] | WatchedPullRequest["reviews"]; |
| 991 | type StateCounts = ReadonlyArray<{ readonly state: string; readonly count: number }> | null; |
| 992 | |
| 993 | const newestEdit = (connection: EditedConnection) => |
| 994 | (connection?.nodes ?? []).reduce( |
| 995 | (newest, node) => |
| 996 | node?.lastEditedAt != null && node.lastEditedAt > newest ? node.lastEditedAt : newest, |
| 997 | "", |
| 998 | ); |
| 999 | |
| 1000 | const stateCounts = (counts: StateCounts) => |
| 1001 | (counts ?? []) |
| 1002 | .filter(({ count }) => count > 0) |
| 1003 | .map(({ state, count }) => `${state}:${count}`) |
| 1004 | .toSorted() |
| 1005 | .join(","); |
| 1006 | |
| 1007 | export function toPullRequestWatchFingerprint( |
| 1008 | pr: WatchedPullRequest, |
| 1009 | ): GitHubPullRequestWatchFingerprint { |
| 1010 | const contexts = pr.commits.nodes?.[0]?.commit.statusCheckRollup?.contexts; |
| 1011 | return { |
| 1012 | status: [ |
| 1013 | pr.state, |
| 1014 | pr.mergeable, |
| 1015 | pr.headRefOid, |
| 1016 | stateCounts(contexts?.checkRunCountsByState ?? null), |
| 1017 | stateCounts(contexts?.statusContextCountsByState ?? null), |
| 1018 | pr.mergeQueueRemovals?.filteredCount ?? 0, |
| 1019 | ].join(" "), |
| 1020 | remarks: [ |
| 1021 | pr.comments.totalCount, |
| 1022 | newestEdit(pr.comments), |
| 1023 | pr.reviews?.totalCount ?? 0, |
| 1024 | newestEdit(pr.reviews), |
| 1025 | pr.reviewThreads.totalCount, |
| 1026 | ].join(" "), |
| 1027 | }; |
| 1028 | } |
| 1029 | |
| 1030 | export interface GitHubPullRequestCore extends GitHubPullRequestDetail { |
| 1031 | readonly mergeQueueRemoval?: PullRequestMergeQueueRemoval; |
| 1032 | readonly maintainerCanModify: boolean; |
| 1033 | readonly canEditMaintainerEdits: boolean; |
| 1034 | readonly mergeCommitSha?: string | null; |
| 1035 | readonly mergedBy?: PullRequestActor | null; |
| 1036 | readonly reviewRequestTeams: ReadonlyArray<PullRequestActor>; |
| 1037 | readonly viewerAccess: GitHubViewerAccess & GitHubRepositoryAccess; |
| 1038 | readonly comparison: GitHubBaseComparison | null; |
| 1039 | readonly checksTruncated: boolean; |
| 1040 | } |
| 1041 | |
| 1042 | type CoreRequestedReviewer = NonNullable< |
| 1043 | NonNullable< |
| 1044 | NonNullable<NonNullable<PullRequestCore.Result["repository"]>["pullRequest"]>["reviewRequests"] |
| 1045 | >["nodes"] |
| 1046 | >[number]; |
| 1047 | |
| 1048 | export function toPullRequestCore(result: PullRequestCore.Result): GitHubPullRequestCore | null { |
| 1049 | const repository = result.repository; |
| 1050 | const pr = repository?.pullRequest; |
| 1051 | if (repository == null || pr == null) return null; |
| 1052 | const contexts = nodesOf(pr.commits)[0]?.commit.statusCheckRollup?.contexts; |
| 1053 | const removal = nodesOf(pr.mergeQueueRemovals).at(-1); |
| 1054 | return { |
| 1055 | ...(removal === undefined || !("id" in removal) |
| 1056 | ? {} |
| 1057 | : { |
| 1058 | mergeQueueRemoval: { |
| 1059 | id: removal.id, |
| 1060 | removedAt: removal.createdAt, |
| 1061 | reason: trimmed(removal.reason), |
| 1062 | }, |
| 1063 | }), |
| 1064 | reviewRequestTeams: nodesOf(pr.reviewRequests).flatMap( |
| 1065 | ({ requestedReviewer }) => toRequestedTeam(requestedReviewer) ?? [], |
| 1066 | ), |
| 1067 | ...toDetail({ |
| 1068 | ...pr, |
| 1069 | latestReviews: [], |
| 1070 | reviewRequests: nodesOf(pr.reviewRequests).flatMap( |
| 1071 | ({ requestedReviewer }: NonNullable<CoreRequestedReviewer>) => |
| 1072 | requestedReviewer === null |
| 1073 | ? [] |
| 1074 | : [ |
| 1075 | { |
| 1076 | login: "login" in requestedReviewer ? requestedReviewer.login : null, |
| 1077 | slug: "slug" in requestedReviewer ? requestedReviewer.slug : null, |
| 1078 | name: |
| 1079 | "teamName" in requestedReviewer |
| 1080 | ? requestedReviewer.teamName |
| 1081 | : "name" in requestedReviewer |
| 1082 | ? requestedReviewer.name |
| 1083 | : null, |
| 1084 | }, |
| 1085 | ], |
| 1086 | ), |
| 1087 | labels: nodesOf(pr.labels), |
| 1088 | statusCheckRollup: toCheckContexts(nodesOf(contexts)), |
| 1089 | }), |
| 1090 | headRepositoryNameWithOwner: trimmed(pr.headRepository?.nameWithOwner), |
| 1091 | maintainerCanModify: pr.maintainerCanModify, |
| 1092 | canEditMaintainerEdits: |
| 1093 | pr.state === "OPEN" && |
| 1094 | pr.isCrossRepository && |
| 1095 | pr.viewerDidAuthor && |
| 1096 | pr.headRepositoryOwner?.__typename === "User" && |
| 1097 | pr.headRepository !== null && |
| 1098 | pr.headRef !== null, |
| 1099 | mergeCommitSha: trimmed(pr.mergeCommit?.oid), |
| 1100 | mergedBy: toActor(pr.mergedBy), |
| 1101 | viewerAccess: { |
| 1102 | canWrite: toCanWrite(repository.viewerPermission), |
| 1103 | canDeleteBranch: toCanWrite(pr.headRepository?.viewerPermission) && pr.headRef !== null, |
| 1104 | canTriage: toCanTriage(repository.viewerPermission), |
| 1105 | ...toPullRequestViewerFields(pr), |
| 1106 | canMergeNow: IMMEDIATELY_MERGEABLE.has(pr.mergeStateStatus), |
| 1107 | mergeCapabilities: { |
| 1108 | merge: repository.mergeCommitAllowed, |
| 1109 | squash: repository.squashMergeAllowed, |
| 1110 | rebase: repository.rebaseMergeAllowed, |
| 1111 | }, |
| 1112 | autoMergeAllowed: repository.autoMergeAllowed, |
| 1113 | }, |
| 1114 | comparison: |
| 1115 | pr.state !== "OPEN" || pr.baseRef?.compare == null |
| 1116 | ? null |
| 1117 | : { |
| 1118 | behindBy: pr.baseRef.compare.behindBy, |
| 1119 | viewerCanUpdate: pr.viewerCanUpdateBranch, |
| 1120 | }, |
| 1121 | checksTruncated: contexts?.pageInfo.hasNextPage === true, |
| 1122 | }; |
| 1123 | } |
| 1124 | |
| 1125 | export interface GitHubWorkflowRunPage { |
| 1126 | readonly runs: ReadonlyArray<GitHubWorkflowRunApproval>; |
| 1127 | readonly rawCount: number; |
| 1128 | } |
| 1129 | |
| 1130 | export function decodeWorkflowRunsJson( |
| 1131 | raw: string, |
| 1132 | ): Result.Result<GitHubWorkflowRunPage, DecodeFailure> { |
| 1133 | const decoded = decodeWorkflowRuns(raw); |
| 1134 | if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); |
| 1135 | return Result.succeed({ |
| 1136 | runs: decoded.success.workflow_runs.map((run) => ({ |
| 1137 | id: run.id, |
| 1138 | name: trimmed(run.name) ?? `Workflow run ${run.id}`, |
| 1139 | url: trimmed(run.html_url), |
| 1140 | })), |
| 1141 | rawCount: decoded.success.workflow_runs.length, |
| 1142 | }); |
| 1143 | } |
| 1144 | |
| 1145 | // Approval-gated runs (action_required) are read separately as action-required checks. |
| 1146 | const UNFINISHED_WORKFLOW_RUN_STATUSES = new Set([ |
| 1147 | "requested", |
| 1148 | "queued", |
| 1149 | "pending", |
| 1150 | "waiting", |
| 1151 | "in_progress", |
| 1152 | ]); |
| 1153 | |
| 1154 | /** Workflow runs GitHub has not finished, which may have no check runs on the head yet. */ |
| 1155 | export function decodeUnfinishedWorkflowRunsJson( |
| 1156 | raw: string, |
| 1157 | ): Result.Result<ReadonlyArray<GitHubWorkflowRunApproval>, DecodeFailure> { |
| 1158 | const decoded = decodeWorkflowRuns(raw); |
| 1159 | if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); |
| 1160 | return Result.succeed( |
| 1161 | decoded.success.workflow_runs |
| 1162 | .filter((run) => UNFINISHED_WORKFLOW_RUN_STATUSES.has(run.status ?? "")) |
| 1163 | .map((run) => ({ |
| 1164 | id: run.id, |
| 1165 | name: trimmed(run.name) ?? `Workflow run ${run.id}`, |
| 1166 | url: trimmed(run.html_url), |
| 1167 | })), |
| 1168 | ); |
| 1169 | } |
| 1170 | |
| 1171 | export function toPullRequestHeads(result: PullRequestHeads.Result): { |
| 1172 | readonly heads: ReadonlyArray<GitHubPullRequestHead>; |
| 1173 | readonly nextCursor: string | null; |
| 1174 | } { |
| 1175 | const connection = result.repository?.pullRequests; |
| 1176 | return { |
| 1177 | heads: nodesOf(connection).map((pullRequest) => ({ |
| 1178 | number: pullRequest.number, |
| 1179 | headSha: pullRequest.headRefOid, |
| 1180 | isCrossRepository: pullRequest.isCrossRepository, |
| 1181 | headRepositoryOwner: trimmed(pullRequest.headRepositoryOwner?.login), |
| 1182 | })), |
| 1183 | nextCursor: nextCursorOf(connection?.pageInfo), |
| 1184 | }; |
| 1185 | } |
| 1186 | |
| 1187 | export interface GitHubPullRequestActivityPage { |
| 1188 | readonly nonMergeCommitIds: ReadonlyArray<string>; |
| 1189 | readonly author?: PullRequestActor | null; |
| 1190 | readonly commits?: ReadonlyArray<PullRequestCommit>; |
| 1191 | readonly remarks: ReadonlyArray<PullRequestComment>; |
| 1192 | readonly nextCommentsCursor: string | null; |
| 1193 | readonly nextReviewsCursor: string | null; |
| 1194 | } |
| 1195 | |
| 1196 | export function toPullRequestActivityPage( |
| 1197 | result: PullRequestActivity.Result, |
| 1198 | ): GitHubPullRequestActivityPage | null { |
| 1199 | const pr = result.repository?.pullRequest; |
| 1200 | if (pr == null) return null; |
| 1201 | return { |
| 1202 | nonMergeCommitIds: nodesOf(pr.commits).flatMap(({ commit }) => |
| 1203 | commit.parents.totalCount > 1 ? [] : [commit.id], |
| 1204 | ), |
| 1205 | ...(pr.author === undefined ? {} : { author: toActor(pr.author) }), |
| 1206 | ...(pr.commits === undefined |
| 1207 | ? {} |
| 1208 | : { |
| 1209 | commits: toCommits( |
| 1210 | nodesOf(pr.commits).map(({ commit }) => ({ |
| 1211 | ...commit, |
| 1212 | authors: nodesOf(commit.authors).map((author) => ({ |
| 1213 | ...author, |
| 1214 | login: author.user?.login ?? null, |
| 1215 | })), |
| 1216 | })), |
| 1217 | ), |
| 1218 | }), |
| 1219 | remarks: toComments({ comments: nodesOf(pr.comments), reviews: nodesOf(pr.reviews) }), |
| 1220 | nextCommentsCursor: nextCursorOf(pr.comments?.pageInfo), |
| 1221 | nextReviewsCursor: nextCursorOf(pr.reviews?.pageInfo), |
| 1222 | }; |
| 1223 | } |
| 1224 | |
| 1225 | export function toPullRequestCommitStats(result: PullRequestCommitStats.Result) { |
| 1226 | return new Map( |
| 1227 | (result.nodes ?? []).flatMap((commit) => |
| 1228 | commit?.__typename === "Commit" |
| 1229 | ? [ |
| 1230 | [ |
| 1231 | commit.oid, |
| 1232 | { |
| 1233 | additions: Math.max(0, commit.additions), |
| 1234 | deletions: Math.max(0, commit.deletions), |
| 1235 | }, |
| 1236 | ] as const, |
| 1237 | ] |
| 1238 | : [], |
| 1239 | ), |
| 1240 | ); |
| 1241 | } |
| 1242 | |
| 1243 | /** A check context as the rollup reports it; opaque outside this module. */ |
| 1244 | export type GitHubCheckContext = CheckFields; |
| 1245 | |
| 1246 | function toCheckContexts(nodes: ReadonlyArray<CheckContext>): ReadonlyArray<GitHubCheckContext> { |
| 1247 | return nodes.map((check) => |
| 1248 | check.__typename === "CheckRun" |
| 1249 | ? { ...check, workflowName: check.checkSuite.workflowRun?.workflow.name ?? null } |
| 1250 | : check, |
| 1251 | ); |
| 1252 | } |
| 1253 | |
| 1254 | export function toPullRequestCheckContextsPage(result: PullRequestCheckContexts.Result): { |
| 1255 | readonly headSha: string; |
| 1256 | readonly contexts: ReadonlyArray<GitHubCheckContext>; |
| 1257 | readonly nextCursor: string | null; |
| 1258 | } | null { |
| 1259 | const pr = result.repository?.pullRequest; |
| 1260 | if (pr == null) return null; |
| 1261 | const contexts = nodesOf(pr.commits)[0]?.commit.statusCheckRollup?.contexts; |
| 1262 | return { |
| 1263 | headSha: pr.headRefOid, |
| 1264 | contexts: toCheckContexts(nodesOf(contexts)), |
| 1265 | nextCursor: nextCursorOf(contexts?.pageInfo), |
| 1266 | }; |
| 1267 | } |
| 1268 | |
| 1269 | export function pullRequestChecksFromContexts(contexts: ReadonlyArray<GitHubCheckContext>): { |
| 1270 | readonly checks: ReadonlyArray<PullRequestCheck>; |
| 1271 | readonly checksState: PullRequestChecksState | null; |
| 1272 | } { |
| 1273 | return { checks: toChecks(contexts), checksState: rollupChecksState(contexts) }; |
| 1274 | } |
| 1275 | |
| 1276 | export interface GitHubReviewThreadComments { |
| 1277 | readonly comments: ReadonlyArray<PullRequestComment>; |
| 1278 | readonly dismissalsByReviewId: ReadonlyMap<string, string>; |
| 1279 | readonly reviewThreads: ReadonlyArray<PullRequestReviewThread>; |
| 1280 | readonly commentCount: number; |
| 1281 | readonly truncated: boolean; |
| 1282 | readonly reviewThreadsTruncated: boolean; |
| 1283 | readonly reactions: ReadonlyArray<PullRequestReaction>; |
| 1284 | readonly reactionsById: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>; |
| 1285 | readonly editedAtById: ReadonlyMap<string, string>; |
| 1286 | readonly reviewers: ReadonlyArray<PullRequestActor>; |
| 1287 | readonly avatarsByLogin: ReadonlyMap<string, string>; |
| 1288 | readonly botLogins: ReadonlySet<string>; |
| 1289 | /** |
| 1290 | * Empty wherever the read never happened (an install too old for the field, a degraded page), |
| 1291 | * which the caller reads as "keep the `gh pr view` list" rather than as "this pull request has |
| 1292 | * no commits". |
| 1293 | */ |
| 1294 | readonly commits: ReadonlyArray<PullRequestCommit>; |
| 1295 | readonly viewer: { readonly canUpdate: boolean; readonly didAuthor: boolean }; |
| 1296 | } |
| 1297 | |
| 1298 | export interface GitHubReviewThreadEntry { |
| 1299 | readonly thread: PullRequestReviewThread; |
| 1300 | readonly commentCount: number; |
| 1301 | readonly nextCommentCursor: string | null; |
| 1302 | } |
| 1303 | |
| 1304 | export interface GitHubReviewThreadPage { |
| 1305 | readonly threads: ReadonlyArray<GitHubReviewThreadEntry>; |
| 1306 | readonly nextCursor: string | null; |
| 1307 | readonly reactions: ReadonlyArray<PullRequestReaction>; |
| 1308 | readonly reactionsById: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>; |
| 1309 | readonly editedAtById: ReadonlyMap<string, string>; |
| 1310 | readonly reviewers: ReadonlyArray<PullRequestActor>; |
| 1311 | readonly avatarsByLogin: ReadonlyMap<string, string>; |
| 1312 | readonly botLogins: ReadonlySet<string>; |
| 1313 | readonly commits: ReadonlyArray<PullRequestCommit>; |
| 1314 | readonly viewer: { readonly canUpdate: boolean; readonly didAuthor: boolean }; |
| 1315 | readonly dismissalsByReviewId: ReadonlyMap<string, string>; |
| 1316 | readonly nextDismissalCursor: string | null; |
| 1317 | } |
| 1318 | |
| 1319 | export function reviewThreadConversation( |
| 1320 | threads: ReadonlyArray<PullRequestReviewThread>, |
| 1321 | ): ReadonlyArray<PullRequestComment> { |
| 1322 | return threads.flatMap((thread) => |
| 1323 | thread.comments.map((comment): PullRequestComment => ({ |
| 1324 | id: comment.id, |
| 1325 | kind: "review-comment", |
| 1326 | author: comment.author, |
| 1327 | body: comment.body, |
| 1328 | createdAt: comment.createdAt, |
| 1329 | editedAt: comment.editedAt ?? null, |
| 1330 | url: comment.url, |
| 1331 | path: thread.path, |
| 1332 | reviewState: null, |
| 1333 | reactions: comment.reactions ?? [], |
| 1334 | })), |
| 1335 | ); |
| 1336 | } |
| 1337 | |
| 1338 | function toDismissalEntries( |
| 1339 | connection: ReviewThreadsPullRequest["reviewDismissals"], |
| 1340 | ): Map<string, string> { |
| 1341 | const entries = new Map<string, string>(); |
| 1342 | for (const node of nodesOf(connection)) { |
| 1343 | if (!("dismissalMessage" in node)) continue; |
| 1344 | const reviewId = trimmed(node.review?.id); |
| 1345 | const message = trimmed(node.dismissalMessage); |
| 1346 | if (reviewId !== null && message !== null) entries.set(reviewId, message); |
| 1347 | } |
| 1348 | return entries; |
| 1349 | } |
| 1350 | |
| 1351 | export function toReviewDismissalsPage(result: ReviewDismissals.Result): { |
| 1352 | readonly dismissalsByReviewId: ReadonlyMap<string, string>; |
| 1353 | readonly nextCursor: string | null; |
| 1354 | } | null { |
| 1355 | const items = result.repository?.pullRequest?.timelineItems; |
| 1356 | if (items === undefined) return null; |
| 1357 | return { |
| 1358 | dismissalsByReviewId: toDismissalEntries(items), |
| 1359 | nextCursor: nextCursorOf(items.pageInfo), |
| 1360 | }; |
| 1361 | } |
| 1362 | |
| 1363 | function toThreadComment(comment: ThreadComment, viewer: string | null): PullRequestThreadComment { |
| 1364 | const reviewUrl = trimmed(comment.pullRequestReview?.url); |
| 1365 | return { |
| 1366 | id: comment.id, |
| 1367 | author: toActor(comment.author), |
| 1368 | body: comment.body, |
| 1369 | createdAt: comment.createdAt, |
| 1370 | editedAt: comment.lastEditedAt, |
| 1371 | url: trimmed(comment.url), |
| 1372 | ...(reviewUrl === null ? {} : { reviewUrl }), |
| 1373 | reactions: toReactions(comment.reactionGroups, viewer), |
| 1374 | }; |
| 1375 | } |
| 1376 | |
| 1377 | type ReviewThreadsPullRequest = NonNullable< |
| 1378 | NonNullable<ReviewThreads.Result["repository"]>["pullRequest"] |
| 1379 | >; |
| 1380 | |
| 1381 | /** A page of threads and the people commenting on them, whichever query carried it. */ |
| 1382 | function toReviewThreadEntries(threads: ReviewThreadPage, viewer: string | null) { |
| 1383 | const threadNodes = nodesOf(threads); |
| 1384 | const entries = threadNodes.flatMap((thread): ReadonlyArray<GitHubReviewThreadEntry> => { |
| 1385 | const path = trimmed(thread.path); |
| 1386 | const id = trimmed(thread.id); |
| 1387 | const loaded = nodesOf(thread.comments); |
| 1388 | // Hidden comments are left out, as in `toComments`; a thread with none left is dropped. |
| 1389 | const comments = loaded.filter((comment) => !comment.isMinimized); |
| 1390 | if (path === null || id === null || comments.length === 0) return []; |
| 1391 | return [ |
| 1392 | { |
| 1393 | thread: { |
| 1394 | id, |
| 1395 | path, |
| 1396 | // Outdated threads lose their diff line; list them without a line anchor. |
| 1397 | line: thread.line !== null && thread.line > 0 ? thread.line : null, |
| 1398 | side: thread.diffSide.toUpperCase() === "LEFT" ? "left" : "right", |
| 1399 | isResolved: thread.isResolved, |
| 1400 | isOutdated: thread.isOutdated, |
| 1401 | comments: comments.map((comment) => toThreadComment(comment, viewer)), |
| 1402 | }, |
| 1403 | commentCount: thread.comments.totalCount - (loaded.length - comments.length), |
| 1404 | nextCommentCursor: nextCursorOf(thread.comments.pageInfo), |
| 1405 | }, |
| 1406 | ]; |
| 1407 | }); |
| 1408 | return { |
| 1409 | entries, |
| 1410 | nextCursor: nextCursorOf(threads.pageInfo), |
| 1411 | authors: threadNodes.flatMap((thread) => |
| 1412 | nodesOf(thread.comments).map((comment) => comment.author), |
| 1413 | ), |
| 1414 | }; |
| 1415 | } |
| 1416 | |
| 1417 | function collectActors(raws: ReadonlyArray<ActorFields | null | undefined>) { |
| 1418 | const avatarsByLogin = new Map<string, string>(); |
| 1419 | const botLogins = new Set<string>(); |
| 1420 | for (const raw of raws) { |
| 1421 | const login = trimmed(raw?.login); |
| 1422 | const avatarUrl = trimmed(raw?.avatarUrl); |
| 1423 | if (login !== null && avatarUrl !== null) avatarsByLogin.set(login, avatarUrl); |
| 1424 | if (login !== null && toActor(raw)?.isBot) botLogins.add(login); |
| 1425 | } |
| 1426 | return { avatarsByLogin, botLogins }; |
| 1427 | } |
| 1428 | |
| 1429 | export function toLaterReviewThreadPage( |
| 1430 | result: ReviewThreadPages.Result, |
| 1431 | ): Pick<GitHubReviewThreadPage, "threads" | "nextCursor" | "avatarsByLogin" | "botLogins"> | null { |
| 1432 | const threads = result.repository?.pullRequest?.reviewThreads; |
| 1433 | if (threads === undefined) return null; |
| 1434 | const { entries, nextCursor, authors } = toReviewThreadEntries( |
| 1435 | threads, |
| 1436 | trimmed(result.viewer.login), |
| 1437 | ); |
| 1438 | return { threads: entries, nextCursor, ...collectActors(authors) }; |
| 1439 | } |
| 1440 | |
| 1441 | export function toReviewThreadPage(result: ReviewThreads.Result): GitHubReviewThreadPage | null { |
| 1442 | const pullRequest = result.repository?.pullRequest; |
| 1443 | if (pullRequest == null) return null; |
| 1444 | const viewer = trimmed(result.viewer.login); |
| 1445 | const page = toReviewThreadEntries(pullRequest.reviewThreads, viewer); |
| 1446 | const requestedReviewers = nodesOf(pullRequest.reviewRequests).map( |
| 1447 | (node): ActorFields | null => node.requestedReviewer, |
| 1448 | ); |
| 1449 | // Someone whose review was hidden is not listed as a reviewer. |
| 1450 | const latestReviews = nodesOf(pullRequest.latestReviews).filter((node) => !node.isMinimized); |
| 1451 | const comments = nodesOf(pullRequest.comments); |
| 1452 | const reviews = nodesOf(pullRequest.reviews); |
| 1453 | const { avatarsByLogin, botLogins } = collectActors([ |
| 1454 | pullRequest.author, |
| 1455 | ...comments.map((node) => node.author), |
| 1456 | ...reviews.map((node) => node.author), |
| 1457 | ...requestedReviewers, |
| 1458 | ...latestReviews.map((node) => node.author), |
| 1459 | ...page.authors, |
| 1460 | ]); |
| 1461 | const reviewers = new Map<string, PullRequestActor>(); |
| 1462 | for (const raw of [...requestedReviewers, ...latestReviews.map((node) => node.author)]) { |
| 1463 | const actor = toActor(raw) ?? toRequestedTeam(raw); |
| 1464 | if (actor !== null && !reviewers.has(actor.login)) reviewers.set(actor.login, actor); |
| 1465 | } |
| 1466 | const commits: PullRequestCommit[] = []; |
| 1467 | for (const { commit } of nodesOf(pullRequest.commits)) { |
| 1468 | const oid = trimmed(commit.oid); |
| 1469 | if (oid === null) continue; |
| 1470 | const committedDate = trimmed(commit.committedDate); |
| 1471 | if (committedDate === null) continue; |
| 1472 | commits.push({ |
| 1473 | oid, |
| 1474 | messageHeadline: commit.messageHeadline, |
| 1475 | committedDate, |
| 1476 | authors: nodesOf(commit.authors).flatMap((author) => toGraphqlCommitActor(author) ?? []), |
| 1477 | }); |
| 1478 | } |
| 1479 | const reactionsById = new Map<string, ReadonlyArray<PullRequestReaction>>(); |
| 1480 | const editedAtById = new Map<string, string>(); |
| 1481 | for (const node of [...comments, ...reviews]) { |
| 1482 | const id = trimmed(node.id); |
| 1483 | if (id === null) continue; |
| 1484 | const editedAt = trimmed(node.lastEditedAt); |
| 1485 | if (editedAt !== null) editedAtById.set(id, editedAt); |
| 1486 | const reactions = toReactions(node.reactionGroups, viewer); |
| 1487 | if (reactions.length > 0) reactionsById.set(id, reactions); |
| 1488 | } |
| 1489 | return { |
| 1490 | threads: page.entries, |
| 1491 | nextCursor: page.nextCursor, |
| 1492 | reactions: toReactions(pullRequest.reactionGroups, viewer), |
| 1493 | reactionsById, |
| 1494 | editedAtById, |
| 1495 | reviewers: [...reviewers.values()], |
| 1496 | avatarsByLogin, |
| 1497 | botLogins, |
| 1498 | commits, |
| 1499 | viewer: toPullRequestViewerFields(pullRequest), |
| 1500 | dismissalsByReviewId: toDismissalEntries(pullRequest.reviewDismissals), |
| 1501 | nextDismissalCursor: nextCursorOf(pullRequest.reviewDismissals.pageInfo), |
| 1502 | }; |
| 1503 | } |
| 1504 | |
| 1505 | export function toReviewThreadCommentsPage(result: ReviewThreadComments.Result): { |
| 1506 | readonly belongsToPullRequest: boolean; |
| 1507 | readonly comments: ReadonlyArray<PullRequestThreadComment>; |
| 1508 | readonly hiddenCount: number; |
| 1509 | readonly nextCursor: string | null; |
| 1510 | } { |
| 1511 | const viewer = trimmed(result.viewer.login); |
| 1512 | const thread = result.node?.__typename === "PullRequestReviewThread" ? result.node : null; |
| 1513 | const pullRequestId = result.repository?.pullRequest?.id; |
| 1514 | const loaded = nodesOf(thread?.comments); |
| 1515 | const comments = loaded.filter((comment) => !comment.isMinimized); |
| 1516 | return { |
| 1517 | belongsToPullRequest: pullRequestId !== undefined && pullRequestId === thread?.pullRequest.id, |
| 1518 | comments: comments.map((comment) => toThreadComment(comment, viewer)), |
| 1519 | hiddenCount: loaded.length - comments.length, |
| 1520 | nextCursor: nextCursorOf(thread?.comments.pageInfo), |
| 1521 | }; |
| 1522 | } |
| 1523 | |
| 1524 | export interface GitHubRepositoryAccess { |
| 1525 | readonly mergeCapabilities: PullRequestMergeCapabilities; |
| 1526 | readonly autoMergeAllowed: boolean; |
| 1527 | readonly canWrite: boolean; |
| 1528 | } |
| 1529 | |
| 1530 | /** States in which `gh pr merge --auto` merges at once instead of arming auto-merge. */ |
| 1531 | export const IMMEDIATELY_MERGEABLE: ReadonlySet<string> = new Set([ |
| 1532 | "CLEAN", |
| 1533 | "HAS_HOOKS", |
| 1534 | "UNSTABLE", |
| 1535 | ]); |
| 1536 | |
| 1537 | /** |
| 1538 | * GitHub answers null only to a GitHub App installation, and no API says what an installation |
| 1539 | * may do, so null is granted and GitHub refuses whatever the app was not given. |
| 1540 | */ |
| 1541 | export function toCanWrite(viewerPermission: string | null | undefined): boolean { |
| 1542 | if (viewerPermission === null) return true; |
| 1543 | switch (viewerPermission?.trim().toUpperCase()) { |
| 1544 | case "ADMIN": |
| 1545 | case "MAINTAIN": |
| 1546 | case "WRITE": |
| 1547 | return true; |
| 1548 | default: |
| 1549 | return false; |
| 1550 | } |
| 1551 | } |
| 1552 | |
| 1553 | function toCanTriage(viewerPermission: string | null | undefined): boolean { |
| 1554 | return viewerPermission?.trim().toUpperCase() === "TRIAGE" || toCanWrite(viewerPermission); |
| 1555 | } |
| 1556 | |
| 1557 | export interface GitHubBaseComparison { |
| 1558 | readonly behindBy: number | null; |
| 1559 | readonly viewerCanUpdate: boolean; |
| 1560 | } |
| 1561 | |
| 1562 | /** assignableUsers avoids push/read:org requirements. Keep requested outsiders/apps removable. */ |
| 1563 | export function toReviewerCandidates( |
| 1564 | result: ReviewerCandidates.Result, |
| 1565 | query?: string, |
| 1566 | ): PullRequestReviewerCandidateList | null { |
| 1567 | const repository = result.repository; |
| 1568 | if (repository == null) return null; |
| 1569 | const pullRequest = repository.pullRequest; |
| 1570 | const author = trimmed(pullRequest?.author?.login); |
| 1571 | const candidates = new Map<string, PullRequestReviewerCandidate>(); |
| 1572 | for (const { requestedReviewer: raw } of nodesOf(pullRequest?.reviewRequests)) { |
| 1573 | if (raw === null) continue; |
| 1574 | const slug = "slug" in raw ? trimmed(raw.slug) : null; |
| 1575 | const id = slug ?? ("login" in raw ? trimmed(raw.login) : null); |
| 1576 | if (id === null) continue; |
| 1577 | candidates.set(`${slug === null ? "user" : "team"} ${id}`, { |
| 1578 | id, |
| 1579 | kind: slug === null ? "user" : "team", |
| 1580 | // Match reviewer rows' org/slug so requests can be withdrawn. |
| 1581 | login: slug === null ? id : (trimmed("combinedSlug" in raw ? raw.combinedSlug : null) ?? id), |
| 1582 | name: trimmed("teamName" in raw ? raw.teamName : "name" in raw ? raw.name : null), |
| 1583 | avatarUrl: trimmed( |
| 1584 | "teamAvatarUrl" in raw ? raw.teamAvatarUrl : "avatarUrl" in raw ? raw.avatarUrl : null, |
| 1585 | ), |
| 1586 | isRequested: true, |
| 1587 | }); |
| 1588 | } |
| 1589 | const hostMatches = new Set<string>(); |
| 1590 | for (const node of nodesOf(repository.assignableUsers)) { |
| 1591 | const login = trimmed(node.login); |
| 1592 | if (login !== null) hostMatches.add(login); |
| 1593 | if (login === null || login === author || candidates.has(`user ${login}`)) continue; |
| 1594 | candidates.set(`user ${login}`, { |
| 1595 | id: login, |
| 1596 | kind: "user", |
| 1597 | login, |
| 1598 | name: trimmed(node.name), |
| 1599 | avatarUrl: trimmed(node.avatarUrl), |
| 1600 | isRequested: false, |
| 1601 | }); |
| 1602 | } |
| 1603 | return { |
| 1604 | candidates: [...candidates.values()].filter( |
| 1605 | (candidate) => !query?.trim() || (candidate.kind === "user" && hostMatches.has(candidate.id)), |
| 1606 | ), |
| 1607 | truncated: repository.assignableUsers.pageInfo.hasNextPage, |
| 1608 | }; |
| 1609 | } |
| 1610 | |
| 1611 | const ReviewerRequestSchema = Schema.Struct({ |
| 1612 | reviewers: Schema.Array(Schema.String), |
| 1613 | team_reviewers: Schema.Array(Schema.String), |
| 1614 | }); |
| 1615 | |
| 1616 | export function buildReviewerRequest( |
| 1617 | reviewers: ReadonlyArray<{ readonly id: string; readonly kind: PullRequestReviewerKind }>, |
| 1618 | ): typeof ReviewerRequestSchema.Type { |
| 1619 | return { |
| 1620 | reviewers: reviewers.flatMap((reviewer) => (reviewer.kind === "user" ? [reviewer.id] : [])), |
| 1621 | team_reviewers: reviewers.flatMap((reviewer) => |
| 1622 | reviewer.kind === "team" ? [reviewer.id] : [], |
| 1623 | ), |
| 1624 | }; |
| 1625 | } |
| 1626 | |
| 1627 | /** Keep applied labels removable even when absent from the repository page. */ |
| 1628 | export function toLabelCandidates( |
| 1629 | result: LabelCandidates.Result, |
| 1630 | ): PullRequestLabelCandidateList | null { |
| 1631 | const repository = result.repository; |
| 1632 | if (repository == null) return null; |
| 1633 | const applied = new Set( |
| 1634 | nodesOf(repository.pullRequest?.labels).flatMap((label) => trimmed(label.name) ?? []), |
| 1635 | ); |
| 1636 | const candidates = new Map<string, PullRequestLabelCandidate>(); |
| 1637 | for (const node of nodesOf(repository.labels)) { |
| 1638 | const name = trimmed(node.name); |
| 1639 | if (name === null) continue; |
| 1640 | candidates.set(name, { |
| 1641 | name, |
| 1642 | color: trimmed(node.color), |
| 1643 | description: trimmed(node.description), |
| 1644 | isApplied: applied.has(name), |
| 1645 | }); |
| 1646 | } |
| 1647 | const missing = [...applied].filter((name) => !candidates.has(name)); |
| 1648 | return { |
| 1649 | candidates: [ |
| 1650 | ...missing.map((name) => ({ name, color: null, description: null, isApplied: true })), |
| 1651 | ...candidates.values(), |
| 1652 | ], |
| 1653 | truncated: repository.labels?.pageInfo.hasNextPage === true, |
| 1654 | }; |
| 1655 | } |
| 1656 | |
| 1657 | export function toRepositoryLabels( |
| 1658 | result: RepositoryLabels.Result, |
| 1659 | ): { readonly items: ReadonlyArray<PullRequestLabel>; readonly truncated: boolean } | null { |
| 1660 | const repository = result.repository; |
| 1661 | if (repository == null) return null; |
| 1662 | return { |
| 1663 | items: nodesOf(repository.labels).flatMap((node) => { |
| 1664 | const name = trimmed(node.name); |
| 1665 | return name === null ? [] : [{ name, color: trimmed(node.color) }]; |
| 1666 | }), |
| 1667 | truncated: repository.labels?.pageInfo.hasNextPage === true, |
| 1668 | }; |
| 1669 | } |
| 1670 | |
| 1671 | export function toRepositoryAuthors( |
| 1672 | result: RepositoryAuthors.Result, |
| 1673 | ): { readonly items: ReadonlyArray<PullRequestActor>; readonly truncated: boolean } | null { |
| 1674 | const repository = result.repository; |
| 1675 | if (repository == null) return null; |
| 1676 | return { |
| 1677 | items: nodesOf(repository.mentionableUsers).flatMap((node) => { |
| 1678 | const login = trimmed(node.login); |
| 1679 | return login === null |
| 1680 | ? [] |
| 1681 | : [{ login, name: trimmed(node.name), avatarUrl: trimmed(node.avatarUrl) }]; |
| 1682 | }), |
| 1683 | truncated: repository.mentionableUsers.pageInfo.hasNextPage, |
| 1684 | }; |
| 1685 | } |
| 1686 | |
| 1687 | /** The `search` string for {@link toRepositoryReferences}; a numeric query searches recent items. */ |
| 1688 | export function referenceSearchQuery(repository: string, query: string | undefined): string { |
| 1689 | const text = query?.trim() ?? ""; |
| 1690 | const titled = text.length === 0 || /^\d+$/.test(text) ? [] : [`in:title ${searchPhrase(text)}`]; |
| 1691 | return [`repo:${repository}`, ...titled, "sort:updated-desc"].join(" "); |
| 1692 | } |
| 1693 | |
| 1694 | /** Quote user text so GitHub cannot interpret it as qualifiers that widen the listing. */ |
| 1695 | export function searchPhrase(query: string): string { |
| 1696 | return `"${query.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`; |
| 1697 | } |
| 1698 | |
| 1699 | type ReferenceNode = |
| 1700 | | ReferenceCandidate |
| 1701 | | NonNullable<NonNullable<RepositoryReferences.Result["search"]["nodes"]>[number]>; |
| 1702 | |
| 1703 | function toReferenceCandidate(node: ReferenceNode): PullRequestReferenceCandidate | null { |
| 1704 | if (node.__typename === "Issue") { |
| 1705 | return { |
| 1706 | reference: `#${node.number}`, |
| 1707 | kind: "issue", |
| 1708 | number: node.number, |
| 1709 | title: node.title, |
| 1710 | state: node.issueState === "OPEN" ? "open" : "closed", |
| 1711 | }; |
| 1712 | } |
| 1713 | if (node.__typename === "PullRequest") { |
| 1714 | return { |
| 1715 | reference: `#${node.number}`, |
| 1716 | kind: "change-request", |
| 1717 | number: node.number, |
| 1718 | title: node.title, |
| 1719 | state: |
| 1720 | node.pullRequestState === "OPEN" |
| 1721 | ? "open" |
| 1722 | : node.pullRequestState === "MERGED" |
| 1723 | ? "merged" |
| 1724 | : "closed", |
| 1725 | }; |
| 1726 | } |
| 1727 | return null; |
| 1728 | } |
| 1729 | |
| 1730 | export function toRepositoryReferences(result: RepositoryReferences.Result): { |
| 1731 | readonly items: ReadonlyArray<PullRequestReferenceCandidate>; |
| 1732 | readonly truncated: boolean; |
| 1733 | } { |
| 1734 | const exact = result.repository?.issueOrPullRequest; |
| 1735 | const nodes = [...(exact == null ? [] : [exact]), ...nodesOf(result.search)]; |
| 1736 | return { |
| 1737 | items: nodes.flatMap((node) => { |
| 1738 | const candidate = toReferenceCandidate(node); |
| 1739 | return candidate === null ? [] : [candidate]; |
| 1740 | }), |
| 1741 | truncated: result.search.pageInfo.hasNextPage, |
| 1742 | }; |
| 1743 | } |
| 1744 | |
| 1745 | export function buildLabelRequest(labels: ReadonlyArray<string>): { |
| 1746 | readonly labels: ReadonlyArray<string>; |
| 1747 | } { |
| 1748 | return { labels }; |
| 1749 | } |
| 1750 | |
| 1751 | export interface GitHubViewerAccess { |
| 1752 | readonly canWrite: boolean; |
| 1753 | readonly canDeleteBranch?: boolean; |
| 1754 | readonly canTriage: boolean; |
| 1755 | readonly canUpdate: boolean; |
| 1756 | readonly didAuthor: boolean; |
| 1757 | /** Permitted and update needed; false also covers current branches. Absent if unread. */ |
| 1758 | readonly canUpdateBranch?: boolean; |
| 1759 | /** Detail-only readiness; omitted by the lightweight action permission read. */ |
| 1760 | readonly canMergeNow?: boolean; |
| 1761 | } |
| 1762 | |
| 1763 | export function toViewerPermissions( |
| 1764 | result: ViewerPermissions.Result, |
| 1765 | ): (GitHubViewerAccess & GitHubRepositoryAccess) | null { |
| 1766 | const repository = result.repository; |
| 1767 | if (repository == null) return null; |
| 1768 | return { |
| 1769 | mergeCapabilities: { |
| 1770 | merge: repository.mergeCommitAllowed, |
| 1771 | squash: repository.squashMergeAllowed, |
| 1772 | rebase: repository.rebaseMergeAllowed, |
| 1773 | }, |
| 1774 | autoMergeAllowed: repository.autoMergeAllowed, |
| 1775 | canWrite: toCanWrite(repository.viewerPermission), |
| 1776 | canDeleteBranch: toCanWrite(repository.pullRequest?.headRepository?.viewerPermission), |
| 1777 | canTriage: toCanTriage(repository.viewerPermission), |
| 1778 | ...toPullRequestViewerFields(repository.pullRequest), |
| 1779 | }; |
| 1780 | } |
| 1781 | |
| 1782 | export interface GitHubPullRequestFilesPatch { |
| 1783 | readonly patch: string; |
| 1784 | readonly truncated: boolean; |
| 1785 | readonly rawCount: number; |
| 1786 | readonly omittedFileStats: ReadonlyArray<PullRequestOmittedFileStat>; |
| 1787 | } |
| 1788 | |
| 1789 | /** The files API omits diff --git headers; assemble them for unified-patch viewers. */ |
| 1790 | export function decodePullRequestFilesJson( |
| 1791 | raw: string, |
| 1792 | ): Result.Result<GitHubPullRequestFilesPatch, DecodeFailure> { |
| 1793 | return Result.map(decodeUnknownList(raw), toFilesPatch); |
| 1794 | } |
| 1795 | |
| 1796 | export function decodeCommitFilesJson( |
| 1797 | raw: string, |
| 1798 | ): Result.Result<GitHubPullRequestFilesPatch, DecodeFailure> { |
| 1799 | return Result.map(decodeCommitFiles(raw), (commit) => toFilesPatch(commit.files ?? [])); |
| 1800 | } |
| 1801 | |
| 1802 | const decodeCommitFiles = decodeJsonResult( |
| 1803 | Schema.Struct({ files: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))) }), |
| 1804 | ); |
| 1805 | |
| 1806 | function toFilesPatch(entries: ReadonlyArray<unknown>): GitHubPullRequestFilesPatch { |
| 1807 | const sections: string[] = []; |
| 1808 | const omittedFileStats: PullRequestOmittedFileStat[] = []; |
| 1809 | let truncated = false; |
| 1810 | for (const entry of entries) { |
| 1811 | const file = decodeFileEntry(entry); |
| 1812 | if (Exit.isFailure(file)) continue; |
| 1813 | const value = file.value; |
| 1814 | const hunks = value.patch ?? ""; |
| 1815 | const status = value.status?.trim().toLowerCase(); |
| 1816 | if (hunks.length === 0) { |
| 1817 | // Hunkless renames are complete; omitted binary changes leave a patch gap. |
| 1818 | const additions = value.additions ?? 0; |
| 1819 | const deletions = value.deletions ?? 0; |
| 1820 | if (additions + deletions > 0) { |
| 1821 | truncated = true; |
| 1822 | omittedFileStats.push({ path: value.filename, additions, deletions }); |
| 1823 | } |
| 1824 | } |
| 1825 | const oldPath = |
| 1826 | status === "renamed" ? value.previous_filename || value.filename : value.filename; |
| 1827 | const header = [ |
| 1828 | `diff --git ${quoteGitPatchPath(`a/${oldPath}`)} ${quoteGitPatchPath(`b/${value.filename}`)}`, |
| 1829 | ...(status === "added" ? ["new file mode 100644"] : []), |
| 1830 | ...(status === "removed" ? ["deleted file mode 100644"] : []), |
| 1831 | ...(status === "renamed" |
| 1832 | ? [ |
| 1833 | // The files API has no similarity score; Pierre needs this header to keep the rename. |
| 1834 | `similarity index ${hunks.length > 0 || (value.additions ?? 0) + (value.deletions ?? 0) > 0 ? 0 : 100}%`, |
| 1835 | `rename from ${quoteGitPatchPath(oldPath)}`, |
| 1836 | `rename to ${quoteGitPatchPath(value.filename)}`, |
| 1837 | ] |
| 1838 | : []), |
| 1839 | `--- ${status === "added" ? "/dev/null" : quoteGitPatchPath(`a/${oldPath}`)}`, |
| 1840 | `+++ ${status === "removed" ? "/dev/null" : quoteGitPatchPath(`b/${value.filename}`)}`, |
| 1841 | ].join("\n"); |
| 1842 | sections.push(hunks.length === 0 ? `${header}\n` : `${header}\n${hunks.replace(/\n?$/, "\n")}`); |
| 1843 | } |
| 1844 | return { |
| 1845 | patch: sections.join(""), |
| 1846 | truncated, |
| 1847 | rawCount: entries.length, |
| 1848 | omittedFileStats, |
| 1849 | }; |
| 1850 | } |
| 1851 | |
| 1852 | export interface GitHubPullRequestFilesViewedPage { |
| 1853 | readonly files: ReadonlyArray<{ |
| 1854 | readonly path: string; |
| 1855 | readonly state: PullRequestFileViewedState; |
| 1856 | }>; |
| 1857 | readonly nextCursor: string | null; |
| 1858 | } |
| 1859 | |
| 1860 | function toFileViewedState(raw: string): PullRequestFileViewedState { |
| 1861 | switch (raw.trim().toUpperCase()) { |
| 1862 | case "VIEWED": |
| 1863 | return "viewed"; |
| 1864 | case "DISMISSED": |
| 1865 | return "dismissed"; |
| 1866 | default: |
| 1867 | return "unviewed"; |
| 1868 | } |
| 1869 | } |
| 1870 | |
| 1871 | export function toPullRequestFilesViewedPage( |
| 1872 | result: PullRequestFilesViewed.Result, |
| 1873 | ): GitHubPullRequestFilesViewedPage { |
| 1874 | const files = result.repository?.pullRequest?.files; |
| 1875 | return { |
| 1876 | files: nodesOf(files).flatMap((node) => |
| 1877 | node.path.length === 0 |
| 1878 | ? [] |
| 1879 | : [{ path: node.path, state: toFileViewedState(node.viewerViewedState) }], |
| 1880 | ), |
| 1881 | nextCursor: nextCursorOf(files?.pageInfo), |
| 1882 | }; |
| 1883 | } |
| 1884 | |
| 1885 | export interface GitHubPullRequestFileStat { |
| 1886 | readonly path: string; |
| 1887 | readonly additions: number; |
| 1888 | readonly deletions: number; |
| 1889 | } |
| 1890 | |
| 1891 | export interface GitHubPullRequestFileStatsPage { |
| 1892 | readonly files: ReadonlyArray<GitHubPullRequestFileStat>; |
| 1893 | readonly nextCursor: string | null; |
| 1894 | } |
| 1895 | |
| 1896 | export function toPullRequestFileStatsPage( |
| 1897 | result: PullRequestFileStats.Result, |
| 1898 | ): GitHubPullRequestFileStatsPage { |
| 1899 | const files = result.repository?.pullRequest?.files; |
| 1900 | return { |
| 1901 | files: nodesOf(files).flatMap(({ path, additions, deletions }) => |
| 1902 | path.length === 0 ? [] : [{ path, additions, deletions }], |
| 1903 | ), |
| 1904 | nextCursor: nextCursorOf(files?.pageInfo), |
| 1905 | }; |
| 1906 | } |
| 1907 | |
| 1908 | const RawStackPullRequestSchema = Schema.Struct({ |
| 1909 | title: Schema.optional(Schema.String), |
| 1910 | draft: Schema.optional(Schema.Boolean), |
| 1911 | number: Schema.Int, |
| 1912 | head: Schema.Struct({ ref: Schema.String, sha: Schema.optional(Schema.String) }), |
| 1913 | state: Schema.optional(Schema.NullOr(Schema.String)), |
| 1914 | merged_at: Schema.optional(Schema.NullOr(Schema.String)), |
| 1915 | }); |
| 1916 | |
| 1917 | const RawStackSchema = Schema.Struct({ |
| 1918 | id: Schema.optional(Schema.NullOr(Schema.Union([Schema.Int, Schema.String]))), |
| 1919 | number: Schema.Int, |
| 1920 | node_id: Schema.optional(Schema.NullOr(Schema.String)), |
| 1921 | url: Schema.String, |
| 1922 | html_url: Schema.optional(Schema.NullOr(Schema.String)), |
| 1923 | base: Schema.Union([Schema.String, Schema.Struct({ ref: Schema.String })]), |
| 1924 | pull_requests: Schema.Array(RawStackPullRequestSchema), |
| 1925 | }); |
| 1926 | |
| 1927 | const decodeStacks = decodeJsonResult(Schema.Array(RawStackSchema)); |
| 1928 | |
| 1929 | export interface GitHubPullRequestStackLayer { |
| 1930 | readonly title?: string; |
| 1931 | readonly isDraft?: boolean; |
| 1932 | readonly headSha?: string; |
| 1933 | readonly number: number; |
| 1934 | readonly headBranch: string; |
| 1935 | readonly state: PullRequestState; |
| 1936 | } |
| 1937 | |
| 1938 | export interface GitHubPullRequestStack { |
| 1939 | readonly id: string; |
| 1940 | readonly number: number; |
| 1941 | readonly url: string; |
| 1942 | readonly base: string; |
| 1943 | readonly layers: ReadonlyArray<GitHubPullRequestStackLayer>; |
| 1944 | } |
| 1945 | |
| 1946 | export function decodePullRequestStacksJson( |
| 1947 | raw: string, |
| 1948 | ): Result.Result<GitHubPullRequestStack | null, DecodeFailure> { |
| 1949 | const decoded = decodeStacks(raw); |
| 1950 | if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); |
| 1951 | const stack = decoded.success[0]; |
| 1952 | if (stack === undefined) return Result.succeed(null); |
| 1953 | return Result.succeed({ |
| 1954 | id: stack.id == null ? (trimmed(stack.node_id) ?? String(stack.number)) : String(stack.id), |
| 1955 | number: stack.number, |
| 1956 | url: trimmed(stack.html_url) ?? stack.url, |
| 1957 | base: typeof stack.base === "string" ? stack.base : stack.base.ref, |
| 1958 | layers: stack.pull_requests.map((pullRequest) => ({ |
| 1959 | ...(pullRequest.title === undefined ? {} : { title: pullRequest.title }), |
| 1960 | ...(pullRequest.draft === undefined ? {} : { isDraft: pullRequest.draft }), |
| 1961 | ...(pullRequest.head.sha === undefined ? {} : { headSha: pullRequest.head.sha }), |
| 1962 | number: pullRequest.number, |
| 1963 | headBranch: pullRequest.head.ref, |
| 1964 | state: toState({ state: pullRequest.state, mergedAt: pullRequest.merged_at }), |
| 1965 | })), |
| 1966 | }); |
| 1967 | } |