The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { isCommitSha, normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils"; |
| 2 | import { |
| 3 | diffFileSection, |
| 4 | truncateLongDiffLines, |
| 5 | } from "@t3tools/source-control-core/server/diffFileRevisions"; |
| 6 | import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage"; |
| 7 | import { KnownWorkflowRuns, makeChecksRevalidator } from "./gitHubConditionalChecks.ts"; |
| 8 | import { runGitHubStackAction, type GitHubStackActionError } from "./githubStackActions.ts"; |
| 9 | import * as Cache from "effect/Cache"; |
| 10 | import * as Context from "effect/Context"; |
| 11 | import * as Clock from "effect/Clock"; |
| 12 | import * as Duration from "effect/Duration"; |
| 13 | import * as Effect from "effect/Effect"; |
| 14 | import * as FileSystem from "effect/FileSystem"; |
| 15 | import * as Layer from "effect/Layer"; |
| 16 | import * as Option from "effect/Option"; |
| 17 | import { GraphQLClient, GraphQLClientError, GraphQLGroup, GraphQLResolver } from "effect/graphql"; |
| 18 | import { HttpClient } from "effect/http"; |
| 19 | import * as RequestResolver from "effect/RequestResolver"; |
| 20 | import * as Result from "effect/Result"; |
| 21 | import * as Schema from "effect/Schema"; |
| 22 | import * as Semaphore from "effect/Semaphore"; |
| 23 | import * as Stream from "effect/Stream"; |
| 24 | import { |
| 25 | resolvePullRequestAuthorFilter, |
| 26 | PositiveInt, |
| 27 | TrimmedNonEmptyString, |
| 28 | type PullRequestAction, |
| 29 | type PullRequestStackHead, |
| 30 | type PullRequestActor, |
| 31 | type PullRequestReferenceCandidate, |
| 32 | type PullRequestComment, |
| 33 | type PullRequestCommit, |
| 34 | type PullRequestFileViewed, |
| 35 | type PullRequestInvolvement, |
| 36 | type PullRequestListFilters, |
| 37 | type PullRequestListState, |
| 38 | type PullRequestMergeMethod, |
| 39 | type PullRequestOmittedFileStat, |
| 40 | type PullRequestReactionContent, |
| 41 | type PullRequestReviewCommentDraft, |
| 42 | type PullRequestReviewVerdict, |
| 43 | type PullRequestReviewerCandidateList, |
| 44 | type PullRequestReviewerKind, |
| 45 | type PullRequestLabel, |
| 46 | type PullRequestLabelCandidateList, |
| 47 | type PullRequestThreadCommentsResult, |
| 48 | type PullRequestUpdateMethod, |
| 49 | type PullRequestPreview, |
| 50 | } from "@t3tools/contracts"; |
| 51 | |
| 52 | import * as GitHubAppAccess from "./GitHubAppAccess.ts"; |
| 53 | import * as GitHubRest from "./GitHubRest.ts"; |
| 54 | import * as GitHubPullRequestEvents from "./gitHubPullRequestEvents.ts"; |
| 55 | import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts"; |
| 56 | import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts"; |
| 57 | import { PullRequestBatchesGraphQLGroup } from "./pullRequestBatches.graphql.ts"; |
| 58 | import { |
| 59 | PullRequestMutationsGraphQLGroup, |
| 60 | type PullRequestActionSummary, |
| 61 | } from "./pullRequestMutations.graphql.ts"; |
| 62 | import { |
| 63 | PullRequestActionState, |
| 64 | PullRequestCore, |
| 65 | PullRequestReadsGraphQLGroup, |
| 66 | } from "./pullRequestReads.graphql.ts"; |
| 67 | import { PullRequestReviewsGraphQLGroup } from "./pullRequestReviews.graphql.ts"; |
| 68 | import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; |
| 69 | import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; |
| 70 | import { |
| 71 | buildReviewSubmission, |
| 72 | buildReviewerRequest, |
| 73 | decodeCommitFilesJson, |
| 74 | pullRequestChecksFromContexts, |
| 75 | decodeWorkflowRunsJson, |
| 76 | decodeUnfinishedWorkflowRunsJson, |
| 77 | type GitHubPullRequestCore, |
| 78 | type GitHubPullRequestFileStat, |
| 79 | type GitHubPullRequestWatchFingerprint, |
| 80 | isSubjectOfPullRequest, |
| 81 | LenientPullRequestList, |
| 82 | LenientPullRequestSearch, |
| 83 | pageRows, |
| 84 | pullRequestLookup, |
| 85 | toLabelCandidates, |
| 86 | toRepositoryAuthors, |
| 87 | toRepositoryReferences, |
| 88 | referenceSearchQuery, |
| 89 | searchPhrase, |
| 90 | toRepositoryLabels, |
| 91 | toPullRequestActivityPage, |
| 92 | toPullRequestActionSummary, |
| 93 | toPullRequestCommitStats, |
| 94 | toPullRequestCheckContextsPage, |
| 95 | toPullRequestCore, |
| 96 | toPullRequestFilesViewedPage, |
| 97 | toPullRequestFileStatsPage, |
| 98 | toPullRequestHeads, |
| 99 | toPullRequestNodeId, |
| 100 | toPullRequestPreview, |
| 101 | toPullRequestRows, |
| 102 | toPullRequestSummary, |
| 103 | toPullRequestWatchFingerprint, |
| 104 | toReviewDismissalsPage, |
| 105 | toReviewerCandidates, |
| 106 | toReviewThreadCommentsPage, |
| 107 | toLaterReviewThreadPage, |
| 108 | toReviewThreadPage, |
| 109 | toStackMembership, |
| 110 | toViewerPermissions, |
| 111 | decodePullRequestFilesJson, |
| 112 | decodePullRequestStacksJson, |
| 113 | buildLabelRequest, |
| 114 | PULL_REQUEST_SEARCH_MAX_ROWS, |
| 115 | gitHubReactionContent, |
| 116 | reviewThreadConversation, |
| 117 | type GitHubPullRequestActivity, |
| 118 | type GitHubPullRequestActivityPage, |
| 119 | type GitHubWorkflowRunPage, |
| 120 | type GitHubPullRequestHead, |
| 121 | type GitHubPullRequestListItem, |
| 122 | type GitHubPullRequestSearchItem, |
| 123 | type GitHubPullRequestStack, |
| 124 | type GitHubReviewThreadComments, |
| 125 | type GitHubRepositoryAccess, |
| 126 | type GitHubWorkflowRunApproval, |
| 127 | type GitHubReviewThreadEntry, |
| 128 | type GitHubReviewThreadPage, |
| 129 | type GitHubViewerAccess, |
| 130 | IMMEDIATELY_MERGEABLE, |
| 131 | } from "./gitHubPullRequestJson.ts"; |
| 132 | import { |
| 133 | gitHubActionsJobId, |
| 134 | tailLogLines, |
| 135 | type ProviderAcrossListCursor, |
| 136 | type ProviderChangeRequestSummary, |
| 137 | type ProviderCheckLog, |
| 138 | type ProviderCheckReference, |
| 139 | type ProviderCheckRerun, |
| 140 | type ProviderListCursor, |
| 141 | } from "@t3tools/source-control-core/server/PullRequestProvider"; |
| 142 | |
| 143 | export class GitHubPullRequestReadError extends Schema.TaggedError<GitHubPullRequestReadError>()( |
| 144 | "GitHubPullRequestReadError", |
| 145 | { |
| 146 | cwd: Schema.String, |
| 147 | operation: Schema.String, |
| 148 | cause: Schema.Defect(), |
| 149 | }, |
| 150 | ) { |
| 151 | override get message(): string { |
| 152 | return `GitHub returned an unreadable ${this.operation} response.`; |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | export class GitHubViewerLoginUnavailableError extends Schema.TaggedError<GitHubViewerLoginUnavailableError>()( |
| 157 | "GitHubViewerLoginUnavailableError", |
| 158 | { |
| 159 | cwd: Schema.String, |
| 160 | }, |
| 161 | ) { |
| 162 | override get message(): string { |
| 163 | return "GitHub returned no login for the authenticated account."; |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | export class GitHubDiffCursorError extends Schema.TaggedError<GitHubDiffCursorError>()( |
| 168 | "GitHubDiffCursorError", |
| 169 | { |
| 170 | cwd: Schema.String, |
| 171 | }, |
| 172 | ) { |
| 173 | override get message(): string { |
| 174 | return "The diff cursor was not one this pull request handed out."; |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | export class GitHubDiffCommitError extends Schema.TaggedError<GitHubDiffCommitError>()( |
| 179 | "GitHubDiffCommitError", |
| 180 | { |
| 181 | cwd: Schema.String, |
| 182 | }, |
| 183 | ) { |
| 184 | override get message(): string { |
| 185 | return "The named commit was not a commit sha."; |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | export class GitHubDiffRevisionsUnavailableError extends Schema.TaggedError<GitHubDiffRevisionsUnavailableError>()( |
| 190 | "GitHubDiffRevisionsUnavailableError", |
| 191 | { |
| 192 | cwd: Schema.String, |
| 193 | number: Schema.Int, |
| 194 | commit: Schema.optional(Schema.String), |
| 195 | }, |
| 196 | ) { |
| 197 | override get message(): string { |
| 198 | return this.commit === undefined |
| 199 | ? `Pull request #${this.number} reported no usable base and head revisions.` |
| 200 | : `Commit ${this.commit} reported no usable revisions for this file.`; |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | export class GitHubDiffFileContentsUnavailableError extends Schema.TaggedError<GitHubDiffFileContentsUnavailableError>()( |
| 205 | "GitHubDiffFileContentsUnavailableError", |
| 206 | { |
| 207 | cwd: Schema.String, |
| 208 | path: Schema.String, |
| 209 | reason: Schema.Literals(["oversized", "binary"]), |
| 210 | }, |
| 211 | ) { |
| 212 | override get message(): string { |
| 213 | return this.reason === "oversized" |
| 214 | ? `The diff file '${this.path}' exceeds the 1 MB expansion limit.` |
| 215 | : `The diff file '${this.path}' is binary.`; |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | export class GitHubRepositorySelectorError extends Schema.TaggedError<GitHubRepositorySelectorError>()( |
| 220 | "GitHubRepositorySelectorError", |
| 221 | { |
| 222 | cwd: Schema.String, |
| 223 | operation: Schema.String, |
| 224 | }, |
| 225 | ) { |
| 226 | override get message(): string { |
| 227 | return "A repository was named that GitHub cannot address."; |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | export class GitHubSubjectScopeError extends Schema.TaggedError<GitHubSubjectScopeError>()( |
| 232 | "GitHubSubjectScopeError", |
| 233 | { |
| 234 | cwd: Schema.String, |
| 235 | operation: Schema.String, |
| 236 | }, |
| 237 | ) { |
| 238 | override get message(): string { |
| 239 | return "The named subject did not belong to the named pull request."; |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | export class GitHubWorkflowApprovalRefusedError extends Schema.TaggedError<GitHubWorkflowApprovalRefusedError>()( |
| 244 | "GitHubWorkflowApprovalRefusedError", |
| 245 | { |
| 246 | cwd: Schema.String, |
| 247 | number: Schema.Int, |
| 248 | reason: Schema.Literals(["head-list-truncated", "head-not-unique", "run-list-truncated"]), |
| 249 | observedCount: Schema.Int, |
| 250 | limit: Schema.Int, |
| 251 | }, |
| 252 | ) { |
| 253 | override get message(): string { |
| 254 | if (this.reason === "head-list-truncated") { |
| 255 | return `GitHub returned more than ${this.limit} pull requests for this head branch.`; |
| 256 | } |
| 257 | if (this.reason === "head-not-unique") { |
| 258 | return `The head revision matched ${this.observedCount} pull requests instead of uniquely matching #${this.number}.`; |
| 259 | } |
| 260 | return `GitHub returned more than ${this.limit} workflow runs awaiting approval.`; |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | export class GitHubWorkflowApprovalHeadUnavailableError extends Schema.TaggedError<GitHubWorkflowApprovalHeadUnavailableError>()( |
| 265 | "GitHubWorkflowApprovalHeadUnavailableError", |
| 266 | { |
| 267 | cwd: Schema.String, |
| 268 | number: Schema.Int, |
| 269 | }, |
| 270 | ) { |
| 271 | override get message(): string { |
| 272 | return `GitHub did not report a complete head revision for #${this.number}.`; |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | export class GitHubWorkflowApprovalHeadChangedError extends Schema.TaggedError<GitHubWorkflowApprovalHeadChangedError>()( |
| 277 | "GitHubWorkflowApprovalHeadChangedError", |
| 278 | { |
| 279 | cwd: Schema.String, |
| 280 | number: Schema.Int, |
| 281 | }, |
| 282 | ) { |
| 283 | override get message(): string { |
| 284 | return `The head revision of #${this.number} changed before its workflows could be approved.`; |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | export class GitHubBranchDeletionRefusedError extends Schema.TaggedError<GitHubBranchDeletionRefusedError>()( |
| 289 | "GitHubBranchDeletionRefusedError", |
| 290 | { |
| 291 | number: Schema.Int, |
| 292 | reason: Schema.Literals([ |
| 293 | "open-pr", |
| 294 | "stack", |
| 295 | "source-unavailable", |
| 296 | "unsafe-branch", |
| 297 | "head-changed", |
| 298 | ]), |
| 299 | }, |
| 300 | ) { |
| 301 | override get message(): string { |
| 302 | switch (this.reason) { |
| 303 | case "open-pr": |
| 304 | return `Close or merge pull request #${this.number} before deleting its source branch.`; |
| 305 | case "stack": |
| 306 | return "Branch deletion is not supported for a stack."; |
| 307 | case "source-unavailable": |
| 308 | return `GitHub did not report a complete source branch for pull request #${this.number}.`; |
| 309 | case "unsafe-branch": |
| 310 | return "The source branch is a default or base branch and cannot be deleted here."; |
| 311 | case "head-changed": |
| 312 | return "The source branch has new commits and was not deleted."; |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | export type GitHubPullRequestApiError = |
| 318 | | GitHubBranchDeletionRefusedError |
| 319 | | GitHubStackActionError |
| 320 | | GitHubRequestPolicy.GitHubApiError |
| 321 | | GitHubPullRequestReadError |
| 322 | | GitHubDiffCursorError |
| 323 | | GitHubDiffCommitError |
| 324 | | GitHubDiffRevisionsUnavailableError |
| 325 | | GitHubDiffFileContentsUnavailableError |
| 326 | | GitHubRepositorySelectorError |
| 327 | | GitHubSubjectScopeError |
| 328 | | GitHubWorkflowApprovalRefusedError |
| 329 | | GitHubWorkflowApprovalHeadUnavailableError |
| 330 | | GitHubWorkflowApprovalHeadChangedError |
| 331 | | SourceControlRateLimit.SourceControlRateLimitPausedError |
| 332 | | GitHubViewerLoginUnavailableError; |
| 333 | |
| 334 | const isGraphQlClientError = (error: unknown): error is GraphQLClientError.GraphQLClientError => |
| 335 | GraphQLClientError.isGraphQLClientError(error); |
| 336 | |
| 337 | const { isNotFoundOnly } = GitHubGraphQlClient; |
| 338 | |
| 339 | const isGitHubApiResponseError = Schema.is(GitHubRequestPolicy.GitHubApiResponseError); |
| 340 | |
| 341 | const isGitHubServerError = (error: unknown): boolean => |
| 342 | isGitHubApiResponseError(error) && error.status >= 500; |
| 343 | |
| 344 | const isMissingPullRef = ({ path, type }: GraphQLClientError.GraphQLError): boolean => |
| 345 | type === "NOT_FOUND" && path?.join(".") === "repository.pullRequest.baseRef.compare"; |
| 346 | |
| 347 | const isRefusedRequestedReviewersOnly = (error: unknown): boolean => |
| 348 | isGraphQlClientError(error) && |
| 349 | error.reason._tag === "ResponseError" && |
| 350 | error.reason.status === 200 && |
| 351 | // A missing pull ref can come along; the retried read tolerates it. |
| 352 | error.reason.errors.every((graphQlError) => { |
| 353 | const { path, type } = graphQlError; |
| 354 | return ( |
| 355 | isMissingPullRef(graphQlError) || |
| 356 | (type === "FORBIDDEN" && |
| 357 | path?.length === 6 && |
| 358 | path[0] === "repository" && |
| 359 | path[1] === "pullRequest" && |
| 360 | path[2] === "reviewRequests" && |
| 361 | path[3] === "nodes" && |
| 362 | typeof path[4] === "number" && |
| 363 | Number.isInteger(path[4]) && |
| 364 | path[4] >= 0 && |
| 365 | path[5] === "requestedReviewer") |
| 366 | ); |
| 367 | }); |
| 368 | |
| 369 | const isMissingPullRefOnly = <E>( |
| 370 | error: E, |
| 371 | ): error is E & |
| 372 | GraphQLClientError.GraphQLClientError & { readonly reason: GraphQLClientError.ResponseError } => |
| 373 | isGraphQlClientError(error) && |
| 374 | error.reason._tag === "ResponseError" && |
| 375 | error.reason.status === 200 && |
| 376 | error.reason.errors.every(isMissingPullRef); |
| 377 | |
| 378 | /** |
| 379 | * GitHub can lack `refs/pull/<number>/head` for a pull request it otherwise answers, and then |
| 380 | * fails only the comparison against it. The rest of that answer stands, its comparison unknown. |
| 381 | */ |
| 382 | const toleratingMissingPullRef = |
| 383 | <A, R2>(decode: (data: unknown) => Effect.Effect<A, Schema.SchemaError, R2>) => |
| 384 | <E, R>(effect: Effect.Effect<A, E, R>) => |
| 385 | effect.pipe( |
| 386 | Effect.catchIf(isMissingPullRefOnly, (error) => |
| 387 | decode(error.reason.data).pipe(Effect.mapError(() => error)), |
| 388 | ), |
| 389 | ); |
| 390 | const decodePullRequestCore = Schema.decodeUnknownEffect(PullRequestCore.result); |
| 391 | const decodePullRequestActionState = Schema.decodeUnknownEffect(PullRequestActionState.result); |
| 392 | |
| 393 | /** A large pull request can produce a multi-megabyte patch; past this it is truncated. */ |
| 394 | const DIFF_MAX_OUTPUT_BYTES = 8 * 1024 * 1024; |
| 395 | const WITHHELD_FILE_DIFF_MAX_OUTPUT_BYTES = 32 * 1024 * 1024; |
| 396 | // Withheld files are mostly minified bundles; megabyte lines would freeze the client's layout. |
| 397 | const WITHHELD_FILE_MAX_LINE_LENGTH = 1_000; |
| 398 | const DIFF_TIMEOUT = Duration.seconds(60); |
| 399 | const DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024; |
| 400 | |
| 401 | const LIST_STATES: Record<PullRequestListState, ReadonlyArray<"OPEN" | "CLOSED" | "MERGED">> = { |
| 402 | all: ["OPEN", "CLOSED", "MERGED"], |
| 403 | open: ["OPEN"], |
| 404 | closed: ["CLOSED", "MERGED"], |
| 405 | merged: ["MERGED"], |
| 406 | }; |
| 407 | |
| 408 | interface GitHubPullRequestListPage<Item = GitHubPullRequestListItem> { |
| 409 | readonly items: ReadonlyArray<Item>; |
| 410 | readonly rawCount: number; |
| 411 | readonly endCursor: string | null; |
| 412 | } |
| 413 | |
| 414 | /** |
| 415 | * Pages of up to a hundred until `rows` have arrived or GitHub has no more. Each page asks |
| 416 | * for only the rows still missing, so the last one does not overshoot. |
| 417 | */ |
| 418 | const collect = Effect.fn("GitHubPullRequestApi.collect")(function* <Item, E>( |
| 419 | rows: number, |
| 420 | page: (after: string | null, rows: number) => Effect.Effect<GitHubPullRequestListPage<Item>, E>, |
| 421 | ) { |
| 422 | const countRows = (pages: ReadonlyArray<GitHubPullRequestListPage<Item>>) => |
| 423 | pages.reduce((total, read) => total + read.rawCount, 0); |
| 424 | const pages: GitHubPullRequestListPage<Item>[] = []; |
| 425 | const seen = new Set<string>(); |
| 426 | let after: string | null = null; |
| 427 | let truncated = false; |
| 428 | while (true) { |
| 429 | const read: GitHubPullRequestListPage<Item> = yield* page(after, rows - countRows(pages)); |
| 430 | pages.push(read); |
| 431 | const next = read.endCursor; |
| 432 | if (next === null) break; |
| 433 | // `truncated` also covers a cursor GitHub repeated before `rows` arrived. |
| 434 | if (seen.has(next) || countRows(pages) >= rows) { |
| 435 | truncated = true; |
| 436 | break; |
| 437 | } |
| 438 | seen.add(next); |
| 439 | after = next; |
| 440 | } |
| 441 | return { |
| 442 | items: pages.flatMap((read) => read.items), |
| 443 | rawCount: countRows(pages), |
| 444 | truncated, |
| 445 | }; |
| 446 | }); |
| 447 | |
| 448 | const PULL_REQUEST_FALLBACK_MAX_ROWS = 1_000; |
| 449 | |
| 450 | // Larger pages make GitHub drop patches and report those files as 0/0. |
| 451 | const DIFF_FILES_PAGE_SIZE = 30; |
| 452 | const FILES_VIEWED_MAX_PAGES = 5; |
| 453 | const FILES_VIEWED_PER_REQUEST = 100; |
| 454 | |
| 455 | export const NODE_ID_CACHE_CAPACITY = 128; |
| 456 | |
| 457 | const REVIEW_THREAD_PAGES = 10; |
| 458 | |
| 459 | const CHECK_CONTEXT_PAGES = 10; |
| 460 | |
| 461 | export interface GitHubPullRequestListBatch { |
| 462 | readonly items: ReadonlyArray<GitHubPullRequestListItem>; |
| 463 | readonly truncated: boolean; |
| 464 | /** False for unsearchable pages returned in `gh` order. */ |
| 465 | readonly continues: boolean; |
| 466 | } |
| 467 | |
| 468 | export interface GitHubPullRequestStat { |
| 469 | readonly repository: string; |
| 470 | readonly number: number; |
| 471 | readonly additions: number; |
| 472 | readonly deletions: number; |
| 473 | } |
| 474 | |
| 475 | /** Four parallel batches of 25 took ~2.1s; one batch of 100 took ~5.2s. */ |
| 476 | const STAT_ALIASES_PER_REQUEST = 25; |
| 477 | // Cache checks stagger reads across scheduler ticks; allow time to batch. |
| 478 | const SUMMARY_BATCH_WINDOW = "10 millis"; |
| 479 | |
| 480 | export interface GitHubPullRequestSearchBatch { |
| 481 | readonly items: ReadonlyArray<GitHubPullRequestSearchItem>; |
| 482 | readonly truncated: boolean; |
| 483 | } |
| 484 | |
| 485 | export interface GitHubPullRequestDiffSlice { |
| 486 | readonly patch: string; |
| 487 | /** Hunks were withheld within this slice. */ |
| 488 | readonly truncated: boolean; |
| 489 | readonly nextCursor: string | null; |
| 490 | readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>; |
| 491 | readonly withheldFilesReadable?: boolean; |
| 492 | } |
| 493 | |
| 494 | export interface GitHubPullRequestFilesViewed { |
| 495 | readonly files: ReadonlyArray<PullRequestFileViewed>; |
| 496 | readonly truncated: boolean; |
| 497 | } |
| 498 | |
| 499 | export interface GitHubPullRequestFileStats { |
| 500 | readonly files: ReadonlyArray<GitHubPullRequestFileStat>; |
| 501 | readonly truncated: boolean; |
| 502 | } |
| 503 | |
| 504 | export class GitHubPullRequestApi extends Context.Service< |
| 505 | GitHubPullRequestApi, |
| 506 | { |
| 507 | readonly withVerifiedCredential: <A, E, R>( |
| 508 | input: { readonly cwd: string; readonly host: string; readonly repository?: string }, |
| 509 | use: (identity: { |
| 510 | readonly accountId: string; |
| 511 | readonly viewer: string; |
| 512 | readonly credentialFingerprint: string; |
| 513 | }) => Effect.Effect<A, E, R>, |
| 514 | ) => Effect.Effect<A, E | GitHubPullRequestApiError, R>; |
| 515 | readonly getRoutingIdentity: (input: { |
| 516 | readonly cwd: string; |
| 517 | readonly host: string; |
| 518 | }) => Effect.Effect< |
| 519 | { readonly accountId: string; readonly viewer: string }, |
| 520 | GitHubPullRequestApiError |
| 521 | >; |
| 522 | readonly getViewerLogin: (input: { |
| 523 | readonly cwd: string; |
| 524 | readonly host: string; |
| 525 | }) => Effect.Effect<string, GitHubPullRequestApiError>; |
| 526 | |
| 527 | readonly listPullRequests: (input: { |
| 528 | readonly cwd: string; |
| 529 | readonly repository: string; |
| 530 | readonly host: string; |
| 531 | readonly state: PullRequestListState; |
| 532 | readonly involvement: PullRequestInvolvement; |
| 533 | readonly viewer: string; |
| 534 | readonly limit: number; |
| 535 | readonly query?: string | undefined; |
| 536 | readonly cursor?: ProviderListCursor | undefined; |
| 537 | readonly filters?: PullRequestListFilters | undefined; |
| 538 | }) => Effect.Effect<GitHubPullRequestListBatch, GitHubPullRequestApiError>; |
| 539 | |
| 540 | readonly searchPullRequests: (input: { |
| 541 | readonly cwd: string; |
| 542 | readonly host: string; |
| 543 | readonly repositories: ReadonlyArray<string>; |
| 544 | readonly state: PullRequestListState; |
| 545 | readonly involvement: PullRequestInvolvement; |
| 546 | readonly viewer: string; |
| 547 | readonly limit: number; |
| 548 | readonly query?: string | undefined; |
| 549 | readonly cursor?: ProviderAcrossListCursor | undefined; |
| 550 | readonly filters?: PullRequestListFilters | undefined; |
| 551 | }) => Effect.Effect<GitHubPullRequestSearchBatch, GitHubPullRequestApiError>; |
| 552 | |
| 553 | readonly listPullRequestStats: (input: { |
| 554 | readonly cwd: string; |
| 555 | readonly host: string; |
| 556 | readonly changeRequests: ReadonlyArray<{ |
| 557 | readonly repository: string; |
| 558 | readonly number: number; |
| 559 | }>; |
| 560 | }) => Effect.Effect<ReadonlyArray<GitHubPullRequestStat>, GitHubPullRequestApiError>; |
| 561 | |
| 562 | readonly getPullRequestSummary: (input: { |
| 563 | readonly cwd: string; |
| 564 | readonly repository: string; |
| 565 | readonly host: string; |
| 566 | readonly number: number; |
| 567 | }) => Effect.Effect<ProviderChangeRequestSummary, GitHubPullRequestApiError>; |
| 568 | /** Null triggers a full watch read when GitHub gives no answer. */ |
| 569 | readonly getPullRequestWatchFingerprint: (input: { |
| 570 | readonly cwd: string; |
| 571 | readonly repository: string; |
| 572 | readonly host: string; |
| 573 | readonly number: number; |
| 574 | }) => Effect.Effect<GitHubPullRequestWatchFingerprint | null, GitHubPullRequestApiError>; |
| 575 | readonly pullRequestEvents: Effect.Success<typeof GitHubPullRequestEvents.make>; |
| 576 | |
| 577 | readonly revalidateChecks: Effect.Success<typeof makeChecksRevalidator>; |
| 578 | |
| 579 | readonly getPullRequestDetail: (input: { |
| 580 | readonly cwd: string; |
| 581 | readonly repository: string; |
| 582 | readonly host: string; |
| 583 | readonly number: number; |
| 584 | }) => Effect.Effect<GitHubPullRequestCore, GitHubPullRequestApiError>; |
| 585 | |
| 586 | readonly getPullRequestPreview: (input: { |
| 587 | readonly cwd: string; |
| 588 | readonly repository: string; |
| 589 | readonly host: string; |
| 590 | readonly number: number; |
| 591 | }) => Effect.Effect< |
| 592 | Omit<PullRequestPreview, "projectId" | "repository">, |
| 593 | GitHubPullRequestApiError |
| 594 | >; |
| 595 | |
| 596 | readonly listWorkflowRunsRequiringApproval: (input: { |
| 597 | readonly cwd: string; |
| 598 | readonly repository: string; |
| 599 | readonly host: string; |
| 600 | readonly number: number; |
| 601 | readonly headSha: string; |
| 602 | readonly headBranch: string; |
| 603 | readonly headRepositoryOwner: string; |
| 604 | readonly isCrossRepository: true; |
| 605 | }) => Effect.Effect<ReadonlyArray<GitHubWorkflowRunApproval>, GitHubPullRequestApiError>; |
| 606 | |
| 607 | /** The head's workflow runs that have not finished, the latest 100. */ |
| 608 | readonly listUnfinishedWorkflowRuns: (input: { |
| 609 | readonly cwd: string; |
| 610 | readonly repository: string; |
| 611 | readonly host: string; |
| 612 | readonly headSha: string; |
| 613 | }) => Effect.Effect<ReadonlyArray<GitHubWorkflowRunApproval>, GitHubPullRequestApiError>; |
| 614 | |
| 615 | readonly getPullRequestStack: (input: { |
| 616 | readonly cwd: string; |
| 617 | readonly includeDetails?: boolean; |
| 618 | readonly repository: string; |
| 619 | readonly host: string; |
| 620 | readonly number: number; |
| 621 | }) => Effect.Effect<GitHubPullRequestStack | null, GitHubPullRequestApiError>; |
| 622 | |
| 623 | readonly getPullRequestActivity: (input: { |
| 624 | readonly cwd: string; |
| 625 | readonly repository: string; |
| 626 | readonly host: string; |
| 627 | readonly number: number; |
| 628 | }) => Effect.Effect<GitHubPullRequestActivity, GitHubPullRequestApiError>; |
| 629 | |
| 630 | readonly getPullRequestDiff: (input: { |
| 631 | readonly cwd: string; |
| 632 | readonly repository: string; |
| 633 | readonly host: string; |
| 634 | readonly number: number; |
| 635 | readonly cursor?: string | undefined; |
| 636 | readonly commit?: string | undefined; |
| 637 | readonly path?: string | undefined; |
| 638 | }) => Effect.Effect<GitHubPullRequestDiffSlice, GitHubPullRequestApiError>; |
| 639 | |
| 640 | readonly getPullRequestDiffFileContents: (input: { |
| 641 | readonly cwd: string; |
| 642 | readonly repository: string; |
| 643 | readonly host: string; |
| 644 | readonly number: number; |
| 645 | readonly commit?: string | undefined; |
| 646 | readonly changeType: "change" | "rename-pure" | "rename-changed" | "new" | "deleted"; |
| 647 | readonly oldPath: string; |
| 648 | readonly newPath: string; |
| 649 | }) => Effect.Effect< |
| 650 | { readonly oldContents: string; readonly newContents: string }, |
| 651 | GitHubPullRequestApiError |
| 652 | >; |
| 653 | |
| 654 | readonly getPullRequestFilesViewed: (input: { |
| 655 | readonly cwd: string; |
| 656 | readonly repository: string; |
| 657 | readonly host: string; |
| 658 | readonly number: number; |
| 659 | }) => Effect.Effect<GitHubPullRequestFilesViewed, GitHubPullRequestApiError>; |
| 660 | |
| 661 | readonly getPullRequestFileStats: (input: { |
| 662 | readonly cwd: string; |
| 663 | readonly repository: string; |
| 664 | readonly host: string; |
| 665 | readonly number: number; |
| 666 | }) => Effect.Effect<GitHubPullRequestFileStats, GitHubPullRequestApiError>; |
| 667 | |
| 668 | /** |
| 669 | * GitHub takes a single path per mutation, so a burst is batched with aliases into one |
| 670 | * document rather than one subprocess per press. |
| 671 | */ |
| 672 | readonly setPullRequestFilesViewed: (input: { |
| 673 | readonly cwd: string; |
| 674 | readonly repository: string; |
| 675 | readonly host: string; |
| 676 | readonly number: number; |
| 677 | readonly files: ReadonlyArray<{ readonly path: string; readonly viewed: boolean }>; |
| 678 | }) => Effect.Effect<void, GitHubPullRequestApiError>; |
| 679 | |
| 680 | readonly listReviewThreadComments: (input: { |
| 681 | readonly cwd: string; |
| 682 | readonly repository: string; |
| 683 | readonly host: string; |
| 684 | readonly number: number; |
| 685 | }) => Effect.Effect<GitHubReviewThreadComments, GitHubPullRequestApiError>; |
| 686 | |
| 687 | readonly getReviewThreadComments: (input: { |
| 688 | readonly cwd: string; |
| 689 | readonly repository: string; |
| 690 | readonly host: string; |
| 691 | readonly number: number; |
| 692 | readonly threadId: string; |
| 693 | readonly cursor: string; |
| 694 | }) => Effect.Effect<PullRequestThreadCommentsResult, GitHubPullRequestApiError>; |
| 695 | |
| 696 | readonly getViewerAccess: (input: { |
| 697 | readonly cwd: string; |
| 698 | readonly repository: string; |
| 699 | readonly host: string; |
| 700 | readonly number: number; |
| 701 | readonly allowReserve?: boolean | undefined; |
| 702 | }) => Effect.Effect<GitHubViewerAccess & GitHubRepositoryAccess, GitHubPullRequestApiError>; |
| 703 | |
| 704 | readonly listReviewerCandidates: (input: { |
| 705 | readonly cwd: string; |
| 706 | readonly repository: string; |
| 707 | readonly host: string; |
| 708 | readonly number: number; |
| 709 | readonly query?: string | undefined; |
| 710 | }) => Effect.Effect<PullRequestReviewerCandidateList, GitHubPullRequestApiError>; |
| 711 | |
| 712 | readonly setReviewerRequest: (input: { |
| 713 | readonly cwd: string; |
| 714 | readonly repository: string; |
| 715 | readonly host: string; |
| 716 | readonly number: number; |
| 717 | readonly reviewers: ReadonlyArray<{ |
| 718 | readonly id: string; |
| 719 | readonly kind: PullRequestReviewerKind; |
| 720 | }>; |
| 721 | readonly requested: boolean; |
| 722 | }) => Effect.Effect<void, GitHubPullRequestApiError>; |
| 723 | |
| 724 | readonly listLabelCandidates: (input: { |
| 725 | readonly cwd: string; |
| 726 | readonly repository: string; |
| 727 | readonly host: string; |
| 728 | readonly number: number; |
| 729 | }) => Effect.Effect<PullRequestLabelCandidateList, GitHubPullRequestApiError>; |
| 730 | |
| 731 | readonly listRepositoryLabels: (input: { |
| 732 | readonly cwd: string; |
| 733 | readonly repository: string; |
| 734 | readonly host: string; |
| 735 | readonly query?: string | undefined; |
| 736 | }) => Effect.Effect< |
| 737 | { readonly items: ReadonlyArray<PullRequestLabel>; readonly truncated: boolean }, |
| 738 | GitHubPullRequestApiError |
| 739 | >; |
| 740 | |
| 741 | readonly searchRepositoryAuthors: (input: { |
| 742 | readonly cwd: string; |
| 743 | readonly repository: string; |
| 744 | readonly host: string; |
| 745 | readonly query?: string | undefined; |
| 746 | }) => Effect.Effect< |
| 747 | { readonly items: ReadonlyArray<PullRequestActor>; readonly truncated: boolean }, |
| 748 | GitHubPullRequestApiError |
| 749 | >; |
| 750 | |
| 751 | readonly searchRepositoryReferences: (input: { |
| 752 | readonly cwd: string; |
| 753 | readonly repository: string; |
| 754 | readonly host: string; |
| 755 | readonly query?: string | undefined; |
| 756 | }) => Effect.Effect< |
| 757 | { |
| 758 | readonly items: ReadonlyArray<PullRequestReferenceCandidate>; |
| 759 | readonly truncated: boolean; |
| 760 | }, |
| 761 | GitHubPullRequestApiError |
| 762 | >; |
| 763 | |
| 764 | readonly setLabels: (input: { |
| 765 | readonly cwd: string; |
| 766 | readonly repository: string; |
| 767 | readonly host: string; |
| 768 | readonly number: number; |
| 769 | readonly labels: ReadonlyArray<string>; |
| 770 | readonly applied: boolean; |
| 771 | }) => Effect.Effect<void, GitHubPullRequestApiError>; |
| 772 | |
| 773 | readonly readCheckLogs: (input: { |
| 774 | readonly host: string; |
| 775 | readonly repository: string; |
| 776 | readonly checks: ReadonlyArray<ProviderCheckReference>; |
| 777 | readonly tailLines: number; |
| 778 | }) => Effect.Effect<ReadonlyArray<ProviderCheckLog>, GitHubPullRequestApiError>; |
| 779 | readonly rerunChecks: (input: { |
| 780 | readonly host: string; |
| 781 | readonly repository: string; |
| 782 | readonly checks: ReadonlyArray<ProviderCheckReference>; |
| 783 | }) => Effect.Effect<ReadonlyArray<ProviderCheckRerun>, GitHubPullRequestApiError>; |
| 784 | readonly runPullRequestAction: (input: { |
| 785 | readonly cwd: string; |
| 786 | readonly repository: string; |
| 787 | readonly host: string; |
| 788 | readonly number: number; |
| 789 | readonly action: PullRequestAction; |
| 790 | readonly stackNumber?: number; |
| 791 | readonly expectedStackHeads?: ReadonlyArray<PullRequestStackHead>; |
| 792 | readonly expectedHeadSha?: string; |
| 793 | readonly removeAgentCreditsOnMerge?: boolean; |
| 794 | readonly mergeMethod?: PullRequestMergeMethod; |
| 795 | readonly updateMethod?: PullRequestUpdateMethod; |
| 796 | }) => Effect.Effect<ProviderChangeRequestSummary | void, GitHubPullRequestApiError>; |
| 797 | |
| 798 | readonly commentOnPullRequest: (input: { |
| 799 | readonly cwd: string; |
| 800 | readonly repository: string; |
| 801 | readonly host: string; |
| 802 | readonly number: number; |
| 803 | readonly body: string; |
| 804 | }) => Effect.Effect<void, GitHubPullRequestApiError>; |
| 805 | |
| 806 | readonly submitReview: (input: { |
| 807 | readonly cwd: string; |
| 808 | readonly repository: string; |
| 809 | readonly host: string; |
| 810 | readonly number: number; |
| 811 | readonly verdict: PullRequestReviewVerdict; |
| 812 | readonly body: string; |
| 813 | readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>; |
| 814 | }) => Effect.Effect<void, GitHubPullRequestApiError>; |
| 815 | |
| 816 | readonly replyToReviewThread: (input: { |
| 817 | readonly cwd: string; |
| 818 | readonly repository: string; |
| 819 | readonly host: string; |
| 820 | readonly threadId: string; |
| 821 | readonly body: string; |
| 822 | }) => Effect.Effect<void, GitHubPullRequestApiError>; |
| 823 | |
| 824 | readonly setReviewThreadResolution: (input: { |
| 825 | readonly cwd: string; |
| 826 | readonly repository: string; |
| 827 | readonly host: string; |
| 828 | readonly threadId: string; |
| 829 | readonly resolved: boolean; |
| 830 | }) => Effect.Effect<void, GitHubPullRequestApiError>; |
| 831 | |
| 832 | readonly setReaction: (input: { |
| 833 | readonly cwd: string; |
| 834 | readonly repository: string; |
| 835 | readonly host: string; |
| 836 | readonly number: number; |
| 837 | readonly subjectId?: string | undefined; |
| 838 | readonly content: PullRequestReactionContent; |
| 839 | readonly reacted: boolean; |
| 840 | }) => Effect.Effect<void, GitHubPullRequestApiError>; |
| 841 | |
| 842 | readonly updatePullRequest: (input: { |
| 843 | readonly maintainerCanModify?: boolean | undefined; |
| 844 | readonly cwd: string; |
| 845 | readonly repository: string; |
| 846 | readonly host: string; |
| 847 | readonly number: number; |
| 848 | readonly title?: string | undefined; |
| 849 | readonly body?: string | undefined; |
| 850 | }) => Effect.Effect<void, GitHubPullRequestApiError>; |
| 851 | |
| 852 | readonly updateComment: (input: { |
| 853 | readonly cwd: string; |
| 854 | readonly repository: string; |
| 855 | readonly host: string; |
| 856 | readonly number: number; |
| 857 | readonly commentId: string; |
| 858 | readonly kind: "issue-comment" | "review-comment"; |
| 859 | readonly body: string; |
| 860 | }) => Effect.Effect<void, GitHubPullRequestApiError>; |
| 861 | } |
| 862 | >()("@t3tools/source-control-github/server/GitHubPullRequestApi") {} |
| 863 | |
| 864 | const CHECK_LOG_MAX_BYTES = 16 * 1024 * 1024; |
| 865 | const NOT_A_JOB = "This check is not a GitHub Actions job, so GitHub cannot re-run it."; |
| 866 | const decodeActionsJob = Schema.decodeEffect( |
| 867 | Schema.fromJsonString(Schema.Struct({ run_id: Schema.Number })), |
| 868 | ); |
| 869 | const decodeRunJobs = Schema.decodeEffect( |
| 870 | Schema.fromJsonString( |
| 871 | Schema.Struct({ |
| 872 | total_count: Schema.Number, |
| 873 | jobs: Schema.Array( |
| 874 | Schema.Struct({ id: Schema.Number, conclusion: Schema.NullOr(Schema.String) }), |
| 875 | ), |
| 876 | }), |
| 877 | ), |
| 878 | ); |
| 879 | const FAILED_CONCLUSIONS = new Set(["failure", "cancelled", "timed_out", "startup_failure"]); |
| 880 | const ONE_JOB_AT_A_TIME = |
| 881 | "GitHub re-runs one job of a run at a time. Re-run this one after the other finishes."; |
| 882 | |
| 883 | interface LocatedCheckJob { |
| 884 | readonly check: ProviderCheckReference; |
| 885 | readonly jobId: string | null; |
| 886 | readonly runId: number | null; |
| 887 | readonly detail: string | null; |
| 888 | } |
| 889 | |
| 890 | function parseRepositorySelector(value: string): { |
| 891 | readonly owner: string; |
| 892 | readonly name: string; |
| 893 | } { |
| 894 | const parts = value.trim().split("/").filter(Boolean); |
| 895 | return { name: parts.at(-1) ?? "", owner: parts.at(-2) ?? "" }; |
| 896 | } |
| 897 | |
| 898 | /** Bound decimal length to prevent exponential notation in request paths. */ |
| 899 | function diffCursorPage(cursor: string): number | null { |
| 900 | return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null; |
| 901 | } |
| 902 | |
| 903 | const REVIEW_QUALIFIERS = { |
| 904 | approved: "approved", |
| 905 | "changes-requested": "changes_requested", |
| 906 | "review-required": "required", |
| 907 | none: "none", |
| 908 | } as const; |
| 909 | |
| 910 | /** Labels/logins cannot contain quotes; strip them to prevent qualifier injection. */ |
| 911 | function qualifierValue(value: string): string { |
| 912 | return `"${value.replaceAll('"', "").trim()}"`; |
| 913 | } |
| 914 | |
| 915 | function filterQualifiers( |
| 916 | filters: PullRequestListFilters | undefined, |
| 917 | viewer: string, |
| 918 | ): ReadonlyArray<string> { |
| 919 | if (filters === undefined) return []; |
| 920 | return [ |
| 921 | // Commas within a qualifier mean OR to GitHub. |
| 922 | ...(filters.labels ?? []).flatMap((group) => |
| 923 | group.length === 0 ? [] : [`label:${group.map(qualifierValue).join(",")}`], |
| 924 | ), |
| 925 | ...(filters.excludedLabels ?? []).map((label) => `-label:${qualifierValue(label)}`), |
| 926 | ...(filters.author === undefined |
| 927 | ? [] |
| 928 | : [`author:${qualifierValue(resolvePullRequestAuthorFilter(filters.author, viewer))}`]), |
| 929 | ...(filters.draft === undefined ? [] : [`draft:${filters.draft === "only"}`]), |
| 930 | ...(filters.review === undefined ? [] : [`review:${REVIEW_QUALIFIERS[filters.review]}`]), |
| 931 | ...(filters.checks === undefined |
| 932 | ? [] |
| 933 | : [`status:${filters.checks === "passing" ? "success" : "failure"}`]), |
| 934 | ]; |
| 935 | } |
| 936 | |
| 937 | function matchesFilters( |
| 938 | item: GitHubPullRequestListItem, |
| 939 | filters: PullRequestListFilters | undefined, |
| 940 | viewer: string, |
| 941 | ): boolean { |
| 942 | if (filters === undefined) return true; |
| 943 | const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase())); |
| 944 | const holds = (label: string) => labels.has(label.trim().toLowerCase()); |
| 945 | return ( |
| 946 | (filters.draft === undefined || item.isDraft === (filters.draft === "only")) && |
| 947 | (filters.review === undefined || |
| 948 | (filters.review === "none" |
| 949 | ? item.reviewDecision === null |
| 950 | : item.reviewDecision === filters.review)) && |
| 951 | (filters.checks === undefined || item.checksState === filters.checks) && |
| 952 | (filters.labels === undefined || filters.labels.every((group) => group.some(holds))) && |
| 953 | (filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) && |
| 954 | (filters.author === undefined || |
| 955 | item.author?.login.toLowerCase() === |
| 956 | resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase()) |
| 957 | ); |
| 958 | } |
| 959 | |
| 960 | function matchesUnsortedListing( |
| 961 | item: GitHubPullRequestListItem, |
| 962 | input: { |
| 963 | readonly state: PullRequestListState; |
| 964 | readonly involvement: PullRequestInvolvement; |
| 965 | readonly viewer: string; |
| 966 | readonly filters?: PullRequestListFilters | undefined; |
| 967 | }, |
| 968 | ): boolean { |
| 969 | const matchesState = input.state === "all" || item.state === input.state; |
| 970 | const viewer = input.viewer.toLowerCase(); |
| 971 | const matchesInvolvement = |
| 972 | input.involvement === "all" || |
| 973 | (input.involvement === "authored" |
| 974 | ? item.author?.login.toLowerCase() === viewer |
| 975 | : item.hasTeamReviewRequest || |
| 976 | item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer)); |
| 977 | return matchesState && matchesInvolvement && matchesFilters(item, input.filters, input.viewer); |
| 978 | } |
| 979 | |
| 980 | const SEARCH_REPOSITORY = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; |
| 981 | |
| 982 | /** Unquoted repo: values must not inject qualifiers. */ |
| 983 | function searchQuery(input: { |
| 984 | readonly repositories: ReadonlyArray<string>; |
| 985 | readonly state: PullRequestListState; |
| 986 | readonly involvement: PullRequestInvolvement; |
| 987 | readonly viewer: string; |
| 988 | readonly query?: string | undefined; |
| 989 | readonly cursor?: Pick<ProviderListCursor, "updatedBefore"> | undefined; |
| 990 | readonly filters?: PullRequestListFilters | undefined; |
| 991 | }): string | null { |
| 992 | if (input.repositories.length === 0) return null; |
| 993 | const repositories = input.repositories.map((repository) => repository.trim()); |
| 994 | if (!repositories.every((repository) => SEARCH_REPOSITORY.test(repository))) return null; |
| 995 | const query = input.query?.trim() ?? ""; |
| 996 | return [ |
| 997 | "is:pr", |
| 998 | ...(input.state === "open" ? ["is:open"] : []), |
| 999 | ...(input.state === "closed" ? ["is:closed", "is:unmerged"] : []), |
| 1000 | ...(input.state === "merged" ? ["is:merged"] : []), |
| 1001 | ...(input.involvement === "authored" ? [`author:${input.viewer}`] : []), |
| 1002 | ...(input.involvement === "reviewing" ? [`review-requested:${input.viewer}`] : []), |
| 1003 | ...(query.length === 0 ? [] : [searchPhrase(query)]), |
| 1004 | ...(input.cursor === undefined ? [] : [`updated:<=${input.cursor.updatedBefore}`]), |
| 1005 | ...filterQualifiers(input.filters, input.viewer), |
| 1006 | "sort:updated-desc", |
| 1007 | ...repositories.map((repository) => `repo:${repository}`), |
| 1008 | ].join(" "); |
| 1009 | } |
| 1010 | |
| 1011 | const decodeRevisionRefs = Schema.decodeUnknownOption( |
| 1012 | Schema.fromJsonString( |
| 1013 | Schema.Struct({ |
| 1014 | sha: Schema.optional(Schema.String), |
| 1015 | parents: Schema.optional(Schema.Array(Schema.Struct({ sha: Schema.String }))), |
| 1016 | base: Schema.optional(Schema.Struct({ sha: Schema.String })), |
| 1017 | head: Schema.optional(Schema.Struct({ sha: Schema.String })), |
| 1018 | }), |
| 1019 | ), |
| 1020 | ); |
| 1021 | |
| 1022 | /** Where a pull request's head forked off its base, the commit its patch is computed from. */ |
| 1023 | const decodeMergeBase = Schema.decodeUnknownOption( |
| 1024 | Schema.fromJsonString( |
| 1025 | Schema.Struct({ merge_base_commit: Schema.Struct({ sha: Schema.String }) }), |
| 1026 | ), |
| 1027 | ); |
| 1028 | |
| 1029 | // GitHub has no fast-forward-only merge; the service refuses methods a host does not advertise. |
| 1030 | const GRAPHQL_MERGE_METHODS: Partial< |
| 1031 | Record<PullRequestMergeMethod, "MERGE" | "SQUASH" | "REBASE"> |
| 1032 | > = { merge: "MERGE", squash: "SQUASH", rebase: "REBASE" }; |
| 1033 | |
| 1034 | const PullRequestGraphQLGroup = GraphQLGroup.merge( |
| 1035 | PullRequestBatchesGraphQLGroup, |
| 1036 | GraphQLGroup.make(LenientPullRequestSearch, LenientPullRequestList), |
| 1037 | PullRequestReadsGraphQLGroup, |
| 1038 | PullRequestReviewsGraphQLGroup, |
| 1039 | PullRequestMutationsGraphQLGroup, |
| 1040 | ).middleware(GitHubGraphQlClient.GitHubGraphQlAuth); |
| 1041 | |
| 1042 | interface RestReadInput<A> { |
| 1043 | readonly cwd: string; |
| 1044 | readonly host: string; |
| 1045 | readonly operation: string; |
| 1046 | readonly path: string; |
| 1047 | readonly decode: (raw: string) => Result.Result<A, unknown>; |
| 1048 | } |
| 1049 | |
| 1050 | /** @public */ |
| 1051 | export const make = Effect.gen(function* () { |
| 1052 | const api = yield* GitHubRest.GitHubRest; |
| 1053 | const appAccess = yield* GitHubAppAccess.GitHubAppAccess; |
| 1054 | const policy = yield* GitHubRequestPolicy.GitHubRequestPolicy; |
| 1055 | const httpClient = yield* HttpClient.HttpClient; |
| 1056 | const sourceControlHost = yield* SourceControlHost.SourceControlHost; |
| 1057 | const fileSystem = yield* FileSystem.FileSystem; |
| 1058 | const revalidateChecks = yield* makeChecksRevalidator; |
| 1059 | const client = yield* GraphQLClient.make(PullRequestGraphQLGroup).pipe( |
| 1060 | Effect.provide(GitHubGraphQlClient.layer), |
| 1061 | ); |
| 1062 | const routingIdentities = new Map< |
| 1063 | string, |
| 1064 | { |
| 1065 | at: number; |
| 1066 | value: { accountId: string; viewer: string }; |
| 1067 | } |
| 1068 | >(); |
| 1069 | const identityLocks = new Map<string, { gate: Semaphore.Semaphore; users: number }>(); |
| 1070 | const RoutingIdentity = Schema.Struct({ |
| 1071 | id: PositiveInt, |
| 1072 | login: TrimmedNonEmptyString, |
| 1073 | }); |
| 1074 | const decodeRoutingIdentity = Schema.decodeUnknownEffect(Schema.fromJsonString(RoutingIdentity)); |
| 1075 | const decodeViewerIdentity = Schema.decodeUnknownEffect(RoutingIdentity); |
| 1076 | const captureVerifiedCredential = Effect.fn("GitHubPullRequestApi.captureVerifiedCredential")( |
| 1077 | function* (input: { |
| 1078 | readonly cwd: string; |
| 1079 | readonly host: string; |
| 1080 | readonly repository?: string; |
| 1081 | }) { |
| 1082 | const unavailable = () => new GitHubViewerLoginUnavailableError({ cwd: input.cwd }); |
| 1083 | const host = input.host.toLowerCase(); |
| 1084 | // A pinned credential is never handed on to another, so pick one that reaches the repository. |
| 1085 | const { token, fingerprint: key } = |
| 1086 | input.repository === undefined |
| 1087 | ? yield* api.credential(host) |
| 1088 | : yield* appAccess.credentialFor(host, input.repository); |
| 1089 | const credential = { host, token, credentialFingerprint: key }; |
| 1090 | return yield* Effect.acquireUseRelease( |
| 1091 | Effect.sync(() => { |
| 1092 | const lock = identityLocks.get(key) ?? { gate: Semaphore.makeUnsafe(1), users: 0 }; |
| 1093 | lock.users++; |
| 1094 | identityLocks.set(key, lock); |
| 1095 | return lock; |
| 1096 | }), |
| 1097 | (lock) => |
| 1098 | lock.gate.withPermit( |
| 1099 | Effect.gen(function* () { |
| 1100 | const now = yield* Clock.currentTimeMillis; |
| 1101 | const cached = routingIdentities.get(key); |
| 1102 | if (cached !== undefined && now - cached.at < 10 * 60_000) |
| 1103 | return { ...credential, ...cached.value }; |
| 1104 | // Pin verification so an auth switch cannot poison its cache entry. |
| 1105 | const identity = yield* api |
| 1106 | .rest({ host, operation: "getRoutingIdentity", path: "user", allowReserve: true }) |
| 1107 | .pipe( |
| 1108 | Effect.flatMap((response) => |
| 1109 | decodeRoutingIdentity(response.body).pipe(Effect.mapError(unavailable)), |
| 1110 | ), |
| 1111 | Effect.catchTags({ |
| 1112 | // The enclosing operation owns the span for this inline handler. |
| 1113 | GitHubApiResponseError: Effect.fnUntraced(function* (error) { |
| 1114 | if (error.status !== 403) return yield* error; |
| 1115 | const { viewer } = yield* client.RoutingIdentityViewer({}).pipe( |
| 1116 | GitHubGraphQlClient.call({ |
| 1117 | host, |
| 1118 | operation: "getRoutingIdentity", |
| 1119 | allowReserve: true, |
| 1120 | }), |
| 1121 | Effect.catchTags({ |
| 1122 | GraphQLClientError: () => Effect.fail(unavailable()), |
| 1123 | }), |
| 1124 | ); |
| 1125 | return yield* decodeViewerIdentity({ |
| 1126 | id: viewer.databaseId, |
| 1127 | login: viewer.login, |
| 1128 | }).pipe(Effect.mapError(unavailable)); |
| 1129 | }), |
| 1130 | }), |
| 1131 | Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, credential), |
| 1132 | Effect.provideService(SourceControlRateLimit.CredentialScope, key), |
| 1133 | ); |
| 1134 | const value = { accountId: String(identity.id), viewer: identity.login }; |
| 1135 | if (routingIdentities.size >= 128) |
| 1136 | routingIdentities.delete(routingIdentities.keys().next().value!); |
| 1137 | routingIdentities.set(key, { at: now, value }); |
| 1138 | return { ...credential, ...value }; |
| 1139 | }), |
| 1140 | ), |
| 1141 | (lock) => |
| 1142 | Effect.sync(() => { |
| 1143 | lock.users--; |
| 1144 | if (lock.users === 0) identityLocks.delete(key); |
| 1145 | }), |
| 1146 | ); |
| 1147 | }, |
| 1148 | ); |
| 1149 | const withVerifiedCredential: GitHubPullRequestApi["Service"]["withVerifiedCredential"] = ( |
| 1150 | input, |
| 1151 | use, |
| 1152 | ) => |
| 1153 | captureVerifiedCredential(input).pipe( |
| 1154 | Effect.flatMap(({ host, token, accountId, viewer, credentialFingerprint }) => |
| 1155 | use({ accountId, viewer, credentialFingerprint }).pipe( |
| 1156 | Effect.provideService(SourceControlRateLimit.CredentialScope, credentialFingerprint), |
| 1157 | Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, { |
| 1158 | host, |
| 1159 | token, |
| 1160 | credentialFingerprint, |
| 1161 | }), |
| 1162 | ), |
| 1163 | ), |
| 1164 | ); |
| 1165 | const getRoutingIdentity: GitHubPullRequestApi["Service"]["getRoutingIdentity"] = (input) => |
| 1166 | captureVerifiedCredential(input).pipe( |
| 1167 | Effect.map(({ accountId, viewer }) => ({ accountId, viewer })), |
| 1168 | ); |
| 1169 | |
| 1170 | const readError = (cwd: string, operation: string, cause: unknown) => |
| 1171 | new GitHubPullRequestReadError({ cwd, operation, cause }); |
| 1172 | |
| 1173 | const graphql = |
| 1174 | (input: { |
| 1175 | readonly cwd: string; |
| 1176 | readonly host: string; |
| 1177 | readonly operation: string; |
| 1178 | readonly allowReserve?: boolean | undefined; |
| 1179 | }) => |
| 1180 | <A, E, R>( |
| 1181 | effect: Effect.Effect<A, E, R>, |
| 1182 | ): Effect.Effect< |
| 1183 | A, |
| 1184 | | Exclude<E, GraphQLClientError.GraphQLClientError> |
| 1185 | | GitHubRequestPolicy.GitHubApiNotFoundError |
| 1186 | | GitHubRequestPolicy.GitHubApiResponseError |
| 1187 | | GitHubPullRequestReadError, |
| 1188 | Exclude<R, GitHubGraphQlClient.GitHubGraphQlTarget> |
| 1189 | > => |
| 1190 | effect.pipe( |
| 1191 | GitHubGraphQlClient.call({ |
| 1192 | host: input.host, |
| 1193 | operation: input.operation, |
| 1194 | ...(input.allowReserve === true ? { allowReserve: true } : {}), |
| 1195 | }), |
| 1196 | Effect.mapError((error) => |
| 1197 | isGraphQlClientError(error) |
| 1198 | ? readError(input.cwd, input.operation, error) |
| 1199 | : (error as Exclude<typeof error, GraphQLClientError.GraphQLClientError>), |
| 1200 | ), |
| 1201 | ); |
| 1202 | |
| 1203 | const found = |
| 1204 | (input: { readonly host: string; readonly operation: string }) => |
| 1205 | <A>(value: A | null): Effect.Effect<A, GitHubRequestPolicy.GitHubApiNotFoundError> => |
| 1206 | value === null |
| 1207 | ? Effect.fail( |
| 1208 | new GitHubRequestPolicy.GitHubApiNotFoundError({ |
| 1209 | host: normalizeHost(input.host), |
| 1210 | operation: input.operation, |
| 1211 | }), |
| 1212 | ) |
| 1213 | : Effect.succeed(value); |
| 1214 | |
| 1215 | /** |
| 1216 | * The pages of a cursor connection, read one after another until GitHub has no more, |
| 1217 | * `maxPages` have been read, or `until` is satisfied. `truncated` says pages remained when |
| 1218 | * reading stopped; a cursor GitHub hands back a second time stops the read as truncated too. |
| 1219 | */ |
| 1220 | const readPages = Effect.fn("GitHubPullRequestApi.readPages")(function* <Page, E, R>( |
| 1221 | stream: Stream.Stream<Page, E | GraphQLClientError.GraphQLClientError, R>, |
| 1222 | options: { |
| 1223 | readonly cwd: string; |
| 1224 | readonly operation: string; |
| 1225 | readonly hasNextPage: (page: NoInfer<Page>) => boolean; |
| 1226 | readonly maxPages?: number; |
| 1227 | readonly until?: (pages: ReadonlyArray<NoInfer<Page>>) => boolean; |
| 1228 | }, |
| 1229 | ) { |
| 1230 | const pages: Page[] = []; |
| 1231 | let repeated = false; |
| 1232 | yield* stream.pipe( |
| 1233 | // `pages` fails a cursor GitHub hands back unchanged, which would page forever. |
| 1234 | Stream.catch((error) => |
| 1235 | isGraphQlClientError(error) && error.reason._tag === "PaginationError" |
| 1236 | ? Stream.sync(() => { |
| 1237 | repeated = true; |
| 1238 | }).pipe(Stream.drain) |
| 1239 | : Stream.fail(error), |
| 1240 | ), |
| 1241 | Stream.runForEachWhile((page) => |
| 1242 | Effect.sync(() => { |
| 1243 | pages.push(page); |
| 1244 | return ( |
| 1245 | options.hasNextPage(page) && |
| 1246 | pages.length < (options.maxPages ?? Infinity) && |
| 1247 | options.until?.(pages) !== true |
| 1248 | ); |
| 1249 | }), |
| 1250 | ), |
| 1251 | ); |
| 1252 | const last = pages.at(-1); |
| 1253 | return { pages, truncated: repeated || (last !== undefined && options.hasNextPage(last)) }; |
| 1254 | }); |
| 1255 | |
| 1256 | // Immutable PR node IDs can be cached across viewed-file toggles. |
| 1257 | const nodeIds = new Map<string, string>(); |
| 1258 | |
| 1259 | const pullRequestNodeId = (input: { |
| 1260 | readonly cwd: string; |
| 1261 | readonly repository: string; |
| 1262 | readonly host: string; |
| 1263 | readonly number: number; |
| 1264 | readonly operation: string; |
| 1265 | }): Effect.Effect<string, GitHubPullRequestApiError> => { |
| 1266 | const { owner, name } = parseRepositorySelector(input.repository); |
| 1267 | const key = `${input.host} ${owner}/${name} ${input.number}`; |
| 1268 | const held = nodeIds.get(key); |
| 1269 | if (held !== undefined) { |
| 1270 | nodeIds.delete(key); |
| 1271 | nodeIds.set(key, held); |
| 1272 | return Effect.succeed(held); |
| 1273 | } |
| 1274 | return client.PullRequestNodeId({ owner, name, number: input.number }).pipe( |
| 1275 | graphql({ ...input, allowReserve: true }), |
| 1276 | Effect.map(toPullRequestNodeId), |
| 1277 | Effect.flatMap(found(input)), |
| 1278 | Effect.tap((nodeId) => |
| 1279 | Effect.sync(() => { |
| 1280 | if (nodeIds.size >= NODE_ID_CACHE_CAPACITY) { |
| 1281 | const oldest = nodeIds.keys().next().value; |
| 1282 | if (oldest !== undefined) nodeIds.delete(oldest); |
| 1283 | } |
| 1284 | nodeIds.set(key, nodeId); |
| 1285 | }), |
| 1286 | ), |
| 1287 | ); |
| 1288 | }; |
| 1289 | |
| 1290 | /** Mutations follow node IDs; reject IDs from other PRs. */ |
| 1291 | const subjectBelongsToPullRequest = (input: { |
| 1292 | readonly cwd: string; |
| 1293 | readonly repository: string; |
| 1294 | readonly host: string; |
| 1295 | readonly number: number; |
| 1296 | readonly subjectId: string; |
| 1297 | readonly operation: string; |
| 1298 | }) => { |
| 1299 | const { owner, name } = parseRepositorySelector(input.repository); |
| 1300 | return client |
| 1301 | .PullRequestSubject({ owner, name, number: input.number, subjectId: input.subjectId }) |
| 1302 | .pipe(graphql({ ...input, allowReserve: true }), Effect.map(isSubjectOfPullRequest)); |
| 1303 | }; |
| 1304 | |
| 1305 | const decodeWith = <A>( |
| 1306 | cwd: string, |
| 1307 | operation: string, |
| 1308 | decode: (raw: string) => Result.Result<A, unknown>, |
| 1309 | raw: string, |
| 1310 | ): Effect.Effect<A, GitHubPullRequestReadError> => { |
| 1311 | const decoded = decode(raw.trim()); |
| 1312 | return Result.isSuccess(decoded) |
| 1313 | ? Effect.succeed(decoded.success) |
| 1314 | : Effect.fail(readError(cwd, operation, decoded.failure)); |
| 1315 | }; |
| 1316 | |
| 1317 | /** A REST read whose JSON answer is decoded the same way. */ |
| 1318 | const restRead = <A>(input: RestReadInput<A>): Effect.Effect<A, GitHubPullRequestApiError> => |
| 1319 | api |
| 1320 | .rest({ host: input.host, operation: input.operation, path: input.path }) |
| 1321 | .pipe( |
| 1322 | Effect.flatMap((response) => |
| 1323 | decodeWith(input.cwd, input.operation, input.decode, response.body), |
| 1324 | ), |
| 1325 | ); |
| 1326 | |
| 1327 | // The last ETag and body of each polled REST read, so an unchanged answer comes back as a |
| 1328 | // 304, which GitHub does not charge. Keyed by the credential the request is pinned to, so a |
| 1329 | // validator never revalidates another account's body. A 304 writes the entry back, so one |
| 1330 | // that is still polled outlives its time to live. |
| 1331 | const validators = yield* Cache.make({ |
| 1332 | capacity: 512, |
| 1333 | timeToLive: "1 hour", |
| 1334 | lookup: (_key: string) => |
| 1335 | Effect.succeed(Option.none<{ readonly etag: string; readonly body: string }>()), |
| 1336 | }); |
| 1337 | const revalidatedRestRead = Effect.fn("GitHubPullRequestApi.revalidatedRestRead")(function* <A>( |
| 1338 | input: RestReadInput<A>, |
| 1339 | ) { |
| 1340 | const host = normalizeHost(input.host); |
| 1341 | const { token, fingerprint } = yield* api.credential(host); |
| 1342 | const key = `${fingerprint}\0${host}\0${input.path}`; |
| 1343 | const previous = yield* Cache.get(validators, key); |
| 1344 | const response = yield* api |
| 1345 | .rest({ |
| 1346 | host, |
| 1347 | operation: input.operation, |
| 1348 | path: input.path, |
| 1349 | ...(Option.isSome(previous) ? { ifNoneMatch: previous.value.etag } : {}), |
| 1350 | }) |
| 1351 | .pipe( |
| 1352 | Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, { |
| 1353 | host, |
| 1354 | token, |
| 1355 | credentialFingerprint: fingerprint, |
| 1356 | }), |
| 1357 | ); |
| 1358 | if (response.status === 304 && Option.isSome(previous)) { |
| 1359 | yield* Cache.set(validators, key, previous); |
| 1360 | return yield* decodeWith(input.cwd, input.operation, input.decode, previous.value.body); |
| 1361 | } |
| 1362 | const decoded = yield* decodeWith(input.cwd, input.operation, input.decode, response.body); |
| 1363 | const etag = response.headers["etag"]?.trim(); |
| 1364 | yield* etag |
| 1365 | ? Cache.set(validators, key, Option.some({ etag, body: response.body })) |
| 1366 | : Cache.invalidate(validators, key); |
| 1367 | return decoded; |
| 1368 | }); |
| 1369 | |
| 1370 | const diffFilesPage = (input: { |
| 1371 | readonly cwd: string; |
| 1372 | readonly repository: string; |
| 1373 | readonly host: string; |
| 1374 | readonly number: number; |
| 1375 | readonly page: number; |
| 1376 | readonly commit?: string | undefined; |
| 1377 | }): Effect.Effect<GitHubPullRequestDiffSlice, GitHubPullRequestApiError> => { |
| 1378 | const { owner, name } = parseRepositorySelector(input.repository); |
| 1379 | const paging = `per_page=${DIFF_FILES_PAGE_SIZE}&page=${input.page}`; |
| 1380 | return api |
| 1381 | .rest({ |
| 1382 | host: input.host, |
| 1383 | operation: "getPullRequestDiff", |
| 1384 | path: |
| 1385 | input.commit === undefined |
| 1386 | ? `repos/${owner}/${name}/pulls/${input.number}/files?${paging}` |
| 1387 | : `repos/${owner}/${name}/commits/${input.commit}?${paging}`, |
| 1388 | maxResponseBytes: DIFF_MAX_OUTPUT_BYTES, |
| 1389 | timeout: DIFF_TIMEOUT, |
| 1390 | }) |
| 1391 | .pipe( |
| 1392 | Effect.flatMap((response) => { |
| 1393 | // Byte-truncated responses are unparseable JSON prefixes. |
| 1394 | if (response.truncated) { |
| 1395 | return Effect.fail( |
| 1396 | readError( |
| 1397 | input.cwd, |
| 1398 | "getPullRequestDiff", |
| 1399 | new Error(`Page ${input.page} of the changed files was too large to read.`), |
| 1400 | ), |
| 1401 | ); |
| 1402 | } |
| 1403 | return decodeWith( |
| 1404 | input.cwd, |
| 1405 | "getPullRequestDiff", |
| 1406 | input.commit === undefined ? decodePullRequestFilesJson : decodeCommitFilesJson, |
| 1407 | response.body, |
| 1408 | ); |
| 1409 | }), |
| 1410 | Effect.map((files) => { |
| 1411 | // Use raw row counts so malformed files cannot prematurely end pagination. |
| 1412 | const morePages = files.rawCount >= DIFF_FILES_PAGE_SIZE; |
| 1413 | return { |
| 1414 | patch: files.patch, |
| 1415 | truncated: files.truncated, |
| 1416 | nextCursor: morePages ? String(input.page + 1) : null, |
| 1417 | ...(files.omittedFileStats.length === 0 |
| 1418 | ? {} |
| 1419 | : { omittedFileStats: files.omittedFileStats }), |
| 1420 | }; |
| 1421 | }), |
| 1422 | ); |
| 1423 | }; |
| 1424 | |
| 1425 | const getPullRequestDiffFileContents: GitHubPullRequestApi["Service"]["getPullRequestDiffFileContents"] = |
| 1426 | Effect.fn("GitHubPullRequestApi.getPullRequestDiffFileContents")(function* (input) { |
| 1427 | if (input.commit !== undefined && !isCommitSha(input.commit)) { |
| 1428 | return yield* new GitHubDiffCommitError({ cwd: input.cwd }); |
| 1429 | } |
| 1430 | const { owner, name } = parseRepositorySelector(input.repository); |
| 1431 | const refsResponse = yield* api.rest({ |
| 1432 | host: input.host, |
| 1433 | operation: "getPullRequestDiffFileContents", |
| 1434 | path: |
| 1435 | input.commit === undefined |
| 1436 | ? `repos/${owner}/${name}/pulls/${input.number}` |
| 1437 | : `repos/${owner}/${name}/commits/${input.commit}`, |
| 1438 | timeout: DIFF_TIMEOUT, |
| 1439 | }); |
| 1440 | const refs = decodeRevisionRefs(refsResponse.body); |
| 1441 | const baseRef = Option.isSome(refs) |
| 1442 | ? input.commit === undefined |
| 1443 | ? refs.value.base?.sha |
| 1444 | : (refs.value.parents?.[0]?.sha ?? "") |
| 1445 | : undefined; |
| 1446 | const headRef = Option.isSome(refs) |
| 1447 | ? input.commit === undefined |
| 1448 | ? refs.value.head?.sha |
| 1449 | : refs.value.sha |
| 1450 | : undefined; |
| 1451 | const rootCommitNewFile = |
| 1452 | input.commit !== undefined && input.changeType === "new" && baseRef === ""; |
| 1453 | if ( |
| 1454 | headRef === undefined || |
| 1455 | (!rootCommitNewFile && (baseRef === undefined || !isCommitSha(baseRef))) || |
| 1456 | !isCommitSha(headRef) |
| 1457 | ) { |
| 1458 | return yield* new GitHubDiffRevisionsUnavailableError({ |
| 1459 | cwd: input.cwd, |
| 1460 | number: input.number, |
| 1461 | ...(input.commit === undefined ? {} : { commit: input.commit }), |
| 1462 | }); |
| 1463 | } |
| 1464 | // A pull request's patch runs from the merge base, and the base branch may have moved on |
| 1465 | // since, so its old side is read there. Page 2 of a compare leaves out the file list; a |
| 1466 | // failed read falls back to the base branch tip. |
| 1467 | const oldRef = |
| 1468 | input.commit === undefined && input.changeType !== "new" |
| 1469 | ? yield* api |
| 1470 | .rest({ |
| 1471 | host: input.host, |
| 1472 | operation: "getPullRequestDiffFileContents", |
| 1473 | path: `repos/${owner}/${name}/compare/${baseRef}...${headRef}?per_page=1&page=2`, |
| 1474 | timeout: DIFF_TIMEOUT, |
| 1475 | }) |
| 1476 | .pipe( |
| 1477 | Effect.map((response) => |
| 1478 | decodeMergeBase(response.body).pipe( |
| 1479 | Option.map((compare) => compare.merge_base_commit.sha), |
| 1480 | Option.filter(isCommitSha), |
| 1481 | Option.getOrElse(() => baseRef ?? ""), |
| 1482 | ), |
| 1483 | ), |
| 1484 | Effect.orElseSucceed(() => baseRef ?? ""), |
| 1485 | ) |
| 1486 | : (baseRef ?? ""); |
| 1487 | |
| 1488 | const readFile = (revision: string, filePath: string) => |
| 1489 | api |
| 1490 | .rest({ |
| 1491 | host: input.host, |
| 1492 | operation: "getPullRequestDiffFileContents", |
| 1493 | accept: "application/vnd.github.raw+json", |
| 1494 | path: `repos/${owner}/${name}/contents/${filePath |
| 1495 | .split("/") |
| 1496 | .map(encodeURIComponent) |
| 1497 | .join("/")}?ref=${encodeURIComponent(revision)}`, |
| 1498 | maxResponseBytes: DIFF_FILE_MAX_OUTPUT_BYTES, |
| 1499 | timeout: DIFF_TIMEOUT, |
| 1500 | }) |
| 1501 | .pipe( |
| 1502 | Effect.flatMap((response) => |
| 1503 | response.truncated || response.body.includes("\0") || response.invalidUtf8 |
| 1504 | ? Effect.fail( |
| 1505 | new GitHubDiffFileContentsUnavailableError({ |
| 1506 | cwd: input.cwd, |
| 1507 | path: filePath, |
| 1508 | reason: response.truncated ? "oversized" : "binary", |
| 1509 | }), |
| 1510 | ) |
| 1511 | : Effect.succeed(response.body), |
| 1512 | ), |
| 1513 | ); |
| 1514 | |
| 1515 | const [oldContents, newContents] = yield* Effect.all( |
| 1516 | [ |
| 1517 | input.changeType === "new" ? Effect.succeed("") : readFile(oldRef, input.oldPath), |
| 1518 | input.changeType === "deleted" ? Effect.succeed("") : readFile(headRef, input.newPath), |
| 1519 | ], |
| 1520 | { concurrency: 2 }, |
| 1521 | ); |
| 1522 | return { oldContents, newContents }; |
| 1523 | }); |
| 1524 | |
| 1525 | /** Older Enterprise servers may lack `isRequired`. */ |
| 1526 | const asksRequired = (host: string) => host.toLowerCase() === "github.com"; |
| 1527 | |
| 1528 | /** |
| 1529 | * Every check context of the head commit, a page at a time, for a rollup the detail read cut at |
| 1530 | * its first hundred. Each page names the head it read, so a push mid-walk fails rather than |
| 1531 | * mixing two revisions' checks. |
| 1532 | */ |
| 1533 | const readAllCheckContexts = Effect.fn("GitHubPullRequestApi.readAllCheckContexts")(function* ( |
| 1534 | input: Parameters<GitHubPullRequestApi["Service"]["getPullRequestDetail"]>[0], |
| 1535 | allowReserve: boolean, |
| 1536 | first: NonNullable<ReturnType<typeof toPullRequestCheckContextsPage>>, |
| 1537 | ) { |
| 1538 | const { owner, name } = parseRepositorySelector(input.repository); |
| 1539 | const target = { ...input, operation: "getPullRequestDetail", allowReserve }; |
| 1540 | const contexts = [...first.contexts]; |
| 1541 | let after = first.nextCursor; |
| 1542 | for (let page = 1; after !== null && page < CHECK_CONTEXT_PAGES; page++) { |
| 1543 | const result = yield* client |
| 1544 | .PullRequestCheckContexts({ |
| 1545 | owner, |
| 1546 | name, |
| 1547 | number: input.number, |
| 1548 | required: asksRequired(input.host), |
| 1549 | after, |
| 1550 | }) |
| 1551 | .pipe(graphql(target)); |
| 1552 | const next = toPullRequestCheckContextsPage(result); |
| 1553 | if (next === null || next.headSha !== first.headSha) { |
| 1554 | return yield* readError( |
| 1555 | input.cwd, |
| 1556 | "getPullRequestDetail", |
| 1557 | new Error("Pull request head changed while reading checks."), |
| 1558 | ); |
| 1559 | } |
| 1560 | if (next.nextCursor === after) return { contexts, truncated: true }; |
| 1561 | contexts.push(...next.contexts); |
| 1562 | after = next.nextCursor; |
| 1563 | } |
| 1564 | return { contexts, truncated: first.nextCursor === null || after !== null }; |
| 1565 | }); |
| 1566 | |
| 1567 | // GitHub refuses a requested-reviewer list holding a team the viewer cannot see. Remember the |
| 1568 | // refusal so later reads of that pull request skip straight to the read without reviewers. |
| 1569 | const refusedReviewers = yield* Cache.make({ |
| 1570 | capacity: 512, |
| 1571 | timeToLive: "10 minutes", |
| 1572 | lookup: (_key: string) => Effect.void, |
| 1573 | }); |
| 1574 | const readRequestedReviewers = Effect.fn("GitHubPullRequestApi.readRequestedReviewers")( |
| 1575 | function* <A, E, R>( |
| 1576 | input: { readonly host: string; readonly repository: string; readonly number: number }, |
| 1577 | wanted: number, |
| 1578 | read: (requestedReviewers: number) => Effect.Effect<A, E, R>, |
| 1579 | ) { |
| 1580 | const host = normalizeHost(input.host); |
| 1581 | const { fingerprint } = yield* api.credential(host); |
| 1582 | const key = `${fingerprint}\0${host}\0${input.repository.toLowerCase()}\0${input.number}`; |
| 1583 | if (yield* Cache.has(refusedReviewers, key)) return yield* read(0); |
| 1584 | return yield* read(wanted).pipe( |
| 1585 | Effect.catchIf(isRefusedRequestedReviewersOnly, () => |
| 1586 | Cache.set(refusedReviewers, key, undefined).pipe(Effect.andThen(read(0))), |
| 1587 | ), |
| 1588 | ); |
| 1589 | }, |
| 1590 | ); |
| 1591 | |
| 1592 | const getPullRequestDetail: GitHubPullRequestApi["Service"]["getPullRequestDetail"] = (input) => { |
| 1593 | const { owner, name } = parseRepositorySelector(input.repository); |
| 1594 | const operation = "getPullRequestDetail"; |
| 1595 | const read = (requestedReviewers: number) => |
| 1596 | client |
| 1597 | .PullRequestCore({ |
| 1598 | owner, |
| 1599 | name, |
| 1600 | number: input.number, |
| 1601 | headRef: `refs/pull/${input.number}/head`, |
| 1602 | required: asksRequired(input.host), |
| 1603 | requestedReviewers, |
| 1604 | mergeQueue: input.host.toLowerCase() === "github.com", |
| 1605 | }) |
| 1606 | .pipe(toleratingMissingPullRef(decodePullRequestCore)); |
| 1607 | return SourceControlRateLimit.Interactive.pipe( |
| 1608 | Effect.flatMap((allowReserve) => |
| 1609 | readRequestedReviewers(input, 100, read).pipe( |
| 1610 | graphql({ ...input, operation, allowReserve }), |
| 1611 | Effect.flatMap((result) => |
| 1612 | found({ ...input, operation })(toPullRequestCore(result)).pipe( |
| 1613 | Effect.filterOrElse( |
| 1614 | (core) => !core.checksTruncated, |
| 1615 | (core) => |
| 1616 | readAllCheckContexts( |
| 1617 | input, |
| 1618 | allowReserve, |
| 1619 | toPullRequestCheckContextsPage(result)!, |
| 1620 | ).pipe( |
| 1621 | Effect.map((all) => ({ |
| 1622 | ...core, |
| 1623 | ...pullRequestChecksFromContexts(all.contexts), |
| 1624 | checksTruncated: all.truncated, |
| 1625 | })), |
| 1626 | ), |
| 1627 | ), |
| 1628 | ), |
| 1629 | ), |
| 1630 | ), |
| 1631 | ), |
| 1632 | ); |
| 1633 | }; |
| 1634 | |
| 1635 | const workflowApprovalLimit = 1_000; |
| 1636 | const workflowApprovalReadError = (cwd: string, cause: unknown) => |
| 1637 | readError(cwd, "listWorkflowRunsRequiringApproval", cause); |
| 1638 | |
| 1639 | const listHeadsByBranch = Effect.fn("GitHubPullRequestApi.listHeadsByBranch")(function* (input: { |
| 1640 | readonly cwd: string; |
| 1641 | readonly repository: string; |
| 1642 | readonly host: string; |
| 1643 | readonly headBranch: string; |
| 1644 | }) { |
| 1645 | const { owner, name } = parseRepositorySelector(input.repository); |
| 1646 | const countHeads = (pages: ReadonlyArray<{ readonly heads: ReadonlyArray<unknown> }>) => |
| 1647 | pages.reduce((total, page) => total + page.heads.length, 0); |
| 1648 | const target = { |
| 1649 | ...input, |
| 1650 | operation: "listWorkflowRunsRequiringApproval", |
| 1651 | allowReserve: true, |
| 1652 | }; |
| 1653 | const { pages, truncated } = yield* readPages( |
| 1654 | GraphQLClient.pages(client.PullRequestHeads, { |
| 1655 | variables: { owner, name, head: input.headBranch }, |
| 1656 | connection: (result) => { |
| 1657 | const page = toPullRequestHeads(result); |
| 1658 | return { |
| 1659 | ...page, |
| 1660 | pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor }, |
| 1661 | }; |
| 1662 | }, |
| 1663 | }), |
| 1664 | { |
| 1665 | ...target, |
| 1666 | hasNextPage: (page) => page.nextCursor !== null, |
| 1667 | until: (pages) => countHeads(pages) > workflowApprovalLimit, |
| 1668 | }, |
| 1669 | ).pipe(graphql(target)); |
| 1670 | return { heads: pages.flatMap((page) => page.heads), truncated }; |
| 1671 | }); |
| 1672 | |
| 1673 | const listActionRequiredRuns = Effect.fn("GitHubPullRequestApi.listActionRequiredRuns")( |
| 1674 | function* (input: { |
| 1675 | readonly cwd: string; |
| 1676 | readonly repository: string; |
| 1677 | readonly host: string; |
| 1678 | readonly headSha: string; |
| 1679 | readonly headBranch: string; |
| 1680 | }) { |
| 1681 | const known = yield* KnownWorkflowRuns; |
| 1682 | if (known !== null && known.headSha === input.headSha) { |
| 1683 | return known.runs.flatMap((run) => |
| 1684 | // Maintainer-gated runs can report completed/action_required. |
| 1685 | (run.conclusion === "action_required" || run.status === "action_required") && |
| 1686 | run.head_branch === input.headBranch |
| 1687 | ? [ |
| 1688 | { |
| 1689 | id: run.id, |
| 1690 | name: run.name?.trim() || `Workflow run ${run.id}`, |
| 1691 | url: run.html_url?.trim() || null, |
| 1692 | }, |
| 1693 | ] |
| 1694 | : [], |
| 1695 | ); |
| 1696 | } |
| 1697 | const { owner, name } = parseRepositorySelector(input.repository); |
| 1698 | const runs: GitHubWorkflowRunApproval[] = []; |
| 1699 | for (let page = 1; runs.length <= workflowApprovalLimit; page++) { |
| 1700 | const read: GitHubWorkflowRunPage = yield* restRead({ |
| 1701 | cwd: input.cwd, |
| 1702 | host: input.host, |
| 1703 | operation: "listWorkflowRunsRequiringApproval", |
| 1704 | path: `repos/${owner}/${name}/actions/runs?head_sha=${encodeURIComponent(input.headSha)}&branch=${encodeURIComponent(input.headBranch)}&event=pull_request&status=action_required&per_page=100&page=${page}`, |
| 1705 | decode: decodeWorkflowRunsJson, |
| 1706 | }).pipe(Effect.mapError((error) => workflowApprovalReadError(input.cwd, error))); |
| 1707 | runs.push(...read.runs); |
| 1708 | if (read.rawCount < 100) break; |
| 1709 | } |
| 1710 | return runs; |
| 1711 | }, |
| 1712 | ); |
| 1713 | |
| 1714 | const listWorkflowRunsRequiringApproval: GitHubPullRequestApi["Service"]["listWorkflowRunsRequiringApproval"] = |
| 1715 | (input) => |
| 1716 | Effect.all( |
| 1717 | [ |
| 1718 | listHeadsByBranch(input).pipe( |
| 1719 | Effect.flatMap( |
| 1720 | ({ |
| 1721 | heads, |
| 1722 | truncated, |
| 1723 | }): Effect.Effect< |
| 1724 | GitHubPullRequestHead, |
| 1725 | GitHubPullRequestReadError | GitHubWorkflowApprovalRefusedError |
| 1726 | > => { |
| 1727 | const exactHeads = heads.filter( |
| 1728 | (pullRequest) => |
| 1729 | pullRequest.headSha === input.headSha && |
| 1730 | pullRequest.isCrossRepository === true && |
| 1731 | pullRequest.headRepositoryOwner?.toLowerCase() === |
| 1732 | input.headRepositoryOwner.toLowerCase(), |
| 1733 | ); |
| 1734 | if (truncated || heads.length > workflowApprovalLimit) { |
| 1735 | return Effect.fail( |
| 1736 | new GitHubWorkflowApprovalRefusedError({ |
| 1737 | cwd: input.cwd, |
| 1738 | number: input.number, |
| 1739 | reason: "head-list-truncated", |
| 1740 | observedCount: heads.length, |
| 1741 | limit: workflowApprovalLimit, |
| 1742 | }), |
| 1743 | ); |
| 1744 | } |
| 1745 | if (exactHeads.length !== 1 || exactHeads[0]?.number !== input.number) { |
| 1746 | return Effect.fail( |
| 1747 | new GitHubWorkflowApprovalRefusedError({ |
| 1748 | cwd: input.cwd, |
| 1749 | number: input.number, |
| 1750 | reason: "head-not-unique", |
| 1751 | observedCount: exactHeads.length, |
| 1752 | limit: workflowApprovalLimit, |
| 1753 | }), |
| 1754 | ); |
| 1755 | } |
| 1756 | return Effect.succeed(exactHeads[0]); |
| 1757 | }, |
| 1758 | ), |
| 1759 | ), |
| 1760 | listActionRequiredRuns(input).pipe( |
| 1761 | Effect.filterOrFail( |
| 1762 | (runs) => !(runs.length > workflowApprovalLimit), |
| 1763 | (runs) => |
| 1764 | new GitHubWorkflowApprovalRefusedError({ |
| 1765 | cwd: input.cwd, |
| 1766 | number: input.number, |
| 1767 | reason: "run-list-truncated", |
| 1768 | observedCount: runs.length, |
| 1769 | limit: workflowApprovalLimit, |
| 1770 | }), |
| 1771 | ), |
| 1772 | ), |
| 1773 | ], |
| 1774 | { concurrency: 2 }, |
| 1775 | ).pipe(Effect.map(([, runs]) => runs)); |
| 1776 | |
| 1777 | const simpleActionMutations = { |
| 1778 | "disable-auto-merge": (pullRequestId: string) => |
| 1779 | client |
| 1780 | .DisablePullRequestAutoMerge({ pullRequestId }) |
| 1781 | .pipe(Effect.map((result) => result.disablePullRequestAutoMerge?.pullRequest)), |
| 1782 | ready: (pullRequestId: string) => |
| 1783 | client |
| 1784 | .MarkPullRequestReadyForReview({ pullRequestId }) |
| 1785 | .pipe(Effect.map((result) => result.markPullRequestReadyForReview?.pullRequest)), |
| 1786 | draft: (pullRequestId: string) => |
| 1787 | client |
| 1788 | .ConvertPullRequestToDraft({ pullRequestId }) |
| 1789 | .pipe(Effect.map((result) => result.convertPullRequestToDraft?.pullRequest)), |
| 1790 | close: (pullRequestId: string) => |
| 1791 | client |
| 1792 | .ClosePullRequest({ pullRequestId }) |
| 1793 | .pipe(Effect.map((result) => result.closePullRequest?.pullRequest)), |
| 1794 | reopen: (pullRequestId: string) => |
| 1795 | client |
| 1796 | .ReopenPullRequest({ pullRequestId }) |
| 1797 | .pipe(Effect.map((result) => result.reopenPullRequest?.pullRequest)), |
| 1798 | } satisfies Partial<Record<PullRequestAction, unknown>>; |
| 1799 | |
| 1800 | /** The mutation already landed, so a reply that does not decode only loses the summary. */ |
| 1801 | const actionSummary = <E, R>( |
| 1802 | effect: Effect.Effect<PullRequestActionSummary | null | undefined, E, R>, |
| 1803 | ) => |
| 1804 | effect.pipe( |
| 1805 | Effect.map(toPullRequestActionSummary), |
| 1806 | Effect.catchIf( |
| 1807 | (error) => isGraphQlClientError(error) && error.reason._tag === "DecodeError", |
| 1808 | () => Effect.void, |
| 1809 | ), |
| 1810 | ); |
| 1811 | |
| 1812 | /** Preserve policy errors; map not-found per lookup and other failures to read errors. */ |
| 1813 | const batchedRead = <A, E, R>( |
| 1814 | input: { readonly cwd: string; readonly host: string; readonly operation: string }, |
| 1815 | effect: Effect.Effect<A, E, R>, |
| 1816 | ): Effect.Effect< |
| 1817 | A, |
| 1818 | | Exclude<E, GraphQLClientError.GraphQLClientError> |
| 1819 | | GitHubPullRequestReadError |
| 1820 | | GitHubRequestPolicy.GitHubApiNotFoundError, |
| 1821 | Exclude<R, GitHubGraphQlClient.GitHubGraphQlTarget> |
| 1822 | > => |
| 1823 | effect.pipe( |
| 1824 | Effect.provideService(GitHubGraphQlClient.GitHubGraphQlTarget, { |
| 1825 | host: input.host, |
| 1826 | operation: input.operation, |
| 1827 | }), |
| 1828 | Effect.mapError((error) => |
| 1829 | !isGraphQlClientError(error) |
| 1830 | ? (error as Exclude<E, GraphQLClientError.GraphQLClientError>) |
| 1831 | : isNotFoundOnly(error) |
| 1832 | ? new GitHubRequestPolicy.GitHubApiNotFoundError({ |
| 1833 | host: input.host, |
| 1834 | operation: input.operation, |
| 1835 | githubErrors: GitHubGraphQlClient.describeErrors(error), |
| 1836 | }) |
| 1837 | : readError(input.cwd, input.operation, error), |
| 1838 | ), |
| 1839 | ); |
| 1840 | |
| 1841 | // Batch by host/credential; isolate missing PRs. |
| 1842 | const summaryResolver = GraphQLResolver.aliased(client.PullRequestSummary, { |
| 1843 | batchKey: GitHubGraphQlClient.batchKey, |
| 1844 | }).pipe( |
| 1845 | RequestResolver.setDelay(SUMMARY_BATCH_WINDOW), |
| 1846 | RequestResolver.batchN(STAT_ALIASES_PER_REQUEST), |
| 1847 | ); |
| 1848 | const getPullRequestSummary: GitHubPullRequestApi["Service"]["getPullRequestSummary"] = Effect.fn( |
| 1849 | "GitHubPullRequestApi.getPullRequestSummary", |
| 1850 | )( |
| 1851 | function* (input) { |
| 1852 | const lookup = pullRequestLookup(input); |
| 1853 | if (lookup === null) { |
| 1854 | return yield* new GitHubRepositorySelectorError({ |
| 1855 | cwd: input.cwd, |
| 1856 | operation: "getPullRequestSummary", |
| 1857 | }); |
| 1858 | } |
| 1859 | const result = yield* GraphQLResolver.request( |
| 1860 | { ...lookup, stacks: input.host.toLowerCase() === "github.com" }, |
| 1861 | summaryResolver, |
| 1862 | ); |
| 1863 | const pullRequest = result.repository?.pullRequest; |
| 1864 | if (pullRequest == null) { |
| 1865 | return yield* new GitHubRequestPolicy.GitHubApiNotFoundError({ |
| 1866 | host: input.host, |
| 1867 | operation: "getPullRequestSummary", |
| 1868 | }); |
| 1869 | } |
| 1870 | return toPullRequestSummary(pullRequest); |
| 1871 | }, |
| 1872 | (effect, input) => |
| 1873 | effect.pipe((effect) => |
| 1874 | batchedRead({ ...input, operation: "getPullRequestSummary" }, effect), |
| 1875 | ), |
| 1876 | ); |
| 1877 | |
| 1878 | // A missing fingerprint triggers a full watch read; a failed request fails the whole batch. |
| 1879 | const watchFingerprintResolver = GraphQLResolver.aliased(client.PullRequestWatchFingerprint, { |
| 1880 | batchKey: GitHubGraphQlClient.batchKey, |
| 1881 | }).pipe( |
| 1882 | RequestResolver.setDelay(SUMMARY_BATCH_WINDOW), |
| 1883 | RequestResolver.batchN(STAT_ALIASES_PER_REQUEST), |
| 1884 | ); |
| 1885 | const getPullRequestWatchFingerprint: GitHubPullRequestApi["Service"]["getPullRequestWatchFingerprint"] = |
| 1886 | (input) => { |
| 1887 | const lookup = pullRequestLookup(input); |
| 1888 | if (lookup === null) return Effect.succeed(null); |
| 1889 | return GraphQLResolver.request( |
| 1890 | { ...lookup, mergeQueue: input.host.toLowerCase() === "github.com" }, |
| 1891 | watchFingerprintResolver, |
| 1892 | ).pipe( |
| 1893 | Effect.map((result) => { |
| 1894 | const pullRequest = result.repository?.pullRequest; |
| 1895 | return pullRequest == null ? null : toPullRequestWatchFingerprint(pullRequest); |
| 1896 | }), |
| 1897 | Effect.catchIf(isNotFoundOnly, () => Effect.succeed(null)), |
| 1898 | (effect) => batchedRead({ ...input, operation: "getPullRequestWatchFingerprint" }, effect), |
| 1899 | ); |
| 1900 | }; |
| 1901 | |
| 1902 | const statsResolver = GraphQLResolver.aliased(client.PullRequestStats, { |
| 1903 | batchKey: GitHubGraphQlClient.batchKey, |
| 1904 | }).pipe(RequestResolver.batchN(STAT_ALIASES_PER_REQUEST)); |
| 1905 | const stackMembershipResolver = GraphQLResolver.aliased(client.PullRequestStackMembership, { |
| 1906 | batchKey: GitHubGraphQlClient.batchKey, |
| 1907 | }).pipe(RequestResolver.batchN(STAT_ALIASES_PER_REQUEST)); |
| 1908 | // GitHub has no bulk viewed-file mutation; aliases combine individual paths into one request. |
| 1909 | const setFileViewedResolver = GraphQLResolver.aliased(client.SetFileViewed, { |
| 1910 | batchKey: GitHubGraphQlClient.batchKey, |
| 1911 | }).pipe(RequestResolver.batchN(FILES_VIEWED_PER_REQUEST)); |
| 1912 | |
| 1913 | return GitHubPullRequestApi.of({ |
| 1914 | withVerifiedCredential, |
| 1915 | revalidateChecks, |
| 1916 | getRoutingIdentity, |
| 1917 | getViewerLogin: Effect.fn("GitHubPullRequestApi.getViewerLogin")(function (input) { |
| 1918 | return getRoutingIdentity(input).pipe(Effect.map((identity) => identity.viewer)); |
| 1919 | }), |
| 1920 | |
| 1921 | listPullRequests: Effect.fn("GitHubPullRequestApi.listPullRequests")(function (input) { |
| 1922 | const fallbackMaxRows = Math.max(input.limit + 1, PULL_REQUEST_FALLBACK_MAX_ROWS); |
| 1923 | const { owner, name } = parseRepositorySelector(input.repository); |
| 1924 | const query = searchQuery({ ...input, repositories: [input.repository] }); |
| 1925 | if (query === null) { |
| 1926 | return Effect.fail( |
| 1927 | new GitHubRepositorySelectorError({ |
| 1928 | cwd: input.cwd, |
| 1929 | operation: "listPullRequests", |
| 1930 | }), |
| 1931 | ); |
| 1932 | } |
| 1933 | const target = { cwd: input.cwd, host: input.host, operation: "listPullRequests" }; |
| 1934 | const toPage = ( |
| 1935 | page: ReturnType<typeof toPullRequestRows>, |
| 1936 | ): GitHubPullRequestListPage & { readonly pageInfo: GraphQLClient.PageInfo } => ({ |
| 1937 | items: page.rows.map((row) => row.item), |
| 1938 | rawCount: page.rawCount, |
| 1939 | endCursor: page.endCursor, |
| 1940 | pageInfo: { hasNextPage: page.endCursor !== null, endCursor: page.endCursor }, |
| 1941 | }); |
| 1942 | const stacks = input.host.toLowerCase() === "github.com"; |
| 1943 | // Search cannot exclude numbers, so the rows already delivered at the boundary come back |
| 1944 | // first; read past them so they do not use up the limit. |
| 1945 | const seenAt = new Set(input.cursor?.seenAt ?? []); |
| 1946 | const isSeen = (item: GitHubPullRequestListItem) => |
| 1947 | item.updatedAt === input.cursor?.updatedBefore && seenAt.has(item.number); |
| 1948 | const read = ( |
| 1949 | continues: boolean, |
| 1950 | requestedRows = input.limit + 1 + (continues ? seenAt.size : 0), |
| 1951 | ): Effect.Effect<GitHubPullRequestListBatch, GitHubPullRequestApiError> => |
| 1952 | collect(requestedRows, (after, rows) => |
| 1953 | (continues |
| 1954 | ? client |
| 1955 | .PullRequestSearch({ |
| 1956 | q: query, |
| 1957 | first: pageRows(rows), |
| 1958 | after, |
| 1959 | // Stack badges come from their own batched read below, for the rows that stay. |
| 1960 | stacks: false, |
| 1961 | stats: true, |
| 1962 | }) |
| 1963 | .pipe(Effect.map((result) => toPage(toPullRequestRows(result.search)))) |
| 1964 | : client |
| 1965 | .PullRequestList({ |
| 1966 | owner, |
| 1967 | name, |
| 1968 | states: LIST_STATES[input.state], |
| 1969 | first: pageRows(rows), |
| 1970 | after, |
| 1971 | stacks: false, |
| 1972 | stats: true, |
| 1973 | }) |
| 1974 | .pipe( |
| 1975 | Effect.map((result) => |
| 1976 | toPage(toPullRequestRows(result.repository?.pullRequests)), |
| 1977 | ), |
| 1978 | ) |
| 1979 | ).pipe(graphql(target)), |
| 1980 | ).pipe( |
| 1981 | Effect.flatMap(({ items: rawItems, rawCount, truncated: cutShort }) => { |
| 1982 | const items = continues |
| 1983 | ? rawItems.filter((item) => !isSeen(item)) |
| 1984 | : rawItems.filter((item) => matchesUnsortedListing(item, input)); |
| 1985 | if ( |
| 1986 | !continues && |
| 1987 | items.length < input.limit && |
| 1988 | rawCount >= requestedRows && |
| 1989 | requestedRows < fallbackMaxRows |
| 1990 | ) { |
| 1991 | const nextRows = Math.min(requestedRows * 2, fallbackMaxRows); |
| 1992 | if (nextRows > requestedRows) return read(false, nextRows); |
| 1993 | } |
| 1994 | return Effect.succeed({ |
| 1995 | items: items.slice(0, input.limit), |
| 1996 | // Probe one raw row past the limit; malformed rows must not prematurely end paging. |
| 1997 | truncated: |
| 1998 | cutShort || |
| 1999 | (continues |
| 2000 | ? rawCount - (rawItems.length - items.length) > input.limit |
| 2001 | : items.length > input.limit || rawCount >= requestedRows), |
| 2002 | continues, |
| 2003 | }); |
| 2004 | }), |
| 2005 | ); |
| 2006 | // Unindexed repositories silently return no search rows, and search can fail while the |
| 2007 | // listing answers. The listing cannot apply a text query or an `updated:<=` cursor. |
| 2008 | const listingServes = input.cursor === undefined && (input.query?.trim().length ?? 0) === 0; |
| 2009 | const listed = read(true).pipe( |
| 2010 | Effect.matchEffect({ |
| 2011 | onSuccess: (batch) => |
| 2012 | batch.items.length > 0 || !listingServes ? Effect.succeed(batch) : read(false), |
| 2013 | onFailure: (error) => |
| 2014 | listingServes && isGitHubServerError(error) ? read(false) : Effect.fail(error), |
| 2015 | }), |
| 2016 | Effect.filterOrElse( |
| 2017 | (batch) => !stacks || batch.items.length === 0, |
| 2018 | (batch) => |
| 2019 | Effect.forEach( |
| 2020 | batch.items, |
| 2021 | (item) => { |
| 2022 | const lookup = pullRequestLookup({ |
| 2023 | repository: input.repository, |
| 2024 | number: item.number, |
| 2025 | }); |
| 2026 | if (lookup === null) return Effect.succeed(item); |
| 2027 | return GraphQLResolver.request(lookup, stackMembershipResolver).pipe( |
| 2028 | Effect.map((result) => { |
| 2029 | const pullRequest = result.repository?.pullRequest; |
| 2030 | const stack = pullRequest == null ? undefined : toStackMembership(pullRequest); |
| 2031 | return stack === undefined ? item : { ...item, stack }; |
| 2032 | }), |
| 2033 | Effect.catch((error) => |
| 2034 | Effect.logWarning("Pull request stack membership enrichment failed", { |
| 2035 | operation: "listPullRequestStackMemberships", |
| 2036 | host: input.host, |
| 2037 | error: error._tag, |
| 2038 | }).pipe(Effect.as(item)), |
| 2039 | ), |
| 2040 | ); |
| 2041 | }, |
| 2042 | { concurrency: "unbounded" }, |
| 2043 | ).pipe( |
| 2044 | Effect.provideService(GitHubGraphQlClient.GitHubGraphQlTarget, { |
| 2045 | host: input.host, |
| 2046 | operation: "listPullRequestStackMemberships", |
| 2047 | }), |
| 2048 | Effect.map((items) => ({ ...batch, items })), |
| 2049 | ), |
| 2050 | ), |
| 2051 | ); |
| 2052 | // GitHub answers a private repository the token cannot see as missing, and its error names |
| 2053 | // the credential that request carried. A personal credential is pinned for the whole |
| 2054 | // read, so a token changed mid-read does not split it; the app keeps the policy's fallback. |
| 2055 | const host = normalizeHost(input.host); |
| 2056 | return api.credential(host).pipe( |
| 2057 | Effect.flatMap(({ token, fingerprint, source }) => |
| 2058 | source === undefined || source === "app" |
| 2059 | ? listed |
| 2060 | : listed.pipe( |
| 2061 | Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, { |
| 2062 | host, |
| 2063 | token, |
| 2064 | credentialFingerprint: fingerprint, |
| 2065 | source, |
| 2066 | }), |
| 2067 | ), |
| 2068 | ), |
| 2069 | ); |
| 2070 | }), |
| 2071 | |
| 2072 | searchPullRequests: Effect.fn("GitHubPullRequestApi.searchPullRequests")(function* (input) { |
| 2073 | const query = searchQuery(input); |
| 2074 | if (query === null) { |
| 2075 | return yield* new GitHubRepositorySelectorError({ |
| 2076 | cwd: input.cwd, |
| 2077 | operation: "searchPullRequests", |
| 2078 | }); |
| 2079 | } |
| 2080 | // Search cannot exclude numbers, so the rows already delivered at the boundary come back |
| 2081 | // first; read past them so they do not use up the limit. |
| 2082 | const seenAt = new Set( |
| 2083 | (input.cursor?.seenAt ?? []).map( |
| 2084 | ({ repository, number }) => `${repository.trim().toLowerCase()}#${number}`, |
| 2085 | ), |
| 2086 | ); |
| 2087 | const stacks = input.host.toLowerCase() === "github.com"; |
| 2088 | let endedShort = false; |
| 2089 | const { |
| 2090 | items: rawItems, |
| 2091 | rawCount, |
| 2092 | truncated, |
| 2093 | } = yield* collect( |
| 2094 | Math.min(input.limit + 1, PULL_REQUEST_SEARCH_MAX_ROWS) + seenAt.size, |
| 2095 | (after, rows) => |
| 2096 | client |
| 2097 | .PullRequestSearch({ q: query, first: pageRows(rows), after, stacks, stats: false }) |
| 2098 | .pipe( |
| 2099 | graphql({ ...input, operation: "searchPullRequests" }), |
| 2100 | Effect.map(({ search }) => { |
| 2101 | const page = toPullRequestRows(search); |
| 2102 | // A short page that says it has more is where this read stops, not a gap to read past. |
| 2103 | const short = page.endCursor !== null && page.rawCount < pageRows(rows); |
| 2104 | if (short) endedShort = true; |
| 2105 | return { |
| 2106 | items: page.rows.flatMap(({ item, repository }) => |
| 2107 | repository === null ? [] : [{ ...item, repository }], |
| 2108 | ), |
| 2109 | rawCount: page.rawCount, |
| 2110 | endCursor: short ? null : page.endCursor, |
| 2111 | }; |
| 2112 | }), |
| 2113 | ), |
| 2114 | ); |
| 2115 | const items = rawItems.filter( |
| 2116 | (item) => |
| 2117 | item.updatedAt !== input.cursor?.updatedBefore || |
| 2118 | !seenAt.has(`${item.repository.trim().toLowerCase()}#${item.number}`), |
| 2119 | ); |
| 2120 | return { |
| 2121 | items: items.slice(0, input.limit), |
| 2122 | truncated: |
| 2123 | truncated || endedShort || rawCount - (rawItems.length - items.length) > input.limit, |
| 2124 | }; |
| 2125 | }), |
| 2126 | |
| 2127 | listPullRequestStats: Effect.fn("GitHubPullRequestApi.listPullRequestStats")( |
| 2128 | function* (input) { |
| 2129 | const lookups = input.changeRequests.map((changeRequest) => ({ |
| 2130 | changeRequest, |
| 2131 | lookup: pullRequestLookup(changeRequest), |
| 2132 | })); |
| 2133 | if (lookups.some(({ lookup }) => lookup === null)) { |
| 2134 | return yield* new GitHubRepositorySelectorError({ |
| 2135 | cwd: input.cwd, |
| 2136 | operation: "listPullRequestStats", |
| 2137 | }); |
| 2138 | } |
| 2139 | const stats = yield* Effect.forEach( |
| 2140 | lookups, |
| 2141 | ({ changeRequest, lookup }) => |
| 2142 | GraphQLResolver.request(lookup!, statsResolver).pipe( |
| 2143 | Effect.map((result) => { |
| 2144 | const pullRequest = result.repository?.pullRequest; |
| 2145 | return pullRequest == null |
| 2146 | ? [] |
| 2147 | : [{ ...changeRequest, ...pullRequest } satisfies GitHubPullRequestStat]; |
| 2148 | }), |
| 2149 | Effect.catchIf(isNotFoundOnly, () => Effect.succeed([])), |
| 2150 | ), |
| 2151 | { concurrency: "unbounded" }, |
| 2152 | ); |
| 2153 | return stats.flat(); |
| 2154 | }, |
| 2155 | (effect, input) => |
| 2156 | effect.pipe((effect) => |
| 2157 | batchedRead({ ...input, operation: "listPullRequestStats" }, effect), |
| 2158 | ), |
| 2159 | ), |
| 2160 | |
| 2161 | getPullRequestSummary, |
| 2162 | getPullRequestWatchFingerprint, |
| 2163 | pullRequestEvents: yield* GitHubPullRequestEvents.make, |
| 2164 | |
| 2165 | getPullRequestDetail, |
| 2166 | getPullRequestPreview: Effect.fn("GitHubPullRequestApi.getPullRequestPreview")( |
| 2167 | function (input) { |
| 2168 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2169 | const operation = "getPullRequestPreview"; |
| 2170 | return client |
| 2171 | .PullRequestPreview({ owner, name, number: input.number }) |
| 2172 | .pipe( |
| 2173 | graphql({ ...input, operation }), |
| 2174 | Effect.map(toPullRequestPreview), |
| 2175 | Effect.flatMap(found({ ...input, operation })), |
| 2176 | ); |
| 2177 | }, |
| 2178 | ), |
| 2179 | listWorkflowRunsRequiringApproval, |
| 2180 | listUnfinishedWorkflowRuns: Effect.fn("GitHubPullRequestApi.listUnfinishedWorkflowRuns")( |
| 2181 | function (input) { |
| 2182 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2183 | // Read with every pull request detail, so revalidate it. |
| 2184 | return revalidatedRestRead({ |
| 2185 | cwd: input.cwd, |
| 2186 | host: input.host, |
| 2187 | operation: "listUnfinishedWorkflowRuns", |
| 2188 | path: `repos/${owner}/${name}/actions/runs?head_sha=${encodeURIComponent(input.headSha)}&per_page=100`, |
| 2189 | decode: decodeUnfinishedWorkflowRunsJson, |
| 2190 | }); |
| 2191 | }, |
| 2192 | ), |
| 2193 | |
| 2194 | getPullRequestStack: Effect.fn("GitHubPullRequestApi.getPullRequestStack")(function (input) { |
| 2195 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2196 | // Polled by the pull request sync for every linked pull request, so revalidate it. |
| 2197 | return revalidatedRestRead({ |
| 2198 | cwd: input.cwd, |
| 2199 | host: input.host, |
| 2200 | operation: "getPullRequestStack", |
| 2201 | path: `repos/${owner}/${name}/stacks?pull_request=${input.number}`, |
| 2202 | decode: decodePullRequestStacksJson, |
| 2203 | }).pipe( |
| 2204 | // @effect-diagnostics-next-line flatMapConditionalToFilterOrFail:off - the fallback needs a non-null stack, which a predicate that also reads includeDetails cannot refine. |
| 2205 | Effect.flatMap((stack) => { |
| 2206 | if (!input.includeDetails || stack === null) return Effect.succeed(stack); |
| 2207 | return restRead({ |
| 2208 | cwd: input.cwd, |
| 2209 | host: input.host, |
| 2210 | operation: "getPullRequestStack", |
| 2211 | path: `repos/${owner}/${name}/stacks/${stack.number}`, |
| 2212 | decode: (raw) => decodePullRequestStacksJson(`[${raw}]`), |
| 2213 | }); |
| 2214 | }), |
| 2215 | // 404 means stacks are unsupported; other failures must preserve synced stacks for a retry. |
| 2216 | Effect.catchTags({ |
| 2217 | GitHubApiNotFoundError: () => Effect.succeed(null), |
| 2218 | }), |
| 2219 | ); |
| 2220 | }), |
| 2221 | |
| 2222 | getPullRequestActivity: Effect.fn("GitHubPullRequestApi.getPullRequestActivity")( |
| 2223 | function* (input) { |
| 2224 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2225 | let author: PullRequestActor | null = null; |
| 2226 | let commits: ReadonlyArray<PullRequestCommit> = []; |
| 2227 | let nonMergeCommitIds: ReadonlyArray<string> = []; |
| 2228 | const remarks: PullRequestComment[] = []; |
| 2229 | let commentsAfter: string | null = null; |
| 2230 | let reviewsAfter: string | null = null; |
| 2231 | let withComments = true; |
| 2232 | let withReviews = true; |
| 2233 | const target = { ...input, operation: "getPullRequestActivity" }; |
| 2234 | const readPage = Effect.fn("GitHubPullRequestApi.readActivityPage")(function* ( |
| 2235 | page: number, |
| 2236 | ) { |
| 2237 | const read: GitHubPullRequestActivityPage = yield* client |
| 2238 | .PullRequestActivity({ |
| 2239 | owner, |
| 2240 | name, |
| 2241 | number: input.number, |
| 2242 | head: page === 0, |
| 2243 | withComments, |
| 2244 | commentsAfter, |
| 2245 | withReviews, |
| 2246 | reviewsAfter, |
| 2247 | }) |
| 2248 | .pipe( |
| 2249 | graphql(target), |
| 2250 | Effect.map(toPullRequestActivityPage), |
| 2251 | Effect.flatMap(found(target)), |
| 2252 | ); |
| 2253 | if (page === 0) { |
| 2254 | author = read.author ?? null; |
| 2255 | commits = read.commits ?? []; |
| 2256 | nonMergeCommitIds = read.nonMergeCommitIds; |
| 2257 | } |
| 2258 | remarks.push(...read.remarks); |
| 2259 | commentsAfter = read.nextCommentsCursor; |
| 2260 | reviewsAfter = read.nextReviewsCursor; |
| 2261 | withComments = withComments && commentsAfter !== null; |
| 2262 | withReviews = withReviews && reviewsAfter !== null; |
| 2263 | }); |
| 2264 | yield* readPage(0); |
| 2265 | const laterPages = Effect.gen(function* () { |
| 2266 | for (let page = 1; page < REVIEW_THREAD_PAGES; page++) { |
| 2267 | if (!withComments && !withReviews) return; |
| 2268 | yield* readPage(page); |
| 2269 | } |
| 2270 | }); |
| 2271 | const emptyStats = toPullRequestCommitStats({ nodes: [] }); |
| 2272 | const [, commitStats] = yield* Effect.all( |
| 2273 | [ |
| 2274 | laterPages, |
| 2275 | nonMergeCommitIds.length === 0 |
| 2276 | ? Effect.succeed(emptyStats) |
| 2277 | : client.PullRequestCommitStats({ ids: nonMergeCommitIds }).pipe( |
| 2278 | graphql(target), |
| 2279 | Effect.map(toPullRequestCommitStats), |
| 2280 | Effect.orElseSucceed(() => emptyStats), |
| 2281 | ), |
| 2282 | ], |
| 2283 | { concurrency: 2 }, |
| 2284 | ); |
| 2285 | return { |
| 2286 | author, |
| 2287 | comments: remarks.toSorted((left, right) => |
| 2288 | left.createdAt.localeCompare(right.createdAt), |
| 2289 | ), |
| 2290 | commits: commits.map((commit) => ({ ...commit, ...commitStats.get(commit.oid) })), |
| 2291 | truncated: commentsAfter !== null || reviewsAfter !== null, |
| 2292 | } satisfies GitHubPullRequestActivity; |
| 2293 | }, |
| 2294 | ), |
| 2295 | |
| 2296 | getPullRequestDiff: Effect.fn("GitHubPullRequestApi.getPullRequestDiff")(function (input) { |
| 2297 | const filesPage = (page: number) => |
| 2298 | diffFilesPage({ |
| 2299 | cwd: input.cwd, |
| 2300 | repository: input.repository, |
| 2301 | host: input.host, |
| 2302 | number: input.number, |
| 2303 | page, |
| 2304 | ...(input.commit === undefined ? {} : { commit: input.commit }), |
| 2305 | }); |
| 2306 | if (input.commit !== undefined && !isCommitSha(input.commit)) { |
| 2307 | return Effect.fail(new GitHubDiffCommitError({ cwd: input.cwd })); |
| 2308 | } |
| 2309 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2310 | const fullDiff = (maxResponseBytes: number) => |
| 2311 | api.rest({ |
| 2312 | host: input.host, |
| 2313 | operation: "getPullRequestDiff", |
| 2314 | path: |
| 2315 | input.commit === undefined |
| 2316 | ? `repos/${owner}/${name}/pulls/${input.number}` |
| 2317 | : `repos/${owner}/${name}/commits/${input.commit}`, |
| 2318 | accept: "application/vnd.github.diff", |
| 2319 | maxResponseBytes, |
| 2320 | timeout: DIFF_TIMEOUT, |
| 2321 | }); |
| 2322 | // GitHub has no per-file diff, so a withheld file is cut from the whole patch here and |
| 2323 | // only its section reaches the client. |
| 2324 | if (input.path !== undefined) { |
| 2325 | const path = input.path; |
| 2326 | return fullDiff(WITHHELD_FILE_DIFF_MAX_OUTPUT_BYTES).pipe( |
| 2327 | Effect.flatMap((response) => { |
| 2328 | const section = response.truncated ? null : diffFileSection(response.body, path); |
| 2329 | if (section === null) { |
| 2330 | return Effect.fail( |
| 2331 | readError( |
| 2332 | input.cwd, |
| 2333 | "getPullRequestDiff", |
| 2334 | new Error( |
| 2335 | response.truncated |
| 2336 | ? `The diff for ${path} is too large to load.` |
| 2337 | : `GitHub's diff does not include ${path}.`, |
| 2338 | ), |
| 2339 | ), |
| 2340 | ); |
| 2341 | } |
| 2342 | return Effect.succeed({ |
| 2343 | patch: truncateLongDiffLines(section, WITHHELD_FILE_MAX_LINE_LENGTH), |
| 2344 | truncated: false, |
| 2345 | nextCursor: null, |
| 2346 | }); |
| 2347 | }), |
| 2348 | ); |
| 2349 | } |
| 2350 | if (input.cursor !== undefined) { |
| 2351 | const page = diffCursorPage(input.cursor); |
| 2352 | return page === null |
| 2353 | ? Effect.fail(new GitHubDiffCursorError({ cwd: input.cwd })) |
| 2354 | : filesPage(page); |
| 2355 | } |
| 2356 | // A withheld file is read from the whole diff, so it is readable unless GitHub refused that. |
| 2357 | const readableFirstPage = () => |
| 2358 | filesPage(1).pipe( |
| 2359 | Effect.map((slice): GitHubPullRequestDiffSlice => ({ |
| 2360 | ...slice, |
| 2361 | withheldFilesReadable: true, |
| 2362 | })), |
| 2363 | ); |
| 2364 | if (input.commit !== undefined) { |
| 2365 | return readableFirstPage(); |
| 2366 | } |
| 2367 | return fullDiff(DIFF_MAX_OUTPUT_BYTES).pipe( |
| 2368 | Effect.flatMap((response) => |
| 2369 | response.truncated |
| 2370 | ? readableFirstPage() |
| 2371 | : Effect.succeed({ patch: response.body, truncated: false, nextCursor: null }), |
| 2372 | ), |
| 2373 | // Above 300 changed files (or about 20,000 lines), GitHub returns 406; use the paged |
| 2374 | // files API. That refusal also covers a single file's read, so none is offered. |
| 2375 | Effect.catchTags({ |
| 2376 | GitHubApiResponseError: (error) => filesPage(1).pipe(Effect.mapError(() => error)), |
| 2377 | }), |
| 2378 | ); |
| 2379 | }), |
| 2380 | |
| 2381 | getPullRequestDiffFileContents, |
| 2382 | |
| 2383 | getReviewThreadComments: Effect.fn("GitHubPullRequestApi.getReviewThreadComments")( |
| 2384 | function (input) { |
| 2385 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2386 | return client |
| 2387 | .ReviewThreadComments({ |
| 2388 | owner, |
| 2389 | name, |
| 2390 | number: input.number, |
| 2391 | threadId: input.threadId, |
| 2392 | after: input.cursor, |
| 2393 | }) |
| 2394 | .pipe( |
| 2395 | graphql({ ...input, operation: "getReviewThreadComments" }), |
| 2396 | Effect.map(toReviewThreadCommentsPage), |
| 2397 | Effect.flatMap(({ belongsToPullRequest, ...page }) => |
| 2398 | belongsToPullRequest |
| 2399 | ? Effect.succeed(page) |
| 2400 | : Effect.fail( |
| 2401 | new GitHubSubjectScopeError({ |
| 2402 | cwd: input.cwd, |
| 2403 | operation: "getReviewThreadComments", |
| 2404 | }), |
| 2405 | ), |
| 2406 | ), |
| 2407 | ); |
| 2408 | }, |
| 2409 | ), |
| 2410 | |
| 2411 | listReviewThreadComments: Effect.fn("GitHubPullRequestApi.listReviewThreadComments")( |
| 2412 | function* (input) { |
| 2413 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2414 | const target = { ...input, operation: "listReviewThreadComments" }; |
| 2415 | const first: GitHubReviewThreadPage = yield* readRequestedReviewers( |
| 2416 | input, |
| 2417 | 50, |
| 2418 | (requestedReviewers) => |
| 2419 | client.ReviewThreads({ owner, name, number: input.number, requestedReviewers }), |
| 2420 | ).pipe(graphql(target), Effect.map(toReviewThreadPage), Effect.flatMap(found(target))); |
| 2421 | const entries: GitHubReviewThreadEntry[] = [...first.threads]; |
| 2422 | const avatarsByLogin = new Map(first.avatarsByLogin); |
| 2423 | const botLogins = new Set(first.botLogins); |
| 2424 | const { reviewers, reactions, reactionsById, editedAtById, commits, viewer } = first; |
| 2425 | const dismissalsByReviewId = new Map(first.dismissalsByReviewId); |
| 2426 | const dismissalCursor = first.nextDismissalCursor; |
| 2427 | let cursor = first.nextCursor; |
| 2428 | let page = 1; |
| 2429 | // Later pages carry the threads alone; the PR-wide fields above come from the first. |
| 2430 | while (cursor !== null && page < REVIEW_THREAD_PAGES) { |
| 2431 | const later: Pick< |
| 2432 | GitHubReviewThreadPage, |
| 2433 | "threads" | "nextCursor" | "avatarsByLogin" | "botLogins" |
| 2434 | > = yield* client |
| 2435 | .ReviewThreadPages({ owner, name, number: input.number, after: cursor }) |
| 2436 | .pipe( |
| 2437 | graphql(target), |
| 2438 | Effect.map(toLaterReviewThreadPage), |
| 2439 | Effect.flatMap(found(target)), |
| 2440 | ); |
| 2441 | entries.push(...later.threads); |
| 2442 | for (const login of later.botLogins) botLogins.add(login); |
| 2443 | for (const [login, avatarUrl] of later.avatarsByLogin) |
| 2444 | avatarsByLogin.set(login, avatarUrl); |
| 2445 | cursor = later.nextCursor; |
| 2446 | page += 1; |
| 2447 | } |
| 2448 | |
| 2449 | if (dismissalCursor !== null) { |
| 2450 | let after: string | null = dismissalCursor; |
| 2451 | const pages: Array<{ |
| 2452 | readonly dismissalsByReviewId: ReadonlyMap<string, string>; |
| 2453 | }> = []; |
| 2454 | const seen = new Set<string>(); |
| 2455 | // Carries on from the thread read's own cursor, which `GraphQLClient.pages` cannot. |
| 2456 | while (after !== null && pages.length < REVIEW_THREAD_PAGES && !seen.has(after)) { |
| 2457 | seen.add(after); |
| 2458 | const read: { |
| 2459 | readonly dismissalsByReviewId: ReadonlyMap<string, string>; |
| 2460 | readonly nextCursor: string | null; |
| 2461 | } = yield* client |
| 2462 | .ReviewDismissals({ owner, name, number: input.number, after }) |
| 2463 | .pipe( |
| 2464 | graphql(target), |
| 2465 | Effect.map(toReviewDismissalsPage), |
| 2466 | Effect.flatMap(found(target)), |
| 2467 | ); |
| 2468 | pages.push(read); |
| 2469 | after = read.nextCursor; |
| 2470 | } |
| 2471 | for (const read of pages) |
| 2472 | for (const [id, message] of read.dismissalsByReviewId) |
| 2473 | dismissalsByReviewId.set(id, message); |
| 2474 | } |
| 2475 | |
| 2476 | const reviewThreads = entries.map((entry) => ({ |
| 2477 | ...entry.thread, |
| 2478 | commentCount: entry.commentCount, |
| 2479 | ...(entry.nextCommentCursor === null |
| 2480 | ? {} |
| 2481 | : { nextCommentsCursor: entry.nextCommentCursor }), |
| 2482 | })); |
| 2483 | return { |
| 2484 | comments: reviewThreadConversation(reviewThreads), |
| 2485 | dismissalsByReviewId, |
| 2486 | reviewThreads, |
| 2487 | commentCount: entries.reduce((total, entry) => total + entry.commentCount, 0), |
| 2488 | truncated: cursor !== null || entries.some((entry) => entry.nextCommentCursor !== null), |
| 2489 | reviewThreadsTruncated: cursor !== null, |
| 2490 | reactions, |
| 2491 | reactionsById, |
| 2492 | editedAtById, |
| 2493 | reviewers, |
| 2494 | avatarsByLogin, |
| 2495 | botLogins, |
| 2496 | commits, |
| 2497 | viewer, |
| 2498 | }; |
| 2499 | }, |
| 2500 | ), |
| 2501 | |
| 2502 | getViewerAccess: Effect.fn("GitHubPullRequestApi.getViewerAccess")(function (input) { |
| 2503 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2504 | const operation = "getViewerAccess"; |
| 2505 | return client |
| 2506 | .ViewerPermissions({ owner, name, number: input.number }) |
| 2507 | .pipe( |
| 2508 | graphql({ ...input, operation }), |
| 2509 | Effect.map(toViewerPermissions), |
| 2510 | Effect.flatMap(found({ ...input, operation })), |
| 2511 | ); |
| 2512 | }), |
| 2513 | |
| 2514 | listReviewerCandidates: Effect.fn("GitHubPullRequestApi.listReviewerCandidates")( |
| 2515 | function (input) { |
| 2516 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2517 | const operation = "listReviewerCandidates"; |
| 2518 | return client |
| 2519 | .ReviewerCandidates({ owner, name, number: input.number, query: input.query ?? null }) |
| 2520 | .pipe( |
| 2521 | graphql({ ...input, operation, allowReserve: true }), |
| 2522 | Effect.map((result) => toReviewerCandidates(result, input.query)), |
| 2523 | Effect.flatMap(found({ ...input, operation })), |
| 2524 | ); |
| 2525 | }, |
| 2526 | ), |
| 2527 | |
| 2528 | setReviewerRequest: Effect.fn("GitHubPullRequestApi.setReviewerRequest")(function (input) { |
| 2529 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2530 | return api |
| 2531 | .rest({ |
| 2532 | host: input.host, |
| 2533 | operation: "setReviewerRequest", |
| 2534 | method: input.requested ? "POST" : "DELETE", |
| 2535 | path: `repos/${owner}/${name}/pulls/${input.number}/requested_reviewers`, |
| 2536 | body: buildReviewerRequest(input.reviewers), |
| 2537 | }) |
| 2538 | .pipe(Effect.asVoid); |
| 2539 | }), |
| 2540 | |
| 2541 | listLabelCandidates: Effect.fn("GitHubPullRequestApi.listLabelCandidates")(function (input) { |
| 2542 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2543 | const operation = "listLabelCandidates"; |
| 2544 | return client |
| 2545 | .LabelCandidates({ owner, name, number: input.number }) |
| 2546 | .pipe( |
| 2547 | graphql({ ...input, operation, allowReserve: true }), |
| 2548 | Effect.map(toLabelCandidates), |
| 2549 | Effect.flatMap(found({ ...input, operation })), |
| 2550 | ); |
| 2551 | }), |
| 2552 | |
| 2553 | listRepositoryLabels: Effect.fn("GitHubPullRequestApi.listRepositoryLabels")(function (input) { |
| 2554 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2555 | const operation = "listRepositoryLabels"; |
| 2556 | return client |
| 2557 | .RepositoryLabels({ owner, name, query: input.query ?? null }) |
| 2558 | .pipe( |
| 2559 | graphql({ ...input, operation, allowReserve: true }), |
| 2560 | Effect.map(toRepositoryLabels), |
| 2561 | Effect.flatMap(found({ ...input, operation })), |
| 2562 | ); |
| 2563 | }), |
| 2564 | |
| 2565 | searchRepositoryAuthors: Effect.fn("GitHubPullRequestApi.searchRepositoryAuthors")( |
| 2566 | function (input) { |
| 2567 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2568 | const operation = "searchRepositoryAuthors"; |
| 2569 | return client |
| 2570 | .RepositoryAuthors({ owner, name, query: input.query ?? null }) |
| 2571 | .pipe( |
| 2572 | graphql({ ...input, operation, allowReserve: true }), |
| 2573 | Effect.map(toRepositoryAuthors), |
| 2574 | Effect.flatMap(found({ ...input, operation })), |
| 2575 | ); |
| 2576 | }, |
| 2577 | ), |
| 2578 | |
| 2579 | searchRepositoryReferences: Effect.fn("GitHubPullRequestApi.searchRepositoryReferences")( |
| 2580 | function (input) { |
| 2581 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2582 | const parsed = /^\d+$/.test(input.query ?? "") ? Number(input.query) : 0; |
| 2583 | // GraphQL validates `$number: Int!` even when `@include` skips the lookup. |
| 2584 | const exact = parsed > 0 && parsed <= 2_147_483_647; |
| 2585 | const search = (lookup: boolean) => |
| 2586 | client.RepositoryReferences({ |
| 2587 | owner, |
| 2588 | name, |
| 2589 | q: referenceSearchQuery(input.repository, input.query), |
| 2590 | number: lookup ? parsed : 0, |
| 2591 | exact: lookup, |
| 2592 | }); |
| 2593 | return search(exact).pipe( |
| 2594 | // A missing number fails the whole query, which would discard the search results. |
| 2595 | Effect.catchIf( |
| 2596 | (error) => exact && isNotFoundOnly(error), |
| 2597 | () => search(false), |
| 2598 | ), |
| 2599 | graphql({ ...input, operation: "searchRepositoryReferences", allowReserve: true }), |
| 2600 | Effect.map(toRepositoryReferences), |
| 2601 | ); |
| 2602 | }, |
| 2603 | ), |
| 2604 | |
| 2605 | setLabels: Effect.fn("GitHubPullRequestApi.setLabels")(function (input) { |
| 2606 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2607 | const issue = `repos/${owner}/${name}/issues/${input.number}/labels`; |
| 2608 | if (input.applied) { |
| 2609 | return api |
| 2610 | .rest({ |
| 2611 | host: input.host, |
| 2612 | operation: "setLabels", |
| 2613 | method: "POST", |
| 2614 | path: issue, |
| 2615 | body: buildLabelRequest(input.labels), |
| 2616 | }) |
| 2617 | .pipe(Effect.asVoid); |
| 2618 | } |
| 2619 | return Effect.forEach( |
| 2620 | input.labels, |
| 2621 | (label) => |
| 2622 | api.rest({ |
| 2623 | host: input.host, |
| 2624 | operation: "setLabels", |
| 2625 | method: "DELETE", |
| 2626 | path: `${issue}/${encodeURIComponent(label)}`, |
| 2627 | }), |
| 2628 | { concurrency: 1, discard: true }, |
| 2629 | ); |
| 2630 | }), |
| 2631 | |
| 2632 | runPullRequestAction: Effect.fn("GitHubPullRequestApi.runPullRequestAction")(function (input) { |
| 2633 | if (input.action === "delete-branch") { |
| 2634 | return Effect.gen(function* () { |
| 2635 | if (input.stackNumber !== undefined) { |
| 2636 | return yield* new GitHubBranchDeletionRefusedError({ |
| 2637 | number: input.number, |
| 2638 | reason: "stack", |
| 2639 | }); |
| 2640 | } |
| 2641 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2642 | const target = { ...input, operation: "deletePullRequestBranch" }; |
| 2643 | const branch = yield* client |
| 2644 | .PullRequestBranchToDelete({ owner, name, number: input.number }) |
| 2645 | .pipe( |
| 2646 | graphql({ ...target, allowReserve: true }), |
| 2647 | Effect.map((result) => result.repository?.pullRequest ?? null), |
| 2648 | Effect.flatMap(found(target)), |
| 2649 | ); |
| 2650 | if (branch.state === "OPEN") { |
| 2651 | return yield* new GitHubBranchDeletionRefusedError({ |
| 2652 | number: input.number, |
| 2653 | reason: "open-pr", |
| 2654 | }); |
| 2655 | } |
| 2656 | const repositoryId = branch.headRepository?.id; |
| 2657 | if (!repositoryId || !branch.headRefName || !branch.headRefOid) { |
| 2658 | return yield* new GitHubBranchDeletionRefusedError({ |
| 2659 | number: input.number, |
| 2660 | reason: "source-unavailable", |
| 2661 | }); |
| 2662 | } |
| 2663 | if (branch.headRefName === branch.baseRefName) { |
| 2664 | return yield* new GitHubBranchDeletionRefusedError({ |
| 2665 | number: input.number, |
| 2666 | reason: "unsafe-branch", |
| 2667 | }); |
| 2668 | } |
| 2669 | const ref = `refs/heads/${branch.headRefName}`; |
| 2670 | const source = yield* client |
| 2671 | .PullRequestSourceBranch({ repositoryId, ref }) |
| 2672 | .pipe(graphql({ ...target, allowReserve: true })); |
| 2673 | const repository = source.node?.__typename === "Repository" ? source.node : null; |
| 2674 | if (repository === null) { |
| 2675 | return yield* new GitHubBranchDeletionRefusedError({ |
| 2676 | number: input.number, |
| 2677 | reason: "source-unavailable", |
| 2678 | }); |
| 2679 | } |
| 2680 | if (repository.ref === null) return; |
| 2681 | if ( |
| 2682 | repository.defaultBranchRef === null || |
| 2683 | branch.headRefName === repository.defaultBranchRef.name |
| 2684 | ) { |
| 2685 | return yield* new GitHubBranchDeletionRefusedError({ |
| 2686 | number: input.number, |
| 2687 | reason: "unsafe-branch", |
| 2688 | }); |
| 2689 | } |
| 2690 | if (repository.ref.target?.oid !== branch.headRefOid) { |
| 2691 | return yield* new GitHubBranchDeletionRefusedError({ |
| 2692 | number: input.number, |
| 2693 | reason: "head-changed", |
| 2694 | }); |
| 2695 | } |
| 2696 | yield* client |
| 2697 | .DeletePullRequestBranch({ |
| 2698 | input: { |
| 2699 | repositoryId, |
| 2700 | refUpdates: [ |
| 2701 | { |
| 2702 | name: ref, |
| 2703 | beforeOid: branch.headRefOid, |
| 2704 | afterOid: "0000000000000000000000000000000000000000", |
| 2705 | }, |
| 2706 | ], |
| 2707 | }, |
| 2708 | }) |
| 2709 | .pipe(graphql(target)); |
| 2710 | }); |
| 2711 | } |
| 2712 | if (input.stackNumber !== undefined) |
| 2713 | return runGitHubStackAction({ ...input, stackNumber: input.stackNumber }).pipe( |
| 2714 | Effect.provideService(GitHubRest.GitHubRest, api), |
| 2715 | Effect.provideService(GitHubAppAccess.GitHubAppAccess, appAccess), |
| 2716 | Effect.provideService(GitHubRequestPolicy.GitHubRequestPolicy, policy), |
| 2717 | Effect.provideService(HttpClient.HttpClient, httpClient), |
| 2718 | Effect.provideService(SourceControlHost.SourceControlHost, sourceControlHost), |
| 2719 | Effect.provideService(FileSystem.FileSystem, fileSystem), |
| 2720 | ); |
| 2721 | if (input.action === "revert") { |
| 2722 | return pullRequestNodeId({ ...input, operation: "revertPullRequest" }).pipe( |
| 2723 | Effect.flatMap((pullRequestId) => |
| 2724 | client |
| 2725 | .RevertPullRequest({ pullRequestId }) |
| 2726 | .pipe(graphql({ ...input, operation: "revertPullRequest" })), |
| 2727 | ), |
| 2728 | Effect.asVoid, |
| 2729 | ); |
| 2730 | } |
| 2731 | if (input.action === "approve-workflows") { |
| 2732 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2733 | return getPullRequestDetail(input).pipe( |
| 2734 | Effect.flatMap((detail) => { |
| 2735 | if (detail.isCrossRepository !== true) return Effect.void; |
| 2736 | if (detail.headSha == null || detail.headRepositoryOwner == null) { |
| 2737 | return Effect.fail( |
| 2738 | new GitHubWorkflowApprovalHeadUnavailableError({ |
| 2739 | cwd: input.cwd, |
| 2740 | number: input.number, |
| 2741 | }), |
| 2742 | ); |
| 2743 | } |
| 2744 | const expectedHeadSha = detail.headSha; |
| 2745 | const expectedHeadBranch = detail.headBranch; |
| 2746 | const expectedHeadRepositoryOwner = detail.headRepositoryOwner; |
| 2747 | return listWorkflowRunsRequiringApproval({ |
| 2748 | ...input, |
| 2749 | headSha: expectedHeadSha, |
| 2750 | headBranch: expectedHeadBranch, |
| 2751 | headRepositoryOwner: expectedHeadRepositoryOwner, |
| 2752 | isCrossRepository: true, |
| 2753 | }).pipe( |
| 2754 | Effect.flatMap((runs) => |
| 2755 | Effect.forEach( |
| 2756 | runs, |
| 2757 | (run) => |
| 2758 | getPullRequestDetail(input).pipe( |
| 2759 | Effect.flatMap((current) => { |
| 2760 | if (current.headSha == null || current.headRepositoryOwner == null) { |
| 2761 | return Effect.fail( |
| 2762 | new GitHubWorkflowApprovalHeadUnavailableError({ |
| 2763 | cwd: input.cwd, |
| 2764 | number: input.number, |
| 2765 | }), |
| 2766 | ); |
| 2767 | } |
| 2768 | if ( |
| 2769 | current.isCrossRepository !== true || |
| 2770 | current.headSha !== expectedHeadSha || |
| 2771 | current.headBranch !== expectedHeadBranch || |
| 2772 | current.headRepositoryOwner.toLowerCase() !== |
| 2773 | expectedHeadRepositoryOwner.toLowerCase() |
| 2774 | ) { |
| 2775 | return Effect.fail( |
| 2776 | new GitHubWorkflowApprovalHeadChangedError({ |
| 2777 | cwd: input.cwd, |
| 2778 | number: input.number, |
| 2779 | }), |
| 2780 | ); |
| 2781 | } |
| 2782 | return listWorkflowRunsRequiringApproval({ |
| 2783 | ...input, |
| 2784 | headSha: current.headSha, |
| 2785 | headBranch: current.headBranch, |
| 2786 | headRepositoryOwner: current.headRepositoryOwner, |
| 2787 | isCrossRepository: true, |
| 2788 | }); |
| 2789 | }), |
| 2790 | Effect.flatMap((currentRuns) => |
| 2791 | currentRuns.some((current) => current.id === run.id) |
| 2792 | ? api |
| 2793 | .rest({ |
| 2794 | host: input.host, |
| 2795 | operation: "approveWorkflowRun", |
| 2796 | method: "POST", |
| 2797 | path: `repos/${owner}/${name}/actions/runs/${run.id}/approve`, |
| 2798 | }) |
| 2799 | .pipe(Effect.asVoid) |
| 2800 | : Effect.void, |
| 2801 | ), |
| 2802 | ), |
| 2803 | { concurrency: 1, discard: true }, |
| 2804 | ), |
| 2805 | ), |
| 2806 | ); |
| 2807 | }), |
| 2808 | ); |
| 2809 | } |
| 2810 | const action = input.action; |
| 2811 | if (action in simpleActionMutations) { |
| 2812 | const mutate = simpleActionMutations[action as keyof typeof simpleActionMutations]; |
| 2813 | return pullRequestNodeId({ ...input, operation: "runPullRequestAction" }).pipe( |
| 2814 | Effect.flatMap((pullRequestId) => |
| 2815 | actionSummary(mutate(pullRequestId)).pipe( |
| 2816 | graphql({ ...input, operation: "runPullRequestAction" }), |
| 2817 | ), |
| 2818 | ), |
| 2819 | ); |
| 2820 | } |
| 2821 | return Effect.gen(function* () { |
| 2822 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2823 | // Fresh head and merge-queue state determine the mutation's revision and route. |
| 2824 | const target = { ...input, operation: "runPullRequestAction" }; |
| 2825 | const state = yield* client |
| 2826 | .PullRequestActionState({ |
| 2827 | owner, |
| 2828 | name, |
| 2829 | number: input.number, |
| 2830 | headRef: `refs/pull/${input.number}/head`, |
| 2831 | }) |
| 2832 | .pipe( |
| 2833 | toleratingMissingPullRef(decodePullRequestActionState), |
| 2834 | graphql({ ...target, allowReserve: true }), |
| 2835 | Effect.map((result) => result.repository?.pullRequest ?? null), |
| 2836 | Effect.flatMap(found(target)), |
| 2837 | ); |
| 2838 | if (action === "update-branch") { |
| 2839 | if (state.baseRef?.compare?.behindBy === 0) return; |
| 2840 | return yield* client |
| 2841 | .UpdatePullRequestBranch({ |
| 2842 | pullRequestId: state.id, |
| 2843 | expectedHeadOid: state.headRefOid, |
| 2844 | updateMethod: input.updateMethod === "rebase" ? "REBASE" : "MERGE", |
| 2845 | }) |
| 2846 | .pipe( |
| 2847 | Effect.map((result) => result.updatePullRequestBranch?.pullRequest), |
| 2848 | actionSummary, |
| 2849 | graphql(target), |
| 2850 | ); |
| 2851 | } |
| 2852 | let body: string | undefined; |
| 2853 | let expectedHead: string | undefined; |
| 2854 | if (input.removeAgentCreditsOnMerge === true && input.mergeMethod !== "rebase") { |
| 2855 | const message = yield* client |
| 2856 | .PullRequestMergeMessage({ |
| 2857 | owner, |
| 2858 | name, |
| 2859 | number: input.number, |
| 2860 | method: input.mergeMethod === "squash" ? "SQUASH" : "MERGE", |
| 2861 | }) |
| 2862 | .pipe( |
| 2863 | graphql({ ...target, allowReserve: true }), |
| 2864 | Effect.map((result) => result.repository?.pullRequest ?? null), |
| 2865 | Effect.flatMap(found(target)), |
| 2866 | ); |
| 2867 | // GitHub's merge queue chooses its own message and ignores custom text. |
| 2868 | if (!message.isMergeQueueEnabled) { |
| 2869 | const cleaned = removeAgentCredits(message.viewerMergeBodyText); |
| 2870 | if (cleaned !== message.viewerMergeBodyText) { |
| 2871 | body = cleaned; |
| 2872 | expectedHead = message.headRefOid; |
| 2873 | } |
| 2874 | } |
| 2875 | } |
| 2876 | // Merge queues always use auto-merge. A PR that became ready since detail loaded |
| 2877 | // merges directly, matching `gh pr merge --auto`. |
| 2878 | const auto = |
| 2879 | state.isMergeQueueEnabled === true || |
| 2880 | (action === "enable-auto-merge" && |
| 2881 | !IMMEDIATELY_MERGEABLE.has(state.mergeStateStatus?.toUpperCase() ?? "")); |
| 2882 | const merge = { |
| 2883 | pullRequestId: state.id, |
| 2884 | mergeMethod: GRAPHQL_MERGE_METHODS[input.mergeMethod ?? "merge"] ?? "MERGE", |
| 2885 | ...((input.expectedHeadSha ?? expectedHead) === undefined |
| 2886 | ? {} |
| 2887 | : { expectedHeadOid: input.expectedHeadSha ?? expectedHead }), |
| 2888 | ...(body === undefined ? {} : { commitBody: body }), |
| 2889 | }; |
| 2890 | return yield* actionSummary( |
| 2891 | auto |
| 2892 | ? client |
| 2893 | .EnablePullRequestAutoMerge({ input: merge }) |
| 2894 | .pipe(Effect.map((result) => result.enablePullRequestAutoMerge?.pullRequest)) |
| 2895 | : client |
| 2896 | .MergePullRequest({ input: merge }) |
| 2897 | .pipe(Effect.map((result) => result.mergePullRequest?.pullRequest)), |
| 2898 | ).pipe(graphql(target)); |
| 2899 | }); |
| 2900 | }), |
| 2901 | |
| 2902 | commentOnPullRequest: Effect.fn("GitHubPullRequestApi.commentOnPullRequest")(function (input) { |
| 2903 | return pullRequestNodeId({ ...input, operation: "commentOnPullRequest" }).pipe( |
| 2904 | Effect.flatMap((subjectId) => |
| 2905 | client |
| 2906 | .AddComment({ subjectId, body: input.body }) |
| 2907 | .pipe(graphql({ ...input, operation: "commentOnPullRequest" })), |
| 2908 | ), |
| 2909 | Effect.asVoid, |
| 2910 | ); |
| 2911 | }), |
| 2912 | |
| 2913 | readCheckLogs: Effect.fn("GitHubPullRequestApi.readCheckLogs")(function* (input) { |
| 2914 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2915 | return yield* Effect.forEach( |
| 2916 | input.checks, |
| 2917 | (check) => { |
| 2918 | const jobId = gitHubActionsJobId(check.url); |
| 2919 | if (jobId === null) { |
| 2920 | return Effect.succeed({ |
| 2921 | ...check, |
| 2922 | log: null, |
| 2923 | truncated: false, |
| 2924 | detail: "This check is not a GitHub Actions job, so GitHub holds no log for it.", |
| 2925 | }); |
| 2926 | } |
| 2927 | // The log is a redirect to storage; fetch drops the credential when it leaves GitHub. |
| 2928 | return api |
| 2929 | .rest({ |
| 2930 | host: input.host, |
| 2931 | operation: "readCheckLog", |
| 2932 | path: `repos/${owner}/${name}/actions/jobs/${jobId}/logs`, |
| 2933 | maxResponseBytes: CHECK_LOG_MAX_BYTES, |
| 2934 | timeout: "60 seconds", |
| 2935 | }) |
| 2936 | .pipe( |
| 2937 | Effect.map((response) => { |
| 2938 | const tail = tailLogLines(response.body, input.tailLines); |
| 2939 | return { |
| 2940 | ...check, |
| 2941 | log: tail.log, |
| 2942 | truncated: tail.truncated || response.truncated, |
| 2943 | detail: response.truncated |
| 2944 | ? "The log is too large; this is from its start." |
| 2945 | : null, |
| 2946 | }; |
| 2947 | }), |
| 2948 | // Sign-in and rate-limit failures fail the call; the rest are this check's. |
| 2949 | Effect.catchTags({ |
| 2950 | GitHubApiNotFoundError: (error) => |
| 2951 | Effect.succeed({ ...check, log: null, truncated: false, detail: error.message }), |
| 2952 | GitHubApiResponseError: (error) => |
| 2953 | Effect.succeed({ ...check, log: null, truncated: false, detail: error.message }), |
| 2954 | }), |
| 2955 | ); |
| 2956 | }, |
| 2957 | { concurrency: 4 }, |
| 2958 | ); |
| 2959 | }), |
| 2960 | |
| 2961 | rerunChecks: Effect.fn("GitHubPullRequestApi.rerunChecks")(function* (input) { |
| 2962 | const { owner, name } = parseRepositorySelector(input.repository); |
| 2963 | const root = `repos/${owner}/${name}/actions`; |
| 2964 | const located = yield* Effect.forEach( |
| 2965 | input.checks, |
| 2966 | (check): Effect.Effect<LocatedCheckJob, GitHubPullRequestApiError> => { |
| 2967 | const jobId = gitHubActionsJobId(check.url); |
| 2968 | if (jobId === null) |
| 2969 | return Effect.succeed({ check, jobId, runId: null, detail: NOT_A_JOB }); |
| 2970 | return api |
| 2971 | .rest({ host: input.host, operation: "readCheckJob", path: `${root}/jobs/${jobId}` }) |
| 2972 | .pipe( |
| 2973 | Effect.flatMap((response) => decodeActionsJob(response.body)), |
| 2974 | Effect.map((job) => ({ check, jobId, runId: job.run_id, detail: null })), |
| 2975 | Effect.catchTags({ |
| 2976 | GitHubApiNotFoundError: (error) => |
| 2977 | Effect.succeed({ check, jobId, runId: null, detail: error.message }), |
| 2978 | GitHubApiResponseError: (error) => |
| 2979 | Effect.succeed({ check, jobId, runId: null, detail: error.message }), |
| 2980 | SchemaError: () => Effect.succeed({ check, jobId, runId: null, detail: NOT_A_JOB }), |
| 2981 | }), |
| 2982 | ); |
| 2983 | }, |
| 2984 | { concurrency: 4 }, |
| 2985 | ); |
| 2986 | // GitHub refuses a second job re-run while the run re-runs, so a run's jobs go together. |
| 2987 | const byRun = new Map<number, Array<LocatedCheckJob>>(); |
| 2988 | for (const entry of located) { |
| 2989 | if (entry.runId === null) continue; |
| 2990 | byRun.set(entry.runId, [...(byRun.get(entry.runId) ?? []), entry]); |
| 2991 | } |
| 2992 | const post = (path: string) => |
| 2993 | api.rest({ host: input.host, operation: "rerunChecks", method: "POST", path }).pipe( |
| 2994 | Effect.as<string | null>(null), |
| 2995 | Effect.catchTags({ |
| 2996 | GitHubApiNotFoundError: (error) => Effect.succeed(error.message), |
| 2997 | GitHubApiResponseError: (error) => Effect.succeed(error.message), |
| 2998 | }), |
| 2999 | ); |
| 3000 | const failedJobsOf = (runId: number) => |
| 3001 | api |
| 3002 | .rest({ |
| 3003 | host: input.host, |
| 3004 | operation: "readRunJobs", |
| 3005 | path: `${root}/runs/${runId}/jobs?filter=latest&per_page=100`, |
| 3006 | }) |
| 3007 | .pipe( |
| 3008 | Effect.flatMap((response) => decodeRunJobs(response.body)), |
| 3009 | // Jobs past the first page are unseen, so such a run counts as unknown. |
| 3010 | Effect.map(({ total_count, jobs }) => |
| 3011 | total_count > jobs.length |
| 3012 | ? new Set<string>() |
| 3013 | : new Set( |
| 3014 | jobs |
| 3015 | .filter((job) => FAILED_CONCLUSIONS.has(job.conclusion ?? "")) |
| 3016 | .map((job) => String(job.id)), |
| 3017 | ), |
| 3018 | ), |
| 3019 | Effect.catchTags({ |
| 3020 | GitHubApiNotFoundError: () => Effect.succeed(new Set<string>()), |
| 3021 | GitHubApiResponseError: () => Effect.succeed(new Set<string>()), |
| 3022 | SchemaError: () => Effect.succeed(new Set<string>()), |
| 3023 | }), |
| 3024 | ); |
| 3025 | const outcomes = new Map<string | null, string | null>(); |
| 3026 | yield* Effect.forEach( |
| 3027 | byRun, |
| 3028 | ([runId, jobs]) => |
| 3029 | Effect.gen(function* () { |
| 3030 | const [first, ...rest] = jobs; |
| 3031 | if (first === undefined) return; |
| 3032 | if (rest.length > 0) { |
| 3033 | // Re-running a run's failed jobs fits only when they are exactly the selection. |
| 3034 | const failed = yield* failedJobsOf(runId); |
| 3035 | if (failed.size === jobs.length && jobs.every((job) => failed.has(job.jobId ?? ""))) { |
| 3036 | const detail = yield* post(`${root}/runs/${runId}/rerun-failed-jobs`); |
| 3037 | for (const job of jobs) outcomes.set(job.jobId, detail); |
| 3038 | return; |
| 3039 | } |
| 3040 | } |
| 3041 | outcomes.set(first.jobId, yield* post(`${root}/jobs/${first.jobId}/rerun`)); |
| 3042 | for (const job of rest) outcomes.set(job.jobId, ONE_JOB_AT_A_TIME); |
| 3043 | }), |
| 3044 | { concurrency: 2, discard: true }, |
| 3045 | ); |
| 3046 | return located.map(({ check, jobId, runId, detail }) => { |
| 3047 | const outcome = runId === null ? detail : (outcomes.get(jobId) ?? null); |
| 3048 | return { name: check.name, rerun: runId !== null && outcome === null, detail: outcome }; |
| 3049 | }); |
| 3050 | }), |
| 3051 | |
| 3052 | submitReview: Effect.fn("GitHubPullRequestApi.submitReview")(function (input) { |
| 3053 | const { owner, name } = parseRepositorySelector(input.repository); |
| 3054 | return api |
| 3055 | .rest({ |
| 3056 | host: input.host, |
| 3057 | operation: "submitReview", |
| 3058 | method: "POST", |
| 3059 | path: `repos/${owner}/${name}/pulls/${input.number}/reviews`, |
| 3060 | body: buildReviewSubmission({ |
| 3061 | verdict: input.verdict, |
| 3062 | body: input.body, |
| 3063 | comments: input.comments, |
| 3064 | }), |
| 3065 | }) |
| 3066 | .pipe(Effect.asVoid); |
| 3067 | }), |
| 3068 | |
| 3069 | replyToReviewThread: Effect.fn("GitHubPullRequestApi.replyToReviewThread")(function (input) { |
| 3070 | return client |
| 3071 | .AddReviewThreadReply({ threadId: input.threadId, body: input.body }) |
| 3072 | .pipe(graphql({ ...input, operation: "replyToReviewThread" }), Effect.asVoid); |
| 3073 | }), |
| 3074 | |
| 3075 | getPullRequestFilesViewed: Effect.fn("GitHubPullRequestApi.getPullRequestFilesViewed")( |
| 3076 | function (input) { |
| 3077 | const { owner, name } = parseRepositorySelector(input.repository); |
| 3078 | const target = { ...input, operation: "getPullRequestFilesViewed" }; |
| 3079 | return readPages( |
| 3080 | GraphQLClient.pages(client.PullRequestFilesViewed, { |
| 3081 | variables: { owner, name, number: input.number }, |
| 3082 | connection: (result) => { |
| 3083 | const page = toPullRequestFilesViewedPage(result); |
| 3084 | return { |
| 3085 | ...page, |
| 3086 | pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor }, |
| 3087 | }; |
| 3088 | }, |
| 3089 | }), |
| 3090 | { |
| 3091 | ...target, |
| 3092 | maxPages: FILES_VIEWED_MAX_PAGES, |
| 3093 | hasNextPage: (page) => page.nextCursor !== null, |
| 3094 | }, |
| 3095 | ).pipe( |
| 3096 | graphql(target), |
| 3097 | Effect.map(({ pages, truncated }) => ({ |
| 3098 | files: pages.flatMap((page) => page.files), |
| 3099 | truncated, |
| 3100 | })), |
| 3101 | ); |
| 3102 | }, |
| 3103 | ), |
| 3104 | |
| 3105 | getPullRequestFileStats: Effect.fn("GitHubPullRequestApi.getPullRequestFileStats")( |
| 3106 | function (input) { |
| 3107 | const { owner, name } = parseRepositorySelector(input.repository); |
| 3108 | const target = { ...input, operation: "getPullRequestFileStats" }; |
| 3109 | return readPages( |
| 3110 | GraphQLClient.pages(client.PullRequestFileStats, { |
| 3111 | variables: { owner, name, number: input.number }, |
| 3112 | connection: (result) => { |
| 3113 | const page = toPullRequestFileStatsPage(result); |
| 3114 | return { |
| 3115 | ...page, |
| 3116 | pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor }, |
| 3117 | }; |
| 3118 | }, |
| 3119 | }), |
| 3120 | { |
| 3121 | ...target, |
| 3122 | maxPages: FILES_VIEWED_MAX_PAGES, |
| 3123 | hasNextPage: (page) => page.nextCursor !== null, |
| 3124 | }, |
| 3125 | ).pipe( |
| 3126 | graphql(target), |
| 3127 | Effect.map(({ pages, truncated }) => ({ |
| 3128 | files: pages.flatMap((page) => page.files), |
| 3129 | truncated, |
| 3130 | })), |
| 3131 | ); |
| 3132 | }, |
| 3133 | ), |
| 3134 | |
| 3135 | setPullRequestFilesViewed: Effect.fn("GitHubPullRequestApi.setPullRequestFilesViewed")( |
| 3136 | function (input) { |
| 3137 | if (input.files.length === 0) return Effect.void; |
| 3138 | const target = { ...input, operation: "setPullRequestFilesViewed" }; |
| 3139 | return pullRequestNodeId(target).pipe( |
| 3140 | Effect.flatMap((pullRequestId) => |
| 3141 | // Top-level mutation fields run in order, so the last toggle for a path wins. |
| 3142 | Effect.forEach( |
| 3143 | input.files, |
| 3144 | (file) => |
| 3145 | GraphQLResolver.request( |
| 3146 | { pullRequestId, path: file.path, viewed: file.viewed }, |
| 3147 | setFileViewedResolver, |
| 3148 | ), |
| 3149 | { concurrency: "unbounded", discard: true }, |
| 3150 | ), |
| 3151 | ), |
| 3152 | graphql(target), |
| 3153 | ); |
| 3154 | }, |
| 3155 | ), |
| 3156 | |
| 3157 | setReviewThreadResolution: Effect.fn("GitHubPullRequestApi.setReviewThreadResolution")( |
| 3158 | function (input) { |
| 3159 | return ( |
| 3160 | input.resolved |
| 3161 | ? client.ResolveReviewThread({ threadId: input.threadId }).pipe(Effect.asVoid) |
| 3162 | : client.UnresolveReviewThread({ threadId: input.threadId }).pipe(Effect.asVoid) |
| 3163 | ).pipe(graphql({ ...input, operation: "setReviewThreadResolution" })); |
| 3164 | }, |
| 3165 | ), |
| 3166 | |
| 3167 | setReaction: Effect.fn("GitHubPullRequestApi.setReaction")(function (input) { |
| 3168 | const givenSubjectId = input.subjectId; |
| 3169 | const subjectId = |
| 3170 | givenSubjectId === undefined |
| 3171 | ? pullRequestNodeId({ ...input, operation: "setReaction" }) |
| 3172 | : subjectBelongsToPullRequest({ |
| 3173 | ...input, |
| 3174 | subjectId: givenSubjectId, |
| 3175 | operation: "setReaction", |
| 3176 | }).pipe( |
| 3177 | Effect.flatMap((belongs) => |
| 3178 | belongs |
| 3179 | ? Effect.succeed(givenSubjectId) |
| 3180 | : Effect.fail( |
| 3181 | new GitHubSubjectScopeError({ |
| 3182 | cwd: input.cwd, |
| 3183 | operation: "setReaction", |
| 3184 | }), |
| 3185 | ), |
| 3186 | ), |
| 3187 | ); |
| 3188 | return subjectId.pipe( |
| 3189 | Effect.flatMap((subjectId) => { |
| 3190 | const variables = { subjectId, content: gitHubReactionContent(input.content) }; |
| 3191 | return ( |
| 3192 | input.reacted |
| 3193 | ? client.AddReaction(variables).pipe(Effect.asVoid) |
| 3194 | : client.RemoveReaction(variables).pipe(Effect.asVoid) |
| 3195 | ).pipe(graphql({ ...input, operation: "setReaction" })); |
| 3196 | }), |
| 3197 | ); |
| 3198 | }), |
| 3199 | |
| 3200 | updatePullRequest: Effect.fn("GitHubPullRequestApi.updatePullRequest")(function (input) { |
| 3201 | return pullRequestNodeId({ ...input, operation: "updatePullRequest" }).pipe( |
| 3202 | Effect.flatMap((pullRequestId) => |
| 3203 | client |
| 3204 | .UpdatePullRequest({ |
| 3205 | pullRequestId, |
| 3206 | ...(input.maintainerCanModify === undefined |
| 3207 | ? {} |
| 3208 | : { maintainerCanModify: input.maintainerCanModify }), |
| 3209 | ...(input.title === undefined ? {} : { title: input.title }), |
| 3210 | ...(input.body === undefined ? {} : { body: input.body }), |
| 3211 | }) |
| 3212 | .pipe(graphql({ ...input, operation: "updatePullRequest" })), |
| 3213 | ), |
| 3214 | Effect.asVoid, |
| 3215 | ); |
| 3216 | }), |
| 3217 | |
| 3218 | updateComment: Effect.fn("GitHubPullRequestApi.updateComment")(function (input) { |
| 3219 | return subjectBelongsToPullRequest({ |
| 3220 | cwd: input.cwd, |
| 3221 | repository: input.repository, |
| 3222 | host: input.host, |
| 3223 | number: input.number, |
| 3224 | subjectId: input.commentId, |
| 3225 | operation: "updateComment", |
| 3226 | }).pipe( |
| 3227 | Effect.flatMap((belongs) => |
| 3228 | belongs |
| 3229 | ? Effect.succeed(input.commentId) |
| 3230 | : Effect.fail( |
| 3231 | new GitHubSubjectScopeError({ |
| 3232 | cwd: input.cwd, |
| 3233 | operation: "updateComment", |
| 3234 | }), |
| 3235 | ), |
| 3236 | ), |
| 3237 | Effect.flatMap((commentId) => { |
| 3238 | const variables = { commentId, body: input.body }; |
| 3239 | return ( |
| 3240 | input.kind === "issue-comment" |
| 3241 | ? client.UpdateIssueComment(variables).pipe(Effect.asVoid) |
| 3242 | : client.UpdateReviewComment(variables).pipe(Effect.asVoid) |
| 3243 | ).pipe(graphql({ ...input, operation: "updateComment" })); |
| 3244 | }), |
| 3245 | ); |
| 3246 | }), |
| 3247 | }); |
| 3248 | }); |
| 3249 | |
| 3250 | export const layer = Layer.effect(GitHubPullRequestApi, make); |