@deepseek-ai/dsh-experimental-forge-github 0.2.2-rc.1 → 0.2.2-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.i18n.yaml +6 -6
  2. package/README.md +27 -6
  3. package/README.zh.md +27 -6
  4. package/lib/index.js +1860 -112
  5. package/lib/types/commits.d.ts +24 -0
  6. package/lib/types/commits.d.ts.map +1 -0
  7. package/lib/types/commits.js.map +1 -0
  8. package/lib/types/compare.d.ts +23 -0
  9. package/lib/types/compare.d.ts.map +1 -0
  10. package/lib/types/compare.js.map +1 -0
  11. package/lib/types/gh.d.ts.map +1 -0
  12. package/lib/types/gh.js.map +1 -0
  13. package/lib/types/graphql.d.ts +66 -10
  14. package/lib/types/graphql.d.ts.map +1 -0
  15. package/lib/types/graphql.js.map +1 -0
  16. package/lib/types/index.d.ts +10 -1
  17. package/lib/types/index.d.ts.map +1 -0
  18. package/lib/types/index.js.map +1 -0
  19. package/lib/types/mutation.d.ts +40 -0
  20. package/lib/types/mutation.d.ts.map +1 -0
  21. package/lib/types/mutation.js.map +1 -0
  22. package/lib/types/overview.d.ts +51 -0
  23. package/lib/types/overview.d.ts.map +1 -0
  24. package/lib/types/overview.js.map +1 -0
  25. package/lib/types/provider.d.ts +71 -6
  26. package/lib/types/provider.d.ts.map +1 -0
  27. package/lib/types/provider.js.map +1 -0
  28. package/lib/types/pull-request-node.d.ts +15 -0
  29. package/lib/types/pull-request-node.d.ts.map +1 -0
  30. package/lib/types/pull-request-node.js.map +1 -0
  31. package/lib/types/review-writes.d.ts +44 -0
  32. package/lib/types/review-writes.d.ts.map +1 -0
  33. package/lib/types/review-writes.js.map +1 -0
  34. package/lib/types/review.d.ts.map +1 -0
  35. package/lib/types/review.js.map +1 -0
  36. package/lib/types/threads.d.ts +37 -0
  37. package/lib/types/threads.d.ts.map +1 -0
  38. package/lib/types/threads.js.map +1 -0
  39. package/lib/types/urls.d.ts +6 -0
  40. package/lib/types/urls.d.ts.map +1 -0
  41. package/lib/types/urls.js.map +1 -0
  42. package/lib/types/viewed.d.ts +37 -0
  43. package/lib/types/viewed.d.ts.map +1 -0
  44. package/lib/types/viewed.js.map +1 -0
  45. package/package.json +13 -9
  46. package/src/commits.ts +102 -0
  47. package/src/compare.ts +43 -0
  48. package/src/gh.ts +71 -0
  49. package/src/graphql.ts +685 -0
  50. package/src/index.ts +60 -0
  51. package/src/mutation.ts +86 -0
  52. package/src/overview.ts +197 -0
  53. package/src/provider.ts +534 -0
  54. package/src/pull-request-node.ts +42 -0
  55. package/src/review-writes.ts +192 -0
  56. package/src/review.ts +59 -0
  57. package/src/threads.ts +262 -0
  58. package/src/urls.ts +89 -0
  59. package/src/viewed.ts +132 -0
package/lib/index.js CHANGED
@@ -4,6 +4,8 @@ import { scrubbedParentEnv } from "@deepseek-ai/dsh-subprocess";
4
4
  import { execa } from "execa";
5
5
  import { changeRequestKey } from "@deepseek-ai/dsh-experimental-forge";
6
6
  import { z as z$1 } from "zod";
7
+ import { assertNever } from "@deepseek-ai/dsh-util-values";
8
+ import { Buffer as Buffer$1 } from "node:buffer";
7
9
  //#region lib/types/gh.js
8
10
  /** Runs the GitHub CLI on the host with a scrubbed, non-interactive environment. */
9
11
  /** Thrown when the `gh` executable cannot start, for example because it is not installed. */
@@ -61,6 +63,8 @@ function ghRunner(config) {
61
63
  /** GitHub remote URL and pull request URL parsing, and validation of the parts inlined into requests. */
62
64
  /** Characters GitHub permits in owner and repository names. */
63
65
  const SEGMENT = /^[A-Za-z0-9_.-]+$/;
66
+ /** A full SHA-1 or SHA-256 object name. */
67
+ const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
64
68
  /**
65
69
  * Check one owner or repository name segment.
66
70
  * @param value - candidate segment.
@@ -83,6 +87,14 @@ function checkedRepository(ref) {
83
87
  return ref.repository;
84
88
  }
85
89
  /**
90
+ * Whether a value is a full commit object name that can be inlined into a request.
91
+ * @param value - candidate commit.
92
+ * @returns whether it is 40 or 64 hexadecimal digits.
93
+ */
94
+ function isCommit(value) {
95
+ return COMMIT.test(value);
96
+ }
97
+ /**
86
98
  * Parse a Git remote URL. Accepts `http(s)://[user@]host[:port]/owner/name`,
87
99
  * `ssh://[user@]host[:port]/owner/name`, `git://host/owner/name`, and the
88
100
  * scp-like `[user@]host:owner/name`, each with an optional `.git` suffix or
@@ -127,6 +139,252 @@ function parsePullRequestUrl(url) {
127
139
  };
128
140
  }
129
141
  //#endregion
142
+ //#region lib/types/commits.js
143
+ /** GitHub pull request commit listing through GraphQL, pinned to one head commit across pages. */
144
+ /** Commits GitHub returns per GraphQL page, its connection maximum. */
145
+ const PAGE$1 = 100;
146
+ /** One page of a pull request's commits with its head; `cursor` continues after the previous page. */
147
+ const COMMITS_QUERY = `query($owner: String!, $name: String!, $number: Int!, $first: Int!, $cursor: String) {
148
+ repository(owner: $owner, name: $name) {
149
+ pullRequest(number: $number) {
150
+ headRefOid
151
+ commits(first: $first, after: $cursor) {
152
+ totalCount
153
+ pageInfo { hasNextPage endCursor }
154
+ nodes { commit { oid messageHeadline authoredDate author { name user { login } } parents(first: 1) { nodes { oid } } } }
155
+ }
156
+ }
157
+ }
158
+ }`;
159
+ const pageSchema$1 = z$1.object({ data: z$1.object({ repository: z$1.object({ pullRequest: z$1.object({
160
+ headRefOid: z$1.string(),
161
+ commits: z$1.object({
162
+ totalCount: z$1.number().int().nonnegative(),
163
+ pageInfo: z$1.object({
164
+ hasNextPage: z$1.boolean(),
165
+ endCursor: z$1.string().nullable()
166
+ }),
167
+ nodes: z$1.array(z$1.object({ commit: z$1.object({
168
+ oid: z$1.string(),
169
+ messageHeadline: z$1.string(),
170
+ authoredDate: z$1.string(),
171
+ author: z$1.object({
172
+ name: z$1.string().nullable(),
173
+ user: z$1.object({ login: z$1.string() }).nullable()
174
+ }).nullable(),
175
+ parents: z$1.object({ nodes: z$1.array(z$1.object({ oid: z$1.string() })) })
176
+ }) }))
177
+ })
178
+ }).nullable() }).nullable() }) });
179
+ /**
180
+ * List a pull request's commits oldest first, at most `limit`, reading pages until the limit or the last commit.
181
+ * Every page must report the head and commit count of the first page, so the list never mixes two pushes, and a cursor
182
+ * no earlier page returned, so the listing ends.
183
+ * @param read - runs one GraphQL request.
184
+ * @param ref - validated pull request address.
185
+ * @param limit - most commits listed.
186
+ * @param signal - cancellation of every page.
187
+ * @returns the commits at one head, or why GitHub did not list them.
188
+ */
189
+ async function listCommits(read, ref, limit, signal) {
190
+ const { host, owner, name } = checkedRepository(ref);
191
+ const commits = [];
192
+ const cursors = /* @__PURE__ */ new Set();
193
+ let first;
194
+ let cursor = null;
195
+ for (;;) {
196
+ const body = await read([
197
+ "api",
198
+ "graphql",
199
+ "--hostname",
200
+ host,
201
+ "-f",
202
+ `query=${COMMITS_QUERY}`,
203
+ "-f",
204
+ `owner=${owner}`,
205
+ "-f",
206
+ `name=${name}`,
207
+ "-F",
208
+ `number=${ref.number}`,
209
+ "-F",
210
+ `first=${Math.min(PAGE$1, limit - commits.length)}`,
211
+ ...cursor === null ? [] : ["-f", `cursor=${cursor}`]
212
+ ], signal);
213
+ if (!body.ok) return body.failure;
214
+ const parsed = pageSchema$1.safeParse(body.body);
215
+ if (!parsed.success) return {
216
+ code: "unavailable",
217
+ message: "unexpected GitHub response to the commit listing"
218
+ };
219
+ const pull = parsed.data.data.repository?.pullRequest;
220
+ if (pull == null) return {
221
+ code: "not-found",
222
+ message: `pull request ${ref.number} was not found`
223
+ };
224
+ const { headRefOid: head, commits: { totalCount: total, pageInfo: { hasNextPage, endCursor } } } = pull;
225
+ first ??= {
226
+ head,
227
+ total
228
+ };
229
+ if (head !== first.head || total !== first.total) return {
230
+ code: "unavailable",
231
+ message: "The pull request head changed while its commits were read"
232
+ };
233
+ for (const { commit } of pull.commits.nodes) commits.push({
234
+ sha: commit.oid,
235
+ parent: commit.parents.nodes[0]?.oid ?? null,
236
+ title: commit.messageHeadline,
237
+ author: commit.author?.user?.login ?? commit.author?.name ?? null,
238
+ authoredAt: commit.authoredDate
239
+ });
240
+ if (!hasNextPage || commits.length >= limit) return {
241
+ headSha: head,
242
+ commits,
243
+ truncated: total > commits.length
244
+ };
245
+ if (endCursor === null || cursors.has(endCursor)) return {
246
+ code: "unavailable",
247
+ message: "GitHub commit pagination did not advance"
248
+ };
249
+ cursors.add(endCursor);
250
+ cursor = endCursor;
251
+ }
252
+ }
253
+ //#endregion
254
+ //#region lib/types/mutation.js
255
+ /** GitHub GraphQL mutations sent once through `gh`, with the document and variables as JSON on standard input. */
256
+ /** HTTP statuses that mean GitHub refused the request, so it changed nothing. */
257
+ const REFUSED = /\(HTTP (?:400|401|403|404|409|422)\)/;
258
+ /**
259
+ * GraphQL error types that mean GitHub refused a mutation before applying it. An error without one of them, such as
260
+ * GitHub's "Something went wrong … may be the result of a timeout", leaves the outcome unknown.
261
+ */
262
+ const REFUSALS = new Set([
263
+ "FORBIDDEN",
264
+ "INSUFFICIENT_SCOPES",
265
+ "NOT_FOUND",
266
+ "RATE_LIMITED",
267
+ "UNPROCESSABLE"
268
+ ]);
269
+ const graphqlErrors = z$1.object({ errors: z$1.array(z$1.object({
270
+ message: z$1.string(),
271
+ type: z$1.string().optional()
272
+ })).min(1) });
273
+ /**
274
+ * Send one mutation with its query and variables as JSON on stdin. The mutation is never retried.
275
+ * @param gh - runs `gh` on the Host.
276
+ * @param host - GitHub host the mutation goes to.
277
+ * @param mutation - the document, its field, and its variables.
278
+ * @param signal - cancellation of the request.
279
+ * @returns the payload of `mutation.field`; `failed` when GitHub reports a refusal by its HTTP status or GraphQL error
280
+ * type, or `gh` cannot start, else `unknown`.
281
+ */
282
+ async function sendMutation(gh, host, mutation, signal) {
283
+ let output;
284
+ try {
285
+ output = await gh([
286
+ "api",
287
+ "graphql",
288
+ "--hostname",
289
+ host,
290
+ "--input",
291
+ "-"
292
+ ], signal, JSON.stringify({
293
+ query: mutation.query,
294
+ variables: mutation.variables
295
+ }));
296
+ } catch (error) {
297
+ const message = error instanceof Error ? error.message : String(error);
298
+ return {
299
+ ok: false,
300
+ code: error instanceof GhUnavailableError ? "failed" : "unknown",
301
+ message
302
+ };
303
+ }
304
+ const body = parse(output.stdout);
305
+ const payload = z$1.object({ data: z$1.record(z$1.string(), z$1.unknown()) }).safeParse(body);
306
+ const value = payload.success ? payload.data.data[mutation.field] : void 0;
307
+ if (value !== void 0 && value !== null) return {
308
+ ok: true,
309
+ payload: value
310
+ };
311
+ const errors = graphqlErrors.safeParse(body);
312
+ if (errors.success) return {
313
+ ok: false,
314
+ code: errors.data.errors.every((error) => error.type !== void 0 && REFUSALS.has(error.type)) ? "failed" : "unknown",
315
+ message: errors.data.errors.map((error) => error.message).join("; ")
316
+ };
317
+ if (output.exitCode !== 0) {
318
+ const message = output.stderr.trim() || output.stdout.trim() || `gh exited with ${output.exitCode}`;
319
+ return {
320
+ ok: false,
321
+ code: REFUSED.test(output.stderr) ? "failed" : "unknown",
322
+ message
323
+ };
324
+ }
325
+ return {
326
+ ok: false,
327
+ code: "unknown",
328
+ message: `unexpected GitHub response to ${mutation.field}`
329
+ };
330
+ }
331
+ function parse(text) {
332
+ let value;
333
+ try {
334
+ value = JSON.parse(text);
335
+ } catch (error) {
336
+ return;
337
+ }
338
+ return value;
339
+ }
340
+ //#endregion
341
+ //#region lib/types/compare.js
342
+ /** Reads GitHub's patch between two commits through the REST compare endpoint. */
343
+ /** `gh` option that prints a response containing terminal escape sequences; `gh` 2.97 added it. */
344
+ const ALLOW_ESCAPES = "--allow-escape-sequences";
345
+ /** What a `gh` older than 2.97 reports for {@link ALLOW_ESCAPES}, before it sends any request. */
346
+ const UNKNOWN_ALLOW_ESCAPES = `unknown flag: ${ALLOW_ESCAPES}`;
347
+ /**
348
+ * Read the unified patch from the merge base of `base` and `head` to `head`, as
349
+ * GitHub computes the diff of a pull request with that base and head commit.
350
+ * Both ends are commit object names, so the answer never follows a moving
351
+ * branch. The patch keeps terminal escape sequences that file contents hold:
352
+ * `gh` 2.97 and newer refuses to print them without `--allow-escape-sequences`,
353
+ * and an older `gh`, which rejects that option, prints them unchanged, so a
354
+ * rejection of the option alone repeats the read without it.
355
+ * GitHub returns the patch however many files it changes; `read` bounds its size.
356
+ * @param read - runs `gh` with the provider's output limit and failure mapping.
357
+ * @param repository - repository that holds both commits, with an owner and name already checked for inlining.
358
+ * @param base - commit whose merge base with `head` starts the patch.
359
+ * @param head - commit the patch ends at.
360
+ * @param signal - cancellation of the read.
361
+ * @returns the patch with `a/` and `b/` path prefixes, or why GitHub did not provide it.
362
+ * @throws when `base` or `head` is not a full commit object name.
363
+ */
364
+ async function readComparison(read, repository, base, head, signal) {
365
+ for (const commit of [base, head]) if (!isCommit(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`);
366
+ const { host, owner, name } = repository;
367
+ const request = [
368
+ "-H",
369
+ "Accept: application/vnd.github.diff",
370
+ `repos/${owner}/${name}/compare/${base}...${head}`
371
+ ];
372
+ const patch = await read([
373
+ "api",
374
+ "--hostname",
375
+ host,
376
+ ALLOW_ESCAPES,
377
+ ...request
378
+ ], signal);
379
+ if (typeof patch === "string" || !patch.message.startsWith(UNKNOWN_ALLOW_ESCAPES)) return patch;
380
+ return await read([
381
+ "api",
382
+ "--hostname",
383
+ host,
384
+ ...request
385
+ ], signal);
386
+ }
387
+ //#endregion
130
388
  //#region lib/types/graphql.js
131
389
  /** GitHub GraphQL documents and their mapping into provider-neutral results. */
132
390
  const CHECK_FIELDS = `pageInfo { hasNextPage endCursor }
@@ -134,20 +392,44 @@ const CHECK_FIELDS = `pageInfo { hasNextPage endCursor }
134
392
  __typename
135
393
  ... on CheckRun {
136
394
  id databaseId name status conclusion detailsUrl startedAt completedAt
137
- checkSuite { app { id } workflowRun { event workflow { id name } } }
395
+ checkSuite { app { id } workflowRun { databaseId event workflow { id name } } }
138
396
  }
139
397
  ... on StatusContext { context state targetUrl createdAt }
140
398
  }`;
141
- const PULL_REQUEST_FIELDS = `number url title state isDraft updatedAt closedAt
399
+ /** Most nodes GitHub returns in one connection page. */
400
+ const PAGE_SIZE$1 = 100;
401
+ const THREAD_FIELDS = "pageInfo { hasNextPage endCursor } nodes { isResolved }";
402
+ /** Most review requests, reviews per kind, and closing issues one snapshot reads. */
403
+ const OVERVIEW_PAGE = 25;
404
+ const REVIEW_FIELDS = "totalCount nodes { state commit { oid } author { __typename login avatarUrl } }";
405
+ /**
406
+ * Pull request fields of one snapshot.
407
+ * @param threads - review threads the first page holds, at most {@link PAGE_SIZE}.
408
+ * @returns the selection of the snapshot fragment.
409
+ */
410
+ function pullRequestFields(threads) {
411
+ return `id number url title state isDraft updatedAt closedAt
142
412
  author { login }
143
- headRefName headRefOid baseRefName additions deletions mergeable mergeStateStatus reviewDecision
144
- reviewThreads(first: 100) { nodes { isResolved } }
145
- commits(last: 1) { nodes { commit { statusCheckRollup { id state contexts(first: 100) {
413
+ headRefName headRefOid baseRefName baseRefOid additions deletions mergeable mergeStateStatus reviewDecision viewerCanUpdateBranch
414
+ canBeRebased
415
+ reviewThreads(first: ${threads}) { ${THREAD_FIELDS} }
416
+ reviewRequests(first: ${OVERVIEW_PAGE}) { totalCount nodes { asCodeOwner requestedReviewer {
417
+ __typename ... on User { login avatarUrl } ... on Bot { login avatarUrl } ... on Team { combinedSlug avatarUrl }
418
+ } } }
419
+ latestReviews(first: ${OVERVIEW_PAGE}) { ${REVIEW_FIELDS} }
420
+ latestOpinionatedReviews(first: ${OVERVIEW_PAGE}) { ${REVIEW_FIELDS} }
421
+ closingIssuesReferences(first: ${OVERVIEW_PAGE}) { totalCount nodes { number title state url repository { name owner { login } } } }
422
+ commits(last: 1) { nodes { commit { statusCheckRollup { id state contexts(first: ${PAGE_SIZE$1}) {
146
423
  ${CHECK_FIELDS}
147
424
  } } } } }`;
425
+ }
148
426
  /** Continue reading the same commit's rollup even if the pull request head moves. */
149
427
  const CHECKS_QUERY = `query($id: ID!, $cursor: String!) {
150
- node(id: $id) { ... on StatusCheckRollup { contexts(first: 100, after: $cursor) { ${CHECK_FIELDS} } } }
428
+ node(id: $id) { ... on StatusCheckRollup { contexts(first: ${PAGE_SIZE$1}, after: $cursor) { ${CHECK_FIELDS} } } }
429
+ }`;
430
+ /** Continue counting a pull request's review threads; variables `id`, `cursor`, and the integer `first`. */
431
+ const THREADS_QUERY = `query($id: ID!, $cursor: String!, $first: Int!) {
432
+ node(id: $id) { ... on PullRequest { reviewThreads(first: $first, after: $cursor) { ${THREAD_FIELDS} } } }
151
433
  }`;
152
434
  const REPOSITORY_FIELDS = "squashMergeAllowed mergeCommitAllowed rebaseMergeAllowed viewerPermission viewerDefaultMergeMethod";
153
435
  /** Head-branch lookup; variables `owner`, `name`, and `branch` are passed as strings. */
@@ -157,6 +439,10 @@ const HEAD_QUERY = `query($owner: String!, $name: String!, $branch: String!) {
157
439
  pullRequests(headRefName: $branch, states: OPEN, first: 20, orderBy: { field: CREATED_AT, direction: DESC }) { nodes { number isCrossRepository } }
158
440
  }
159
441
  }`;
442
+ /** Head and base commits of one pull request; variables `owner` and `name` are strings, `number` is an integer. */
443
+ const PULL_REQUEST_COMMITS_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
444
+ repository(owner: $owner, name: $name) { pullRequest(number: $number) { headRefOid baseRefOid } }
445
+ }`;
160
446
  const checkRunSchema = z$1.object({
161
447
  __typename: z$1.literal("CheckRun"),
162
448
  id: z$1.string(),
@@ -170,6 +456,7 @@ const checkRunSchema = z$1.object({
170
456
  checkSuite: z$1.object({
171
457
  app: z$1.object({ id: z$1.string() }).nullable(),
172
458
  workflowRun: z$1.object({
459
+ databaseId: z$1.number().int().nonnegative().nullable(),
173
460
  event: z$1.string(),
174
461
  workflow: z$1.object({
175
462
  id: z$1.string(),
@@ -185,14 +472,33 @@ const statusContextSchema = z$1.object({
185
472
  state: z$1.string(),
186
473
  targetUrl: z$1.string().nullable()
187
474
  });
475
+ const pageInfoSchema$1 = z$1.object({
476
+ hasNextPage: z$1.boolean(),
477
+ endCursor: z$1.string().nullable()
478
+ });
188
479
  const checkPageSchema = z$1.object({
189
- pageInfo: z$1.object({
190
- hasNextPage: z$1.boolean(),
191
- endCursor: z$1.string().nullable()
192
- }),
480
+ pageInfo: pageInfoSchema$1,
193
481
  nodes: z$1.array(z$1.unknown())
194
482
  });
195
- const pullRequestSchema = z$1.object({
483
+ const threadPageSchema$1 = z$1.object({
484
+ pageInfo: pageInfoSchema$1,
485
+ nodes: z$1.array(z$1.object({ isResolved: z$1.boolean() }))
486
+ });
487
+ const actorSchema = z$1.object({
488
+ __typename: z$1.string(),
489
+ login: z$1.string(),
490
+ avatarUrl: z$1.string().nullable()
491
+ });
492
+ const reviewsSchema = z$1.object({
493
+ totalCount: z$1.number().int().nonnegative(),
494
+ nodes: z$1.array(z$1.object({
495
+ state: z$1.string(),
496
+ commit: z$1.object({ oid: z$1.string() }).nullable(),
497
+ author: actorSchema.nullable()
498
+ }))
499
+ });
500
+ const pullRequestSchema$1 = z$1.object({
501
+ id: z$1.string().transform((value) => value),
196
502
  url: z$1.string(),
197
503
  title: z$1.string(),
198
504
  state: z$1.enum([
@@ -207,12 +513,42 @@ const pullRequestSchema = z$1.object({
207
513
  headRefName: z$1.string(),
208
514
  headRefOid: z$1.string(),
209
515
  baseRefName: z$1.string(),
516
+ baseRefOid: z$1.unknown().transform((value) => typeof value === "string" && isCommit(value) ? value : void 0),
210
517
  additions: z$1.number().int().nonnegative(),
211
518
  deletions: z$1.number().int().nonnegative(),
212
519
  mergeable: z$1.string(),
213
520
  mergeStateStatus: z$1.string(),
214
521
  reviewDecision: z$1.string().nullable(),
215
- reviewThreads: z$1.object({ nodes: z$1.array(z$1.object({ isResolved: z$1.boolean() })) }),
522
+ viewerCanUpdateBranch: z$1.boolean(),
523
+ canBeRebased: z$1.boolean(),
524
+ reviewThreads: threadPageSchema$1,
525
+ reviewRequests: z$1.object({
526
+ totalCount: z$1.number().int().nonnegative(),
527
+ nodes: z$1.array(z$1.object({
528
+ asCodeOwner: z$1.boolean(),
529
+ requestedReviewer: z$1.object({
530
+ __typename: z$1.string(),
531
+ login: z$1.string().optional(),
532
+ combinedSlug: z$1.string().optional(),
533
+ avatarUrl: z$1.string().nullable().optional()
534
+ }).nullable()
535
+ }))
536
+ }),
537
+ latestReviews: reviewsSchema,
538
+ latestOpinionatedReviews: reviewsSchema,
539
+ closingIssuesReferences: z$1.object({
540
+ totalCount: z$1.number().int().nonnegative(),
541
+ nodes: z$1.array(z$1.object({
542
+ number: z$1.number().int().positive(),
543
+ title: z$1.string(),
544
+ state: z$1.string(),
545
+ url: z$1.string(),
546
+ repository: z$1.object({
547
+ name: z$1.string(),
548
+ owner: z$1.object({ login: z$1.string() })
549
+ })
550
+ }))
551
+ }),
216
552
  commits: z$1.object({ nodes: z$1.array(z$1.object({ commit: z$1.object({ statusCheckRollup: z$1.object({
217
553
  id: z$1.string().transform((value) => value),
218
554
  state: z$1.string(),
@@ -249,18 +585,36 @@ const headSchema = z$1.object({ data: z$1.object({ repository: z$1.object({
249
585
  isCrossRepository: z$1.boolean()
250
586
  })) })
251
587
  }).nullable() }) });
588
+ const pullRequestCommitsSchema = z$1.object({ data: z$1.object({ repository: z$1.object({ pullRequest: z$1.object({
589
+ headRefOid: z$1.string().refine(isCommit),
590
+ baseRefOid: z$1.string().refine(isCommit)
591
+ }) }) }) });
252
592
  /** GitHub merge states in which the merge button works: mergeable, with passing or non-required failing checks. */
253
593
  const MERGEABLE_NOW = new Set([
254
594
  "CLEAN",
255
595
  "HAS_HOOKS",
256
596
  "UNSTABLE"
257
597
  ]);
258
- /** Repository permissions that may merge. */
598
+ /** Repository permissions that may merge and rerun workflow jobs. */
259
599
  const MERGERS = new Set([
260
600
  "ADMIN",
261
601
  "MAINTAIN",
262
602
  "WRITE"
263
603
  ]);
604
+ /** Repository permissions that may request reviews. */
605
+ const TRIAGERS = new Set([
606
+ "ADMIN",
607
+ "MAINTAIN",
608
+ "WRITE",
609
+ "TRIAGE"
610
+ ]);
611
+ /** Outcome of a submitted review by GitHub state; a pending review is not submitted. */
612
+ const VERDICTS = {
613
+ APPROVED: "approved",
614
+ CHANGES_REQUESTED: "changes-requested",
615
+ COMMENTED: "commented",
616
+ DISMISSED: "dismissed"
617
+ };
264
618
  /** Merge methods in menu order, with the repository setting that allows each and GitHub's name for it. */
265
619
  const METHODS = [
266
620
  {
@@ -283,10 +637,11 @@ const METHODS = [
283
637
  * Build one query that reads every change request in `refs`, grouping them by
284
638
  * repository. Owners, names, and numbers are validated before they are inlined.
285
639
  * @param refs - change requests on one host.
640
+ * @param maxReviewThreads - positive integer bound on the review threads counted per change request.
286
641
  * @returns the document and its alias targets.
287
642
  * @throws when an owner, name, or number cannot be inlined safely.
288
643
  */
289
- function snapshotQuery(refs) {
644
+ function snapshotQuery(refs, maxReviewThreads) {
290
645
  const repositories = /* @__PURE__ */ new Map();
291
646
  for (const ref of refs) {
292
647
  const { owner, name } = checkedRepository(ref);
@@ -313,22 +668,26 @@ function snapshotQuery(refs) {
313
668
  fields.push(`r${r}: repository(owner: ${owner}, name: ${JSON.stringify(repository.name)}) { ${REPOSITORY_FIELDS} ${pulls.join(" ")} }`);
314
669
  }
315
670
  return {
316
- document: `query { ${fields.join(" ")} }\nfragment ChangeRequestFields on PullRequest { ${PULL_REQUEST_FIELDS} }`,
317
- targets
671
+ document: `query { ${fields.join(" ")} }
672
+ fragment ChangeRequestFields on PullRequest { ${pullRequestFields(Math.min(PAGE_SIZE$1, maxReviewThreads))} }`,
673
+ targets,
674
+ maxReviewThreads
318
675
  };
319
676
  }
320
677
  /**
321
678
  * Map a snapshot response, including GitHub's partial-error form, into one
322
679
  * result per alias target. Path-scoped errors apply to their repository or
323
680
  * pull request; errors without a path apply to every unresolved target. A
324
- * repository without readable merge settings offers no merge. Polling returns
681
+ * repository without readable merge settings offers no merge. Review threads
682
+ * are counted across pages up to `query.maxReviewThreads`. Polling returns
325
683
  * the first check page; an explicit detail read can complete its pagination.
684
+ * A continuation page that fails or does not advance fails its target.
326
685
  * @param body - parsed JSON printed by `gh api graphql`.
327
686
  * @param query - the query that produced the response.
328
- * @param readChecks - optional detail reader for the same commit; omission returns the first page with its truncation flag.
329
- * @returns a snapshot with its check truncation flag, or a failure, for every target.
687
+ * @param pages - continuation reads of review threads and, for a detail read, of checks on the same commit.
688
+ * @returns a snapshot with its check and thread truncation flags, or a failure, for every target.
330
689
  */
331
- async function mapSnapshotResponse(body, query, readChecks) {
690
+ async function mapSnapshotResponse(body, query, pages) {
332
691
  const results = /* @__PURE__ */ new Map();
333
692
  const parsed = responseSchema.safeParse(body);
334
693
  const repositories = new Set([...query.targets.keys()].map((alias) => alias.split(".")[0]));
@@ -345,32 +704,14 @@ async function mapSnapshotResponse(body, query, readChecks) {
345
704
  const errors = parsed.data.errors ?? [];
346
705
  const error = errors.find((entry) => entry.path?.[0] === repositoryAlias && (entry.path.length === 1 || entry.path[1] === pullAlias)) ?? errors.find((entry) => entry.path === void 0 || !repositories.has(String(entry.path[0])));
347
706
  const raw = parsed.data.data?.[repositoryAlias]?.[pullAlias];
348
- const node = pullRequestSchema.safeParse(raw);
707
+ const node = pullRequestSchema$1.safeParse(raw);
349
708
  const settings = repositorySchema.safeParse(parsed.data.data?.[repositoryAlias]);
350
709
  if (node.success) {
710
+ const { id, reviewThreads } = node.data;
351
711
  const rollup = node.data.commits.nodes[0]?.commit.statusCheckRollup;
352
- if (rollup !== void 0 && rollup !== null) {
353
- const cursors = /* @__PURE__ */ new Set();
354
- while (readChecks !== void 0 && rollup.contexts.pageInfo.hasNextPage) {
355
- const cursor = rollup.contexts.pageInfo.endCursor;
356
- if (cursor === null || cursors.has(cursor)) {
357
- results.set(key, {
358
- code: "unavailable",
359
- message: "GitHub check pagination did not advance"
360
- });
361
- break;
362
- }
363
- cursors.add(cursor);
364
- const next = await readChecks(rollup.id, cursor);
365
- if (!next.ok) {
366
- results.set(key, next.failure);
367
- break;
368
- }
369
- rollup.contexts.nodes.push(...next.page.nodes);
370
- rollup.contexts.pageInfo = next.page.pageInfo;
371
- }
372
- }
373
- if (!results.has(key)) results.set(key, toSnapshot(ref, node.data, settings.success ? settings.data : void 0));
712
+ const { checks } = pages;
713
+ const failure = await readPages(reviewThreads, query.maxReviewThreads, "review thread", async (cursor, first) => await pages.threads(id, cursor, first)) ?? (rollup === void 0 || rollup === null || checks === void 0 ? void 0 : await readPages(rollup.contexts, Number.POSITIVE_INFINITY, "check", async (cursor) => await checks(rollup.id, cursor)));
714
+ results.set(key, failure ?? toSnapshot(ref, node.data, settings.success ? settings.data : void 0));
374
715
  } else if (error !== void 0) results.set(key, {
375
716
  code: error.type === "NOT_FOUND" ? "not-found" : "unavailable",
376
717
  message: error.message
@@ -387,28 +728,83 @@ async function mapSnapshotResponse(body, query, readChecks) {
387
728
  return results;
388
729
  }
389
730
  /**
731
+ * Append the following pages of a connection until it ends or holds `limit` nodes.
732
+ * @param connection - first page, extended in place.
733
+ * @param limit - most nodes to hold.
734
+ * @param label - what the connection lists, for failure messages.
735
+ * @param read - reads the page after `cursor`, holding at most `first` nodes.
736
+ * @returns a failure that prevents publishing the partial connection, or undefined once it ended or is full.
737
+ */
738
+ async function readPages(connection, limit, label, read) {
739
+ const cursors = /* @__PURE__ */ new Set();
740
+ while (connection.pageInfo.hasNextPage && connection.nodes.length < limit) {
741
+ const cursor = connection.pageInfo.endCursor;
742
+ if (cursor === null || cursors.has(cursor)) return {
743
+ code: "unavailable",
744
+ message: `GitHub ${label} pagination did not advance`
745
+ };
746
+ cursors.add(cursor);
747
+ const next = await read(cursor, Math.min(PAGE_SIZE$1, limit - connection.nodes.length));
748
+ if (!next.ok) return next.failure;
749
+ connection.nodes.push(...next.page.nodes);
750
+ connection.pageInfo = next.page.pageInfo;
751
+ }
752
+ }
753
+ /**
390
754
  * Validate a continuation response before adding its checks to the snapshot.
391
755
  * @param body - parsed GraphQL response for a rollup node.
392
756
  * @returns the complete page or a failure; partial-error pages are not accepted.
393
757
  */
394
758
  function mapCheckPageResponse(body) {
759
+ return mapPageResponse(body, z$1.object({ contexts: checkPageSchema }).transform((node) => node.contexts), "check");
760
+ }
761
+ /**
762
+ * Validate a continuation response of {@link THREADS_QUERY} before counting its review threads.
763
+ * @param body - parsed GraphQL response for a pull request node.
764
+ * @returns the complete page or a failure; partial-error pages are not accepted.
765
+ */
766
+ function mapThreadPageResponse(body) {
767
+ return mapPageResponse(body, z$1.object({ reviewThreads: threadPageSchema$1 }).transform((node) => node.reviewThreads), "review thread");
768
+ }
769
+ /**
770
+ * Validate one continuation response of a `node(id:)` query.
771
+ * @param body - parsed GraphQL response.
772
+ * @param page - schema that maps the node to its connection page.
773
+ * @param label - what the connection lists, for failure messages.
774
+ * @returns the page, or a failure for an error, a missing node, or unexpected fields.
775
+ */
776
+ function mapPageResponse(body, page, label) {
395
777
  const parsed = z$1.object({
396
- data: z$1.object({ node: z$1.object({ contexts: checkPageSchema }).nullable() }).nullable().optional(),
778
+ data: z$1.object({ node: page.nullable() }).nullable().optional(),
397
779
  errors: z$1.array(z$1.object({ message: z$1.string() })).optional()
398
780
  }).safeParse(body);
399
781
  if (parsed.success && !parsed.data.errors?.length && parsed.data.data?.node != null) return {
400
782
  ok: true,
401
- page: parsed.data.data.node.contexts
783
+ page: parsed.data.data.node
402
784
  };
403
785
  return {
404
786
  ok: false,
405
787
  failure: {
406
788
  code: "unavailable",
407
- message: parsed.success ? parsed.data.errors?.[0]?.message ?? "GitHub check page is unavailable" : "unexpected GitHub check page"
789
+ message: parsed.success ? parsed.data.errors?.[0]?.message ?? `GitHub ${label} page is unavailable` : `unexpected GitHub ${label} page`
408
790
  }
409
791
  };
410
792
  }
411
793
  /**
794
+ * Map a read of {@link PULL_REQUEST_COMMITS_QUERY}.
795
+ * @param body - parsed JSON printed by `gh api graphql`.
796
+ * @returns both commits, or undefined when the response does not name them as full commit object names.
797
+ */
798
+ function mapPullRequestCommitsResponse(body) {
799
+ const parsed = pullRequestCommitsSchema.safeParse(body);
800
+ if (!parsed.success) return void 0;
801
+ const { headRefOid, baseRefOid } = parsed.data.data.repository.pullRequest;
802
+ return {
803
+ head: headRefOid,
804
+ base: baseRefOid
805
+ };
806
+ }
807
+ /**
412
808
  * Map a head-branch lookup of {@link HEAD_QUERY}, which selects open pull requests, into change requests.
413
809
  * @param body - parsed JSON printed by `gh api graphql`.
414
810
  * @param repository - repository that was queried.
@@ -455,7 +851,8 @@ function toSnapshot(ref, node, settings) {
455
851
  url: run.data.detailsUrl,
456
852
  workflow: run.data.checkSuite?.workflowRun?.workflow.name ?? null,
457
853
  startedAt: run.data.startedAt,
458
- completedAt: run.data.completedAt
854
+ completedAt: run.data.completedAt,
855
+ rerun: workflow?.databaseId == null ? null : actionsRun(workflow.databaseId)
459
856
  });
460
857
  continue;
461
858
  }
@@ -466,7 +863,8 @@ function toSnapshot(ref, node, settings) {
466
863
  url: status.data.targetUrl,
467
864
  workflow: null,
468
865
  startedAt: null,
469
- completedAt: null
866
+ completedAt: null,
867
+ rerun: null
470
868
  });
471
869
  else if (typeof context === "object" && context !== null && "__typename" in context && (context.__typename === "CheckRun" || context.__typename === "StatusContext")) return {
472
870
  code: "unavailable",
@@ -476,6 +874,8 @@ function toSnapshot(ref, node, settings) {
476
874
  }
477
875
  const checks = [...latest.values()].map((value) => value.check);
478
876
  const summary = rollup?.contexts.pageInfo.hasNextPage || unknownContext || checks.length === 0 ? checksRollup(rollup?.state) : checks.some((check) => check.state === "failure" || check.state === "cancelled") ? "failure" : checks.some((check) => check.state === "pending") ? "pending" : "success";
877
+ const permission = settings?.viewerPermission ?? "";
878
+ const open = node.state === "OPEN";
479
879
  return {
480
880
  ref,
481
881
  url: node.url,
@@ -486,20 +886,100 @@ function toSnapshot(ref, node, settings) {
486
886
  headBranch: node.headRefName,
487
887
  headSha: node.headRefOid,
488
888
  baseBranch: node.baseRefName,
889
+ ...node.baseRefOid === void 0 ? {} : { baseSha: node.baseRefOid },
489
890
  additions: node.additions,
490
891
  deletions: node.deletions,
491
892
  mergeability: mergeability(node.mergeable),
492
893
  mergeReady: settings !== void 0 && MERGERS.has(settings.viewerPermission ?? "") && node.state === "OPEN" && !node.isDraft && MERGEABLE_NOW.has(node.mergeStateStatus),
493
894
  mergeMethods: settings === void 0 ? [] : mergeMethods(settings),
895
+ branchUpdates: !open || !node.viewerCanUpdateBranch || node.mergeable === "CONFLICTING" ? [] : node.canBeRebased ? ["merge", "rebase"] : ["merge"],
494
896
  reviewDecision: reviewDecision(node.reviewDecision),
897
+ reviewers: reviewersOf(node),
898
+ reviewersTruncated: [
899
+ node.reviewRequests,
900
+ node.latestReviews,
901
+ node.latestOpinionatedReviews
902
+ ].some((connection) => connection.totalCount > connection.nodes.length),
903
+ canRequestReviews: open && TRIAGERS.has(permission),
495
904
  checks,
496
905
  checksRollup: summary,
497
906
  checksTruncated: rollup?.contexts.pageInfo.hasNextPage ?? false,
907
+ canRerunChecks: MERGERS.has(permission),
498
908
  unresolvedThreads: node.reviewThreads.nodes.filter((thread) => !thread.isResolved).length,
909
+ threadsTruncated: node.reviewThreads.pageInfo.hasNextPage,
910
+ closingIssues: node.closingIssuesReferences.nodes.map((issue) => ({
911
+ repository: {
912
+ forge: ref.repository.forge,
913
+ host: ref.repository.host,
914
+ owner: issue.repository.owner.login,
915
+ name: issue.repository.name
916
+ },
917
+ number: issue.number,
918
+ title: issue.title,
919
+ state: issue.state === "OPEN" ? "open" : "closed",
920
+ url: issue.url
921
+ })),
922
+ closingIssuesTruncated: node.closingIssuesReferences.totalCount > node.closingIssuesReferences.nodes.length,
499
923
  updatedAt: node.updatedAt,
500
924
  closedAt: node.closedAt
501
925
  };
502
926
  }
927
+ /**
928
+ * The requested reviewers in host order, then the other accounts that submitted a review, each with their latest
929
+ * outcome. An approval or change request outlasts later comments, as GitHub's reviewer list shows it; the author and
930
+ * accounts GitHub does not name are left out.
931
+ */
932
+ function reviewersOf(node) {
933
+ const reviewers = /* @__PURE__ */ new Map();
934
+ const keyOf = (kind, login) => `${kind}:${login.toLowerCase()}`;
935
+ for (const request of node.reviewRequests.nodes) {
936
+ const reviewer = request.requestedReviewer;
937
+ const kind = reviewer?.__typename === "User" ? "user" : reviewer?.__typename === "Bot" ? "bot" : reviewer?.__typename === "Team" ? "team" : void 0;
938
+ const login = kind === "team" ? reviewer?.combinedSlug : reviewer?.login;
939
+ if (kind === void 0 || login === void 0) continue;
940
+ reviewers.set(keyOf(kind, login), {
941
+ kind,
942
+ login,
943
+ avatarUrl: reviewer?.avatarUrl ?? null,
944
+ requested: true,
945
+ codeOwner: request.asCodeOwner,
946
+ verdict: null,
947
+ reviewedSha: null
948
+ });
949
+ }
950
+ const author = node.author?.login.toLowerCase();
951
+ for (const review of [...node.latestReviews.nodes, ...node.latestOpinionatedReviews.nodes]) {
952
+ const verdict = VERDICTS[review.state];
953
+ const account = review.author;
954
+ if (verdict === void 0 || account === null || account.login.toLowerCase() === author) continue;
955
+ const kind = account.__typename === "Bot" ? "bot" : "user";
956
+ const key = keyOf(kind, account.login);
957
+ const known = reviewers.get(key);
958
+ reviewers.set(key, {
959
+ kind,
960
+ login: account.login,
961
+ avatarUrl: known?.avatarUrl ?? account.avatarUrl,
962
+ requested: known?.requested ?? false,
963
+ codeOwner: known?.codeOwner ?? false,
964
+ verdict,
965
+ reviewedSha: review.commit?.oid ?? null
966
+ });
967
+ }
968
+ return [...reviewers.values()];
969
+ }
970
+ /** The rerun identity of a GitHub Actions job: the database id of its workflow run, which reruns its failed jobs. */
971
+ function actionsRun(run) {
972
+ return `actions:${run}`;
973
+ }
974
+ /**
975
+ * Read the workflow run database id from a check's rerun identity.
976
+ * @param id - identity a snapshot of this provider named.
977
+ * @returns the workflow run id, or undefined for an identity this provider did not build.
978
+ */
979
+ function actionsRunOf(id) {
980
+ const match = /^actions:(\d{1,15})$/.exec(id);
981
+ return match === null ? void 0 : Number(match[1]);
982
+ }
503
983
  /** The methods the repository allows, the viewer's default first. */
504
984
  function mergeMethods(settings) {
505
985
  const allowed = METHODS.filter((entry) => settings[entry.allowed]);
@@ -568,7 +1048,7 @@ const pull = z$1.object({
568
1048
  state: z$1.string()
569
1049
  });
570
1050
  const receipt = z$1.object({ html_url: z$1.url() });
571
- const EVENTS = {
1051
+ const EVENTS$1 = {
572
1052
  comment: "COMMENT",
573
1053
  approve: "APPROVE",
574
1054
  "request-changes": "REQUEST_CHANGES"
@@ -631,7 +1111,7 @@ async function submitGitHubReview(gh, ref, request, signal) {
631
1111
  ...inline(request.comment)
632
1112
  } : {
633
1113
  commit_id: request.headSha,
634
- event: EVENTS[request.event],
1114
+ event: EVENTS$1[request.event],
635
1115
  body: request.body,
636
1116
  comments: request.comments.map(inline)
637
1117
  };
@@ -664,22 +1144,1028 @@ async function submitGitHubReview(gh, ref, request, signal) {
664
1144
  }
665
1145
  }
666
1146
  //#endregion
1147
+ //#region lib/types/pull-request-node.js
1148
+ /** The node id of a pull request that a GraphQL mutation names, read together with the head the write must still find. */
1149
+ /** Node id and head commit of one pull request; variables `owner` and `name` are strings, `number` is an integer. */
1150
+ const PULL_REQUEST_NODE_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
1151
+ repository(owner: $owner, name: $name) { pullRequest(number: $number) { id headRefOid } }
1152
+ }`;
1153
+ const nodeSchema = z$1.object({ data: z$1.object({ repository: z$1.object({ pullRequest: z$1.object({
1154
+ id: z$1.string(),
1155
+ headRefOid: z$1.string()
1156
+ }).nullable() }).nullable() }) });
1157
+ /**
1158
+ * Read a pull request's node id before a write, refusing once its head is not `headSha`.
1159
+ * @param read - runs one GraphQL query.
1160
+ * @param ref - pull request address.
1161
+ * @param headSha - head commit the write must still find, or null for a write that does not depend on the head.
1162
+ * @param signal - cancellation of the read.
1163
+ * @returns the node id, `stale` when the head moved, or why the write must not proceed.
1164
+ */
1165
+ async function pullRequestNode(read, ref, headSha, signal) {
1166
+ const { host, owner, name } = checkedRepository(ref);
1167
+ const node = await read([
1168
+ "api",
1169
+ "graphql",
1170
+ "--hostname",
1171
+ host,
1172
+ "-f",
1173
+ `query=${PULL_REQUEST_NODE_QUERY}`,
1174
+ "-f",
1175
+ `owner=${owner}`,
1176
+ "-f",
1177
+ `name=${name}`,
1178
+ "-F",
1179
+ `number=${ref.number}`
1180
+ ], signal);
1181
+ if (!node.ok) return {
1182
+ code: node.failure.code === "unauthenticated" ? "unauthenticated" : "failed",
1183
+ message: node.failure.message
1184
+ };
1185
+ const parsed = nodeSchema.safeParse(node.body);
1186
+ if (!parsed.success) return {
1187
+ code: "failed",
1188
+ message: "unexpected GitHub response to the pull request read"
1189
+ };
1190
+ const pull = parsed.data.data.repository?.pullRequest;
1191
+ if (pull == null) return {
1192
+ code: "failed",
1193
+ message: `pull request ${ref.number} was not found`
1194
+ };
1195
+ if (headSha !== null && pull.headRefOid.toLowerCase() !== headSha.toLowerCase()) return {
1196
+ code: "stale",
1197
+ message: `the pull request head moved from ${headSha} to ${pull.headRefOid}`
1198
+ };
1199
+ return pull.id;
1200
+ }
1201
+ //#endregion
1202
+ //#region lib/types/viewed.js
1203
+ /** The signed-in user's viewed marks on pull request files through GraphQL, pinned to one head commit. */
1204
+ /** Files GitHub returns per GraphQL page, its connection maximum. */
1205
+ const PAGE = 100;
1206
+ /** One page of a pull request's files with the viewer's marks and its head; `cursor` continues after the previous page. */
1207
+ const VIEWED_QUERY = `query($owner: String!, $name: String!, $number: Int!, $first: Int!, $cursor: String) {
1208
+ repository(owner: $owner, name: $name) {
1209
+ pullRequest(number: $number) {
1210
+ headRefOid
1211
+ files(first: $first, after: $cursor) { totalCount pageInfo { hasNextPage endCursor } nodes { path viewerViewedState } }
1212
+ }
1213
+ }
1214
+ }`;
1215
+ /** Mark one file viewed; variables `id` (pull request node id) and `path`, sent on standard input. */
1216
+ const MARK_VIEWED_MUTATION = `mutation($id: ID!, $path: String!) {
1217
+ markFileAsViewed(input: { pullRequestId: $id, path: $path }) { clientMutationId }
1218
+ }`;
1219
+ /** Clear one file's viewed mark; variables `id` (pull request node id) and `path`, sent on standard input. */
1220
+ const UNMARK_VIEWED_MUTATION = `mutation($id: ID!, $path: String!) {
1221
+ unmarkFileAsViewed(input: { pullRequestId: $id, path: $path }) { clientMutationId }
1222
+ }`;
1223
+ const STATES = new Map([
1224
+ ["VIEWED", "viewed"],
1225
+ ["UNVIEWED", "unviewed"],
1226
+ ["DISMISSED", "dismissed"]
1227
+ ]);
1228
+ const pageSchema = z$1.object({ data: z$1.object({ repository: z$1.object({ pullRequest: z$1.object({
1229
+ headRefOid: z$1.string(),
1230
+ files: z$1.object({
1231
+ totalCount: z$1.number().int().nonnegative(),
1232
+ pageInfo: z$1.object({
1233
+ hasNextPage: z$1.boolean(),
1234
+ endCursor: z$1.string().nullable()
1235
+ }),
1236
+ nodes: z$1.array(z$1.object({
1237
+ path: z$1.string(),
1238
+ viewerViewedState: z$1.string()
1239
+ }))
1240
+ }).nullable()
1241
+ }).nullable() }).nullable() }) });
1242
+ /**
1243
+ * Read the viewer's marks on a pull request's files, at most `limit`, reading pages until the limit or the last file.
1244
+ * Every page must name `headSha` as the head, so the marks never mix two pushes, and a cursor no earlier page returned,
1245
+ * so the listing ends. A state GitHub adds later reads as `unviewed`.
1246
+ * @param read - runs one GraphQL request.
1247
+ * @param ref - pull request address.
1248
+ * @param headSha - head commit the marks must be read at.
1249
+ * @param limit - most files listed.
1250
+ * @param signal - cancellation of every page.
1251
+ * @returns the marks at `headSha`, `stale` once the head is another commit, or why GitHub did not list them.
1252
+ * @throws when `headSha` is not a full commit object name.
1253
+ */
1254
+ async function readViewed(read, ref, headSha, limit, signal) {
1255
+ const { host, owner, name } = checkedRepository(ref);
1256
+ if (!isCommit(headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(headSha)}`);
1257
+ const files = /* @__PURE__ */ new Map();
1258
+ let listed = 0;
1259
+ const cursors = /* @__PURE__ */ new Set();
1260
+ let cursor = null;
1261
+ for (;;) {
1262
+ const body = await read([
1263
+ "api",
1264
+ "graphql",
1265
+ "--hostname",
1266
+ host,
1267
+ "-f",
1268
+ `query=${VIEWED_QUERY}`,
1269
+ "-f",
1270
+ `owner=${owner}`,
1271
+ "-f",
1272
+ `name=${name}`,
1273
+ "-F",
1274
+ `number=${ref.number}`,
1275
+ "-F",
1276
+ `first=${Math.min(PAGE, limit - listed)}`,
1277
+ ...cursor === null ? [] : ["-f", `cursor=${cursor}`]
1278
+ ], signal);
1279
+ if (!body.ok) return body.failure;
1280
+ const parsed = pageSchema.safeParse(body.body);
1281
+ if (!parsed.success) return {
1282
+ code: "unavailable",
1283
+ message: "unexpected GitHub response to the viewed file read"
1284
+ };
1285
+ const pull = parsed.data.data.repository?.pullRequest;
1286
+ if (pull == null) return {
1287
+ code: "not-found",
1288
+ message: `pull request ${ref.number} was not found`
1289
+ };
1290
+ if (pull.headRefOid.toLowerCase() !== headSha.toLowerCase()) return {
1291
+ code: "stale",
1292
+ message: `the pull request head moved from ${headSha} to ${pull.headRefOid}`
1293
+ };
1294
+ if (pull.files === null) return {
1295
+ code: "unavailable",
1296
+ message: "GitHub did not list the pull request files"
1297
+ };
1298
+ const { totalCount, pageInfo: { hasNextPage, endCursor }, nodes } = pull.files;
1299
+ for (const node of nodes) files.set(node.path, STATES.get(node.viewerViewedState) ?? "unviewed");
1300
+ listed += nodes.length;
1301
+ if (!hasNextPage || listed >= limit) return {
1302
+ headSha: pull.headRefOid,
1303
+ files: Object.fromEntries(files),
1304
+ truncated: totalCount > listed
1305
+ };
1306
+ if (endCursor === null || cursors.has(endCursor)) return {
1307
+ code: "unavailable",
1308
+ message: "GitHub file pagination did not advance"
1309
+ };
1310
+ cursors.add(endCursor);
1311
+ cursor = endCursor;
1312
+ }
1313
+ }
1314
+ /**
1315
+ * Set or clear the viewer's mark on one file. GitHub's mutations take no head commit, so the pull request head is read
1316
+ * first and the write is refused once it is another commit; a push between that read and the write leaves the mark on
1317
+ * the file as the new head has it.
1318
+ * @param read - runs one GraphQL query.
1319
+ * @param write - runs one GraphQL mutation.
1320
+ * @param ref - pull request address.
1321
+ * @param request - the file, its mark, and the head commit the user saw.
1322
+ * @param signal - cancellation of both requests.
1323
+ * @returns undefined once GitHub saved the mark, `stale` when the head moved, or why GitHub refused.
1324
+ * @throws when `request.headSha` is not a full commit object name.
1325
+ */
1326
+ async function writeViewed(read, write, ref, request, signal) {
1327
+ if (!isCommit(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`);
1328
+ const id = await pullRequestNode(read, ref, request.headSha, signal);
1329
+ if (typeof id !== "string") return id;
1330
+ const variables = {
1331
+ id,
1332
+ path: request.path
1333
+ };
1334
+ return await write(ref.repository.host, request.viewed ? {
1335
+ query: MARK_VIEWED_MUTATION,
1336
+ field: "markFileAsViewed",
1337
+ variables
1338
+ } : {
1339
+ query: UNMARK_VIEWED_MUTATION,
1340
+ field: "unmarkFileAsViewed",
1341
+ variables
1342
+ }, signal);
1343
+ }
1344
+ //#endregion
1345
+ //#region lib/types/overview.js
1346
+ /** GitHub writes and reads of the change request overview: review requests, reviewer candidates, and branch updates. */
1347
+ /**
1348
+ * Add review requests from users and teams by node id; variable `input` is a `RequestReviewsInput`. Every supported
1349
+ * host has it, while GitHub Enterprise Server 3.19 and 3.20 lack `requestReviewsByLogin`.
1350
+ */
1351
+ const REQUEST_REVIEWS_MUTATION = `mutation($input: RequestReviewsInput!) {
1352
+ requestReviews(input: $input) { clientMutationId }
1353
+ }`;
1354
+ /** Add review requests from bots by login, which only this mutation accepts; variable `input` is a `RequestReviewsByLoginInput`. */
1355
+ const REQUEST_BOT_REVIEWS_MUTATION = `mutation($input: RequestReviewsByLoginInput!) {
1356
+ requestReviewsByLogin(input: $input) { clientMutationId }
1357
+ }`;
1358
+ /**
1359
+ * Split a team reviewer named `organization/slug`.
1360
+ * @param login - the team's name.
1361
+ * @returns the organization and the slug, or undefined for another name.
1362
+ */
1363
+ function teamOf(login) {
1364
+ const [organization, slug, ...rest] = login.split("/");
1365
+ return organization === void 0 || organization === "" || slug === void 0 || slug === "" || rest.length > 0 ? void 0 : [organization, slug];
1366
+ }
1367
+ /** Merge or rebase the base branch into the head branch; variable `input` is an `UpdatePullRequestBranchInput`. */
1368
+ const UPDATE_BRANCH_MUTATION = `mutation($input: UpdatePullRequestBranchInput!) {
1369
+ updatePullRequestBranch(input: $input) { clientMutationId }
1370
+ }`;
1371
+ /** Most accounts one candidate listing returns. */
1372
+ const CANDIDATES = 20;
1373
+ /** Accounts that can review and GitHub's suggestions; variables `owner`, `name`, and `search` are strings, `number` is an integer. */
1374
+ const CANDIDATES_QUERY = `query($owner: String!, $name: String!, $number: Int!, $search: String!) {
1375
+ repository(owner: $owner, name: $name) {
1376
+ assignableUsers(first: ${CANDIDATES}, query: $search) { nodes { login name avatarUrl } }
1377
+ pullRequest(number: $number) { author { login } suggestedReviewers { reviewer { login name avatarUrl } } }
1378
+ }
1379
+ }`;
1380
+ const account = z$1.object({
1381
+ login: z$1.string(),
1382
+ name: z$1.string().nullable(),
1383
+ avatarUrl: z$1.string().nullable()
1384
+ });
1385
+ const candidatesSchema = z$1.object({ data: z$1.object({ repository: z$1.object({
1386
+ assignableUsers: z$1.object({ nodes: z$1.array(account) }),
1387
+ pullRequest: z$1.object({
1388
+ author: z$1.object({ login: z$1.string() }).nullable(),
1389
+ suggestedReviewers: z$1.array(z$1.object({ reviewer: account }))
1390
+ }).nullable()
1391
+ }).nullable() }) });
1392
+ /**
1393
+ * Request reviews, adding to the requests GitHub holds. Users and teams are resolved to node ids in one query and asked
1394
+ * with `requestReviews`; bots, named with or without GitHub's `[bot]` suffix, are asked with `requestReviewsByLogin`
1395
+ * afterwards, which hosts without it refuse. A team is named `organization/slug`.
1396
+ * @param read - runs one GraphQL query.
1397
+ * @param write - runs one GraphQL mutation.
1398
+ * @param ref - pull request address.
1399
+ * @param request - the reviewers to ask.
1400
+ * @param signal - cancellation of every request.
1401
+ * @returns undefined once GitHub accepted every request, or why it refused; a refused bot request follows an accepted
1402
+ * request of the users and teams.
1403
+ */
1404
+ async function requestGitHubReviews(read, write, ref, request, signal) {
1405
+ if (request.reviewers.length === 0) return {
1406
+ code: "failed",
1407
+ message: "No reviewer was named"
1408
+ };
1409
+ const logins = (kind) => request.reviewers.filter((reviewer) => reviewer.kind === kind).map((reviewer) => reviewer.login);
1410
+ const users = logins("user");
1411
+ const teams = [];
1412
+ for (const login of logins("team")) {
1413
+ const team = teamOf(login);
1414
+ if (team === void 0) return {
1415
+ code: "failed",
1416
+ message: `Team ${JSON.stringify(login)} is not named organization/slug`
1417
+ };
1418
+ teams.push(team);
1419
+ }
1420
+ const bots = logins("bot").map((login) => login.endsWith("[bot]") ? login : `${login}[bot]`);
1421
+ const id = await pullRequestNode(read, ref, null, signal);
1422
+ if (typeof id !== "string") return id;
1423
+ const { host } = ref.repository;
1424
+ if (users.length > 0 || teams.length > 0) {
1425
+ const ids = await reviewerIds(read, host, users, teams, signal);
1426
+ if ("code" in ids) return ids;
1427
+ const failure = await write(host, {
1428
+ query: REQUEST_REVIEWS_MUTATION,
1429
+ field: "requestReviews",
1430
+ variables: { input: {
1431
+ pullRequestId: id,
1432
+ union: true,
1433
+ ...ids.users.length > 0 ? { userIds: ids.users } : {},
1434
+ ...ids.teams.length > 0 ? { teamIds: ids.teams } : {}
1435
+ } }
1436
+ }, signal);
1437
+ if (failure !== void 0) return failure;
1438
+ }
1439
+ if (bots.length === 0) return void 0;
1440
+ return await write(host, {
1441
+ query: REQUEST_BOT_REVIEWS_MUTATION,
1442
+ field: "requestReviewsByLogin",
1443
+ variables: { input: {
1444
+ pullRequestId: id,
1445
+ union: true,
1446
+ botLogins: bots
1447
+ } }
1448
+ }, signal);
1449
+ }
1450
+ const idNode = z$1.object({ id: z$1.string() });
1451
+ /**
1452
+ * Resolve user logins and team slugs to node ids with one aliased query whose names are variables.
1453
+ * @returns the ids in request order, or why GitHub did not resolve them, as for an unknown login.
1454
+ */
1455
+ async function reviewerIds(read, host, users, teams, signal) {
1456
+ const declarations = [...users.map((_, index) => `$u${index}: String!`), ...teams.flatMap((_, index) => [`$o${index}: String!`, `$t${index}: String!`])];
1457
+ const fields = [...users.map((_, index) => `u${index}: user(login: $u${index}) { id }`), ...teams.map((_, index) => `t${index}: organization(login: $o${index}) { team(slug: $t${index}) { id } }`)];
1458
+ const body = await read([
1459
+ "api",
1460
+ "graphql",
1461
+ "--hostname",
1462
+ host,
1463
+ "-f",
1464
+ `query=${`query(${declarations.join(", ")}) { ${fields.join(" ")} }`}`,
1465
+ ...users.flatMap((login, index) => ["-f", `u${index}=${login}`]),
1466
+ ...teams.flatMap(([organization, slug], index) => [
1467
+ "-f",
1468
+ `o${index}=${organization}`,
1469
+ "-f",
1470
+ `t${index}=${slug}`
1471
+ ])
1472
+ ], signal);
1473
+ if (!body.ok) return {
1474
+ code: body.failure.code === "unauthenticated" ? "unauthenticated" : "failed",
1475
+ message: body.failure.message
1476
+ };
1477
+ const parsed = z$1.object({ data: z$1.record(z$1.string(), z$1.unknown()) }).safeParse(body.body);
1478
+ if (!parsed.success) return {
1479
+ code: "failed",
1480
+ message: "unexpected GitHub response to the reviewer lookup"
1481
+ };
1482
+ const { data } = parsed.data;
1483
+ const userIds = [];
1484
+ for (const [index, login] of users.entries()) {
1485
+ const user = idNode.safeParse(data[`u${index}`]);
1486
+ if (!user.success) return {
1487
+ code: "failed",
1488
+ message: `GitHub has no user ${login}`
1489
+ };
1490
+ userIds.push(user.data.id);
1491
+ }
1492
+ const teamIds = [];
1493
+ for (const [index, [organization, slug]] of teams.entries()) {
1494
+ const team = z$1.object({ team: idNode }).safeParse(data[`t${index}`]);
1495
+ if (!team.success) return {
1496
+ code: "failed",
1497
+ message: `GitHub shows the signed-in user no team ${organization}/${slug}`
1498
+ };
1499
+ teamIds.push(team.data.team.id);
1500
+ }
1501
+ return {
1502
+ users: userIds,
1503
+ teams: teamIds
1504
+ };
1505
+ }
1506
+ /**
1507
+ * Update the head branch with `updatePullRequestBranch`. The head is read first and the update is refused once it is
1508
+ * another commit; GitHub also checks `expectedHeadOid` itself.
1509
+ * @param read - runs one GraphQL query.
1510
+ * @param write - runs one GraphQL mutation.
1511
+ * @param ref - pull request address.
1512
+ * @param request - update method and the head commit the user confirmed.
1513
+ * @param signal - cancellation of both requests.
1514
+ * @returns undefined once GitHub accepted the update, `stale` when the head moved, or why GitHub refused.
1515
+ * @throws when `request.headSha` is not a full commit object name.
1516
+ */
1517
+ async function updateGitHubBranch(read, write, ref, request, signal) {
1518
+ if (!isCommit(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`);
1519
+ const id = await pullRequestNode(read, ref, request.headSha, signal);
1520
+ if (typeof id !== "string") return id;
1521
+ return await write(ref.repository.host, {
1522
+ query: UPDATE_BRANCH_MUTATION,
1523
+ field: "updatePullRequestBranch",
1524
+ variables: { input: {
1525
+ pullRequestId: id,
1526
+ expectedHeadOid: request.headSha,
1527
+ updateMethod: request.method === "rebase" ? "REBASE" : "MERGE"
1528
+ } }
1529
+ }, signal);
1530
+ }
1531
+ /**
1532
+ * List accounts a review can be requested from: GitHub's suggestions for the pull request when `query` is empty, then
1533
+ * the accounts that can be assigned in the repository whose login or name matches `query`, without the author.
1534
+ * @param read - runs one GraphQL query.
1535
+ * @param ref - pull request address.
1536
+ * @param query - text the login or name contains.
1537
+ * @param signal - cancellation of the read.
1538
+ * @returns at most 20 accounts, each once, or why GitHub did not list them.
1539
+ */
1540
+ async function gitHubReviewerCandidates(read, ref, query, signal) {
1541
+ const { host, owner, name } = checkedRepository(ref);
1542
+ const search = query.trim();
1543
+ const body = await read([
1544
+ "api",
1545
+ "graphql",
1546
+ "--hostname",
1547
+ host,
1548
+ "-f",
1549
+ `query=${CANDIDATES_QUERY}`,
1550
+ "-f",
1551
+ `owner=${owner}`,
1552
+ "-f",
1553
+ `name=${name}`,
1554
+ "-F",
1555
+ `number=${ref.number}`,
1556
+ "-f",
1557
+ `search=${search}`
1558
+ ], signal);
1559
+ if (!body.ok) return body.failure;
1560
+ const parsed = candidatesSchema.safeParse(body.body);
1561
+ if (!parsed.success) return {
1562
+ code: "unavailable",
1563
+ message: "unexpected GitHub response to the reviewer listing"
1564
+ };
1565
+ const repository = parsed.data.data.repository;
1566
+ if (repository === null) return {
1567
+ code: "not-found",
1568
+ message: `repository ${owner}/${name} is not visible`
1569
+ };
1570
+ const author = repository.pullRequest?.author?.login.toLowerCase();
1571
+ const listed = /* @__PURE__ */ new Map();
1572
+ const add = (entry, suggested) => {
1573
+ const key = entry.login.toLowerCase();
1574
+ if (key !== author && !listed.has(key)) listed.set(key, {
1575
+ login: entry.login,
1576
+ name: entry.name,
1577
+ avatarUrl: entry.avatarUrl,
1578
+ suggested
1579
+ });
1580
+ };
1581
+ if (search === "") for (const suggestion of repository.pullRequest?.suggestedReviewers ?? []) add(suggestion.reviewer, true);
1582
+ for (const user of repository.assignableUsers.nodes) add(user, false);
1583
+ return [...listed.values()].slice(0, CANDIDATES);
1584
+ }
1585
+ //#endregion
1586
+ //#region lib/types/review-writes.js
1587
+ /** GitHub writes to review threads and the pending review through GraphQL mutations, each after a check of the head. */
1588
+ /**
1589
+ * Pull request fields every write checks: its id, its head, and its pending reviews. GitHub lists a pending review only
1590
+ * to its author, who has at most one per pull request; the page reads the most GitHub returns, so the viewer's review is
1591
+ * found by `viewerDidAuthor` even if another user's were listed first.
1592
+ */
1593
+ const CHECKED_PULL = "id headRefOid reviews(states: PENDING, first: 100) { nodes { id viewerDidAuthor } }";
1594
+ /** The pull request, its head, and the signed-in user's pending review; variables `owner` and `name` are strings, `number` an integer. */
1595
+ const WRITE_CHECK_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
1596
+ repository(owner: $owner, name: $name) { pullRequest(number: $number) { ${CHECKED_PULL} } }
1597
+ }`;
1598
+ /** The same check plus the pull request that holds the thread or comment `target`, a string variable. */
1599
+ const WRITE_TARGET_CHECK_QUERY = `query($owner: String!, $name: String!, $number: Int!, $target: ID!) {
1600
+ repository(owner: $owner, name: $name) { pullRequest(number: $number) { ${CHECKED_PULL} } }
1601
+ target: node(id: $target) { ... on PullRequestReviewThread { pullRequest { id } } ... on PullRequestReviewComment { pullRequest { id } } }
1602
+ }`;
1603
+ /** Start a pending review at a commit, with the line threads of `threads`. */
1604
+ const ADD_REVIEW_MUTATION = `mutation($pull: ID!, $commit: GitObjectID!, $threads: [DraftPullRequestReviewThread]) {
1605
+ addPullRequestReview(input: { pullRequestId: $pull, commitOID: $commit, threads: $threads }) { pullRequestReview { id } }
1606
+ }`;
1607
+ /** Add one line thread to a pending review. */
1608
+ const ADD_THREAD_MUTATION = `mutation($review: ID!, $path: String!, $body: String!, $line: Int!, $side: DiffSide!, $startLine: Int, $startSide: DiffSide) {
1609
+ addPullRequestReviewThread(input: {
1610
+ pullRequestReviewId: $review, path: $path, body: $body, line: $line, side: $side, startLine: $startLine, startSide: $startSide
1611
+ }) { thread { id } }
1612
+ }`;
1613
+ /** Reply to a thread, inside the pending review `review` when it is set. */
1614
+ const REPLY_MUTATION = `mutation($thread: ID!, $body: String!, $review: ID) {
1615
+ addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $thread, body: $body, pullRequestReviewId: $review }) { comment { id } }
1616
+ }`;
1617
+ /** Mark a thread resolved. */
1618
+ const RESOLVE_MUTATION = "mutation($thread: ID!) { resolveReviewThread(input: { threadId: $thread }) { thread { id } } }";
1619
+ /** Mark a thread unresolved. */
1620
+ const UNRESOLVE_MUTATION = "mutation($thread: ID!) { unresolveReviewThread(input: { threadId: $thread }) { thread { id } } }";
1621
+ /** Replace the text of a review comment. */
1622
+ const EDIT_COMMENT_MUTATION = `mutation($comment: ID!, $body: String!) {
1623
+ updatePullRequestReviewComment(input: { pullRequestReviewCommentId: $comment, body: $body }) { pullRequestReviewComment { id } }
1624
+ }`;
1625
+ /** Delete a review comment. */
1626
+ const DELETE_COMMENT_MUTATION = "mutation($comment: ID!) { deletePullRequestReviewComment(input: { id: $comment }) { clientMutationId } }";
1627
+ /** Submit a pending review with a decision and summary. */
1628
+ const SUBMIT_REVIEW_MUTATION = `mutation($review: ID!, $event: PullRequestReviewEvent!, $body: String) {
1629
+ submitPullRequestReview(input: { pullRequestReviewId: $review, event: $event, body: $body }) { pullRequestReview { id } }
1630
+ }`;
1631
+ /** Delete a pending review with its comments. */
1632
+ const DELETE_REVIEW_MUTATION = "mutation($review: ID!) { deletePullRequestReview(input: { pullRequestReviewId: $review }) { pullRequestReview { id } } }";
1633
+ const EVENTS = {
1634
+ comment: "COMMENT",
1635
+ approve: "APPROVE",
1636
+ "request-changes": "REQUEST_CHANGES"
1637
+ };
1638
+ const checkSchema = z$1.object({ data: z$1.object({
1639
+ repository: z$1.object({ pullRequest: z$1.object({
1640
+ id: z$1.string(),
1641
+ headRefOid: z$1.string(),
1642
+ reviews: z$1.object({ nodes: z$1.array(z$1.object({
1643
+ id: z$1.string(),
1644
+ viewerDidAuthor: z$1.boolean()
1645
+ })) })
1646
+ }) }),
1647
+ target: z$1.object({ pullRequest: z$1.object({ id: z$1.string() }).optional() }).nullable().optional()
1648
+ }) });
1649
+ const stringId = z$1.object({ id: z$1.string() });
1650
+ /**
1651
+ * Write to the review threads or the pending review of a pull request. One read first checks that the head is still
1652
+ * `write.headSha`, finds the signed-in user's pending review, and, for a write to a thread or comment, that the pull
1653
+ * request holds it; a moved head returns `stale` and a thread or comment elsewhere `failed`, both without writing. A
1654
+ * pending reply without a pending review first starts an empty one at `write.headSha`; when the reply then fails, that
1655
+ * empty review stays. A reply at once is refused with `failed` while the user has a pending review, since GitHub would
1656
+ * add it to that review. Mutations send their variables as JSON on stdin, and none is retried: a refusal GitHub reports
1657
+ * returns `failed`, and an answer that does not show whether GitHub applied a mutation returns `unknown`.
1658
+ * @param read - runs the check as one GraphQL request.
1659
+ * @param gh - bounded, cancellable GitHub CLI runner for the mutations.
1660
+ * @param ref - pull request, with an owner and name already checked for inlining.
1661
+ * @param write - the write and the head commit the user saw.
1662
+ * @param signal - cancellation of the check and the mutations.
1663
+ * @returns whether GitHub took the write.
1664
+ * @throws with `signal.reason` when the signal aborts before a mutation is sent.
1665
+ */
1666
+ async function writeGitHubReview(read, gh, ref, write, signal) {
1667
+ const { host, owner, name } = checkedRepository(ref);
1668
+ const target = targetOf(write);
1669
+ const checked = await read([
1670
+ "api",
1671
+ "graphql",
1672
+ "--hostname",
1673
+ host,
1674
+ "-f",
1675
+ `query=${target === null ? WRITE_CHECK_QUERY : WRITE_TARGET_CHECK_QUERY}`,
1676
+ "-f",
1677
+ `owner=${owner}`,
1678
+ "-f",
1679
+ `name=${name}`,
1680
+ "-F",
1681
+ `number=${ref.number}`,
1682
+ ...target === null ? [] : ["-f", `target=${target}`]
1683
+ ], signal);
1684
+ if (!checked.ok) return {
1685
+ ok: false,
1686
+ code: "failed",
1687
+ message: checked.failure.message
1688
+ };
1689
+ const parsed = checkSchema.safeParse(checked.body);
1690
+ if (!parsed.success) return {
1691
+ ok: false,
1692
+ code: "failed",
1693
+ message: "unexpected GitHub response to the pull request check"
1694
+ };
1695
+ const pull = parsed.data.data.repository.pullRequest;
1696
+ if (pull.headRefOid.toLowerCase() !== write.headSha.toLowerCase()) return {
1697
+ ok: false,
1698
+ code: "stale",
1699
+ message: `the pull request head moved from ${write.headSha} to ${pull.headRefOid}`
1700
+ };
1701
+ if (target !== null && parsed.data.data.target?.pullRequest?.id !== pull.id) return {
1702
+ ok: false,
1703
+ code: "failed",
1704
+ message: `${target} is not a review thread or comment of pull request ${ref.number}`
1705
+ };
1706
+ const pending = pull.reviews.nodes.find((review) => review.viewerDidAuthor)?.id ?? null;
1707
+ signal.throwIfAborted();
1708
+ const send = async (mutation) => await sendMutation(gh, host, mutation, signal);
1709
+ const done = (sent) => sent.ok ? { ok: true } : sent;
1710
+ /** Find the pending review, starting one at the head without threads when the user has none. */
1711
+ const pendingReview = async () => {
1712
+ if (pending !== null) return {
1713
+ ok: true,
1714
+ id: pending
1715
+ };
1716
+ const started = await send({
1717
+ query: ADD_REVIEW_MUTATION,
1718
+ field: "addPullRequestReview",
1719
+ variables: {
1720
+ pull: pull.id,
1721
+ commit: write.headSha,
1722
+ threads: null
1723
+ }
1724
+ });
1725
+ if (!started.ok) return started;
1726
+ const review = z$1.object({ pullRequestReview: stringId }).safeParse(started.payload);
1727
+ return review.success ? {
1728
+ ok: true,
1729
+ id: review.data.pullRequestReview.id
1730
+ } : {
1731
+ ok: false,
1732
+ code: "unknown",
1733
+ message: "unexpected GitHub response to starting a pending review"
1734
+ };
1735
+ };
1736
+ switch (write.kind) {
1737
+ case "reply": {
1738
+ if (!write.pending && pending !== null) return {
1739
+ ok: false,
1740
+ code: "failed",
1741
+ message: "GitHub adds a reply to the pending review while one exists; submit or discard it first"
1742
+ };
1743
+ const review = write.pending ? await pendingReview() : {
1744
+ ok: true,
1745
+ id: null
1746
+ };
1747
+ if (!review.ok) return review;
1748
+ return done(await send({
1749
+ query: REPLY_MUTATION,
1750
+ field: "addPullRequestReviewThreadReply",
1751
+ variables: {
1752
+ thread: write.thread,
1753
+ body: write.body,
1754
+ review: review.id
1755
+ }
1756
+ }));
1757
+ }
1758
+ case "resolve": return done(await send(write.resolved ? {
1759
+ query: RESOLVE_MUTATION,
1760
+ field: "resolveReviewThread",
1761
+ variables: { thread: write.thread }
1762
+ } : {
1763
+ query: UNRESOLVE_MUTATION,
1764
+ field: "unresolveReviewThread",
1765
+ variables: { thread: write.thread }
1766
+ }));
1767
+ case "edit-comment": return done(await send({
1768
+ query: EDIT_COMMENT_MUTATION,
1769
+ field: "updatePullRequestReviewComment",
1770
+ variables: {
1771
+ comment: write.comment,
1772
+ body: write.body
1773
+ }
1774
+ }));
1775
+ case "delete-comment": return done(await send({
1776
+ query: DELETE_COMMENT_MUTATION,
1777
+ field: "deletePullRequestReviewComment",
1778
+ variables: { comment: write.comment }
1779
+ }));
1780
+ case "add-pending": return done(await send(pending === null ? {
1781
+ query: ADD_REVIEW_MUTATION,
1782
+ field: "addPullRequestReview",
1783
+ variables: {
1784
+ pull: pull.id,
1785
+ commit: write.headSha,
1786
+ threads: [draftThread(write.comment)]
1787
+ }
1788
+ } : {
1789
+ query: ADD_THREAD_MUTATION,
1790
+ field: "addPullRequestReviewThread",
1791
+ variables: {
1792
+ review: pending,
1793
+ ...draftThread(write.comment)
1794
+ }
1795
+ }));
1796
+ case "submit-pending":
1797
+ if (pending !== write.review) return missingReview(write.review);
1798
+ return done(await send({
1799
+ query: SUBMIT_REVIEW_MUTATION,
1800
+ field: "submitPullRequestReview",
1801
+ variables: {
1802
+ review: write.review,
1803
+ event: EVENTS[write.event],
1804
+ body: write.body
1805
+ }
1806
+ }));
1807
+ case "discard-pending":
1808
+ if (pending !== write.review) return missingReview(write.review);
1809
+ return done(await send({
1810
+ query: DELETE_REVIEW_MUTATION,
1811
+ field: "deletePullRequestReview",
1812
+ variables: { review: write.review }
1813
+ }));
1814
+ /* v8 ignore next -- closed ForgeReviewWrite kind union exhaustiveness guard */
1815
+ default: return assertNever(write, "ForgeReviewWrite.kind");
1816
+ }
1817
+ }
1818
+ /** The thread or comment a write changes, or null for a write to the pull request's pending review. */
1819
+ function targetOf(write) {
1820
+ switch (write.kind) {
1821
+ case "reply":
1822
+ case "resolve": return write.thread;
1823
+ case "edit-comment":
1824
+ case "delete-comment": return write.comment;
1825
+ case "add-pending":
1826
+ case "submit-pending":
1827
+ case "discard-pending": return null;
1828
+ /* v8 ignore next -- closed ForgeReviewWrite kind union exhaustiveness guard */
1829
+ default: return assertNever(write, "ForgeReviewWrite.kind");
1830
+ }
1831
+ }
1832
+ /** The fields of a line thread in a pending review, for one side of the diff. */
1833
+ function draftThread(comment) {
1834
+ const side = comment.side === "L" ? "LEFT" : "RIGHT";
1835
+ return {
1836
+ path: comment.path,
1837
+ body: comment.body,
1838
+ line: comment.endLine,
1839
+ side,
1840
+ ...comment.startLine === comment.endLine ? {
1841
+ startLine: null,
1842
+ startSide: null
1843
+ } : {
1844
+ startLine: comment.startLine,
1845
+ startSide: side
1846
+ }
1847
+ };
1848
+ }
1849
+ function missingReview(review) {
1850
+ return {
1851
+ ok: false,
1852
+ code: "failed",
1853
+ message: `the pending review ${review} is no longer the signed-in user's pending review`
1854
+ };
1855
+ }
1856
+ //#endregion
1857
+ //#region lib/types/threads.js
1858
+ /** Reads the review threads of a GitHub pull request at one head commit through GraphQL. */
1859
+ /** Most nodes GitHub returns in one connection page. */
1860
+ const PAGE_SIZE = 100;
1861
+ /** Repository permissions that may comment on a locked conversation. */
1862
+ const WRITERS = new Set([
1863
+ "ADMIN",
1864
+ "MAINTAIN",
1865
+ "WRITE"
1866
+ ]);
1867
+ const COMMENT_PAGE = `comments(first: ${PAGE_SIZE}, after: $cursor) { pageInfo { hasNextPage endCursor } nodes { id state createdAt url body viewerCanUpdate viewerCanDelete author { __typename login avatarUrl(size: 48) } } }`;
1868
+ const THREAD_PAGE = `pageInfo { hasNextPage endCursor } nodes { ${`id isOutdated isResolved path diffSide startDiffSide line startLine originalLine originalStartLine subjectType
1869
+ viewerCanReply viewerCanResolve viewerCanUnresolve
1870
+ root: comments(first: 1) { nodes { diffHunk commit { oid } originalCommit { oid } } }
1871
+ ${COMMENT_PAGE.replace(", after: $cursor", "")}`} }`;
1872
+ /**
1873
+ * First thread page with the head, the viewer, whether the viewer may comment, and the viewer's pending review; variables
1874
+ * `owner` and `name` are strings, `number` and `first` integers.
1875
+ */
1876
+ const REVIEW_QUERY = `query($owner: String!, $name: String!, $number: Int!, $first: Int!) {
1877
+ viewer { login }
1878
+ repository(owner: $owner, name: $name) {
1879
+ isArchived viewerPermission
1880
+ pullRequest(number: $number) {
1881
+ id headRefOid locked
1882
+ reviews(states: PENDING, first: 100) { nodes { id viewerDidAuthor comments { totalCount } } }
1883
+ reviewThreads(first: $first) { ${THREAD_PAGE} }
1884
+ }
1885
+ }
1886
+ }`;
1887
+ /** Following thread page with the head it was read at; variables `id` and `cursor` are strings, `first` an integer. */
1888
+ const REVIEW_THREADS_QUERY = `query($id: ID!, $cursor: String!, $first: Int!) {
1889
+ node(id: $id) { ... on PullRequest { headRefOid reviewThreads(first: $first, after: $cursor) { ${THREAD_PAGE} } } }
1890
+ }`;
1891
+ /** Following comment page of one thread; variables `id` and `cursor` are strings. */
1892
+ const THREAD_COMMENTS_QUERY = `query($id: ID!, $cursor: String!) {
1893
+ node(id: $id) { ... on PullRequestReviewThread { ${COMMENT_PAGE} } }
1894
+ }`;
1895
+ const pageInfoSchema = z$1.object({
1896
+ hasNextPage: z$1.boolean(),
1897
+ endCursor: z$1.string().nullable()
1898
+ });
1899
+ const commitSchema = z$1.object({ oid: z$1.string().refine(isCommit) }).nullable();
1900
+ const commentSchema = z$1.object({
1901
+ id: z$1.string(),
1902
+ state: z$1.string(),
1903
+ createdAt: z$1.string(),
1904
+ url: z$1.string().nullable(),
1905
+ body: z$1.string(),
1906
+ viewerCanUpdate: z$1.boolean(),
1907
+ viewerCanDelete: z$1.boolean(),
1908
+ author: z$1.object({
1909
+ __typename: z$1.string(),
1910
+ login: z$1.string(),
1911
+ avatarUrl: z$1.string().nullable()
1912
+ }).nullable()
1913
+ });
1914
+ const commentPageSchema = z$1.object({
1915
+ pageInfo: pageInfoSchema,
1916
+ nodes: z$1.array(commentSchema)
1917
+ });
1918
+ const threadSchema = z$1.object({
1919
+ id: z$1.string(),
1920
+ isOutdated: z$1.boolean(),
1921
+ isResolved: z$1.boolean(),
1922
+ path: z$1.string(),
1923
+ diffSide: z$1.string(),
1924
+ startDiffSide: z$1.string().nullable(),
1925
+ line: z$1.number().int().nullable(),
1926
+ startLine: z$1.number().int().nullable(),
1927
+ originalLine: z$1.number().int().nullable(),
1928
+ originalStartLine: z$1.number().int().nullable(),
1929
+ subjectType: z$1.string(),
1930
+ viewerCanReply: z$1.boolean(),
1931
+ viewerCanResolve: z$1.boolean(),
1932
+ viewerCanUnresolve: z$1.boolean(),
1933
+ root: z$1.object({ nodes: z$1.array(z$1.object({
1934
+ diffHunk: z$1.string(),
1935
+ commit: commitSchema,
1936
+ originalCommit: commitSchema
1937
+ })) }),
1938
+ comments: commentPageSchema
1939
+ });
1940
+ const threadPageSchema = z$1.object({
1941
+ pageInfo: pageInfoSchema,
1942
+ nodes: z$1.array(threadSchema)
1943
+ });
1944
+ const pendingSchema = z$1.object({
1945
+ id: z$1.string(),
1946
+ viewerDidAuthor: z$1.boolean(),
1947
+ comments: z$1.object({ totalCount: z$1.number().int().nonnegative() })
1948
+ });
1949
+ const pullRequestSchema = z$1.object({
1950
+ id: z$1.string(),
1951
+ headRefOid: z$1.string(),
1952
+ locked: z$1.boolean(),
1953
+ reviews: z$1.object({ nodes: z$1.array(pendingSchema) }),
1954
+ reviewThreads: threadPageSchema
1955
+ });
1956
+ const firstPageSchema = z$1.object({ data: z$1.object({
1957
+ viewer: z$1.object({ login: z$1.string() }).nullable(),
1958
+ repository: z$1.object({
1959
+ isArchived: z$1.boolean(),
1960
+ viewerPermission: z$1.string().nullable(),
1961
+ pullRequest: pullRequestSchema.nullable()
1962
+ }).nullable()
1963
+ }) });
1964
+ const nextPageSchema = z$1.object({ data: z$1.object({ node: z$1.object({
1965
+ headRefOid: z$1.string(),
1966
+ reviewThreads: threadPageSchema
1967
+ }) }) });
1968
+ const commentsPageSchema = z$1.object({ data: z$1.object({ node: z$1.object({ comments: commentPageSchema }) }) });
1969
+ /**
1970
+ * Read the review threads of a pull request while its head is `headSha`. The first page also names the head; every
1971
+ * following thread page names the head again, so a head that moves during the read returns
1972
+ * `stale`, while a thread's comment pages do not. Threads are read up to `maxReviewThreads`, each with all of its
1973
+ * comments. A later page that would bring the pages read, measured as JSON, past `maxOutputBytes` is dropped with the
1974
+ * threads after it, and the result is marked truncated; `read` fails a first page whose output alone passes the limit.
1975
+ * @param read - runs one GraphQL request.
1976
+ * @param ref - pull request, with an owner and name already checked for inlining.
1977
+ * @param headSha - head commit the threads must be read at.
1978
+ * @param limits - thread and byte bounds.
1979
+ * @param signal - cancellation of the read.
1980
+ * @returns the threads, or why GitHub did not provide them at `headSha`.
1981
+ */
1982
+ async function readReviewThreads(read, ref, headSha, limits, signal) {
1983
+ const { host, owner, name } = checkedRepository(ref);
1984
+ const graphql = async (variables) => {
1985
+ const output = await read([
1986
+ "api",
1987
+ "graphql",
1988
+ "--hostname",
1989
+ host,
1990
+ ...variables
1991
+ ], signal);
1992
+ if (!output.ok) return output.failure;
1993
+ return {
1994
+ body: output.body,
1995
+ bytes: Buffer$1.byteLength(JSON.stringify(output.body))
1996
+ };
1997
+ };
1998
+ const unexpected = {
1999
+ code: "unavailable",
2000
+ message: "unexpected GitHub response to the review thread read"
2001
+ };
2002
+ const stale = (head) => head.toLowerCase() === headSha.toLowerCase() ? void 0 : {
2003
+ code: "stale",
2004
+ message: `the pull request head moved from ${headSha} to ${head}`
2005
+ };
2006
+ const first = await graphql([
2007
+ "-f",
2008
+ `query=${REVIEW_QUERY}`,
2009
+ "-f",
2010
+ `owner=${owner}`,
2011
+ "-f",
2012
+ `name=${name}`,
2013
+ "-F",
2014
+ `number=${ref.number}`,
2015
+ "-F",
2016
+ `first=${Math.min(PAGE_SIZE, limits.maxReviewThreads)}`
2017
+ ]);
2018
+ if ("code" in first) return first;
2019
+ const parsed = firstPageSchema.safeParse(first.body);
2020
+ if (!parsed.success) return unexpected;
2021
+ const repository = parsed.data.data.repository;
2022
+ const pull = repository?.pullRequest;
2023
+ if (repository == null || pull == null) return {
2024
+ code: "not-found",
2025
+ message: `pull request ${ref.number} was not found`
2026
+ };
2027
+ const moved = stale(pull.headRefOid);
2028
+ if (moved !== void 0) return moved;
2029
+ let bytes = first.bytes;
2030
+ let page = pull.reviewThreads;
2031
+ const threads = [];
2032
+ const viewer = parsed.data.data.viewer?.login ?? null;
2033
+ const pending = pull.reviews.nodes.find((review) => review.viewerDidAuthor);
2034
+ const pendingReview = pending === void 0 ? null : {
2035
+ id: pending.id,
2036
+ comments: pending.comments.totalCount
2037
+ };
2038
+ const viewerCanReview = !repository.isArchived && (!pull.locked || WRITERS.has(repository.viewerPermission ?? ""));
2039
+ const result = (truncated) => ({
2040
+ headSha,
2041
+ viewer,
2042
+ threads,
2043
+ truncated,
2044
+ pendingReview,
2045
+ viewerCanReview
2046
+ });
2047
+ const cursors = /* @__PURE__ */ new Set();
2048
+ for (;;) {
2049
+ for (const node of page.nodes.slice(0, limits.maxReviewThreads - threads.length)) {
2050
+ const comments = [...node.comments.nodes];
2051
+ const commentCursors = /* @__PURE__ */ new Set();
2052
+ let more = node.comments.pageInfo;
2053
+ while (more.hasNextPage) {
2054
+ const cursor = more.endCursor;
2055
+ if (cursor === null || commentCursors.has(cursor)) return {
2056
+ code: "unavailable",
2057
+ message: "GitHub review comment pagination did not advance"
2058
+ };
2059
+ commentCursors.add(cursor);
2060
+ const next = await graphql([
2061
+ "-f",
2062
+ `query=${THREAD_COMMENTS_QUERY}`,
2063
+ "-f",
2064
+ `id=${node.id}`,
2065
+ "-f",
2066
+ `cursor=${cursor}`
2067
+ ]);
2068
+ if ("code" in next) return next;
2069
+ const comment = commentsPageSchema.safeParse(next.body);
2070
+ if (!comment.success) return unexpected;
2071
+ bytes += next.bytes;
2072
+ if (bytes > limits.maxOutputBytes) return result(true);
2073
+ comments.push(...comment.data.data.node.comments.nodes);
2074
+ more = comment.data.data.node.comments.pageInfo;
2075
+ }
2076
+ if (comments.length > 0) threads.push(toThread(node, comments, headSha));
2077
+ }
2078
+ if (threads.length >= limits.maxReviewThreads || !page.pageInfo.hasNextPage) return result(page.pageInfo.hasNextPage);
2079
+ const cursor = page.pageInfo.endCursor;
2080
+ if (cursor === null || cursors.has(cursor)) return {
2081
+ code: "unavailable",
2082
+ message: "GitHub review thread pagination did not advance"
2083
+ };
2084
+ cursors.add(cursor);
2085
+ const next = await graphql([
2086
+ "-f",
2087
+ `query=${REVIEW_THREADS_QUERY}`,
2088
+ "-f",
2089
+ `id=${pull.id}`,
2090
+ "-f",
2091
+ `cursor=${cursor}`,
2092
+ "-F",
2093
+ `first=${Math.min(PAGE_SIZE, limits.maxReviewThreads - threads.length)}`
2094
+ ]);
2095
+ if ("code" in next) return next;
2096
+ const following = nextPageSchema.safeParse(next.body);
2097
+ if (!following.success) return unexpected;
2098
+ const movedLater = stale(following.data.data.node.headRefOid);
2099
+ if (movedLater !== void 0) return movedLater;
2100
+ bytes += next.bytes;
2101
+ if (bytes > limits.maxOutputBytes) return result(true);
2102
+ page = following.data.data.node.reviewThreads;
2103
+ }
2104
+ }
2105
+ /**
2106
+ * Map one thread. GitHub keeps a thread's `line` on the commit of its first comment, which stays an older commit for
2107
+ * a comment written on a commit the head no longer is; such a thread, like one GitHub marks outdated or leaves
2108
+ * without a line, has no position at `head`. A range whose start is on the other side of the diff keeps its last line.
2109
+ */
2110
+ function toThread(node, comments, head) {
2111
+ const root = node.root.nodes[0];
2112
+ const line = node.subjectType !== "FILE";
2113
+ const sameSide = node.startDiffSide === null || node.startDiffSide === node.diffSide;
2114
+ const placed = line && !node.isOutdated && node.line !== null && root?.commit?.oid.toLowerCase() === head.toLowerCase();
2115
+ return {
2116
+ id: node.id,
2117
+ path: node.path,
2118
+ side: node.diffSide === "LEFT" ? "L" : "R",
2119
+ subject: line ? "line" : "file",
2120
+ current: placed && node.line !== null ? anchor(head, sameSide ? node.startLine : null, node.line) : null,
2121
+ original: line && node.originalLine !== null && root?.originalCommit != null ? anchor(root.originalCommit.oid, sameSide ? node.originalStartLine : null, node.originalLine) : null,
2122
+ diffHunk: root === void 0 || root.diffHunk === "" ? null : root.diffHunk,
2123
+ resolved: node.isResolved,
2124
+ viewerCanReply: node.viewerCanReply,
2125
+ viewerCanResolve: node.isResolved ? node.viewerCanUnresolve : node.viewerCanResolve,
2126
+ comments: comments.map(toComment)
2127
+ };
2128
+ }
2129
+ function anchor(commit, start, end) {
2130
+ return {
2131
+ commit,
2132
+ startLine: start !== null && start >= 1 && start <= end ? start : end,
2133
+ endLine: end
2134
+ };
2135
+ }
2136
+ function toComment(node) {
2137
+ return {
2138
+ id: node.id,
2139
+ author: node.author === null ? null : {
2140
+ login: node.author.login,
2141
+ avatarUrl: node.author.avatarUrl,
2142
+ bot: node.author.__typename === "Bot"
2143
+ },
2144
+ body: node.body,
2145
+ createdAt: node.createdAt,
2146
+ pending: node.state === "PENDING",
2147
+ url: node.url,
2148
+ viewerCanEdit: node.viewerCanUpdate,
2149
+ viewerCanDelete: node.viewerCanDelete
2150
+ };
2151
+ }
2152
+ //#endregion
667
2153
  //#region lib/types/provider.js
668
2154
  /** GitHub implementation of the forge provider contract. */
669
2155
  const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i;
670
2156
  /** Status code `gh api` appends to the message of a failed request. */
671
2157
  const HTTP_STATUS = /\(HTTP (\d{3})\)/;
672
2158
  /**
673
- * GitHub's error code for an answer over its size limits, such as a diff over
674
- * 300 files: `gh pr diff` prints it after the field, and `gh api` returns it in the JSON error body.
2159
+ * GitHub's error code for an answer over its size limits, such as a file over
2160
+ * the contents API limit: `gh api` returns it in the JSON error body.
675
2161
  */
676
2162
  const TOO_LARGE = /\btoo_large\b/;
677
- /** A full SHA-1 or SHA-256 object name. */
678
- const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
2163
+ /** HTTP status GitHub answers when it refuses to render a diff over its limits. */
2164
+ const NOT_ACCEPTABLE = "406";
679
2165
  /** Reads GitHub and GitHub Enterprise pull requests through a `gh` runner. */
680
2166
  var GitHubProvider = class {
681
2167
  gh;
682
- maxOutputBytes;
2168
+ limits;
683
2169
  forge = "github";
684
2170
  hosts;
685
2171
  async submitReview(ref, request, signal) {
@@ -692,13 +2178,38 @@ var GitHubProvider = class {
692
2178
  return await submitGitHubReview(this.gh, ref, request, signal);
693
2179
  }
694
2180
  /**
2181
+ * Read the review threads of a pull request at `headSha` through GraphQL, each page naming the head it was read at.
2182
+ * @see readReviewThreads
2183
+ */
2184
+ async readReview(ref, headSha, signal) {
2185
+ const failure = this.hostFailure(ref.repository.host);
2186
+ if (failure !== void 0) return failure;
2187
+ if (!isCommit(headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(headSha)}`);
2188
+ return await readReviewThreads(this.graphql, ref, headSha, this.limits, signal);
2189
+ }
2190
+ /**
2191
+ * Write to the review threads or the pending review of a pull request through GraphQL mutations after a check of its head.
2192
+ * @see writeGitHubReview
2193
+ */
2194
+ async writeReview(ref, write, signal) {
2195
+ const failure = this.hostFailure(ref.repository.host);
2196
+ if (failure !== void 0) return {
2197
+ ok: false,
2198
+ code: "failed",
2199
+ message: failure.message
2200
+ };
2201
+ if (!isCommit(write.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(write.headSha)}`);
2202
+ return await writeGitHubReview(this.graphql, this.gh, ref, write, signal);
2203
+ }
2204
+ /**
695
2205
  * @param gh - runner that executes `gh` on the host.
696
2206
  * @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts.
697
- * @param maxOutputBytes - maximum combined JSON bytes retained by an explicit check read.
2207
+ * @param limits - bounds on retained check and review bytes, counted and read review threads, listed commits, and listed
2208
+ * viewed files.
698
2209
  */
699
- constructor(gh, hosts, maxOutputBytes) {
2210
+ constructor(gh, hosts, limits) {
700
2211
  this.gh = gh;
701
- this.maxOutputBytes = maxOutputBytes;
2212
+ this.limits = limits;
702
2213
  this.hosts = new Set(hosts.map((host) => host.toLowerCase()));
703
2214
  }
704
2215
  repositoryFromRemote(url) {
@@ -749,11 +2260,7 @@ var GitHubProvider = class {
749
2260
  return (await this.fetchHost(ref.repository.host, [ref], signal, true)).get(changeRequestKey(ref));
750
2261
  } catch (error) {
751
2262
  if (signal.aborted) throw signal.reason;
752
- if (error instanceof GhUnavailableError || error instanceof GhTimeoutError || error instanceof GhOutputLimitError) return {
753
- code: error instanceof GhOutputLimitError ? "too-large" : "unavailable",
754
- message: error.message
755
- };
756
- throw error;
2263
+ return processFailure(error);
757
2264
  }
758
2265
  }
759
2266
  async findByHead(repository, branch, signal) {
@@ -809,7 +2316,7 @@ var GitHubProvider = class {
809
2316
  code: "failed",
810
2317
  message: failure.message
811
2318
  };
812
- if (!COMMIT.test(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`);
2319
+ if (!isCommit(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`);
813
2320
  return await this.act([
814
2321
  "api",
815
2322
  "--hostname",
@@ -823,27 +2330,71 @@ var GitHubProvider = class {
823
2330
  `sha=${request.headSha}`
824
2331
  ], signal);
825
2332
  }
826
- /** Read the pull request's diff with `gh pr diff`, which GitHub computes against the merge base. */
827
- async diff(ref, signal) {
2333
+ /**
2334
+ * Read the pull request's diff at `headSha`. One GraphQL read names the
2335
+ * current head and the base commit GitHub recorded with it; a head other
2336
+ * than `headSha` returns `stale`. Otherwise the compare endpoint reads the
2337
+ * patch from the merge base of that base commit and `headSha`, as the pull
2338
+ * request's own diff does, with both ends fixed. Given the `base` the latest
2339
+ * status recorded with `headSha`, the comparison from it runs while the
2340
+ * GraphQL read confirms the head; a stale head or another base commit
2341
+ * cancels that comparison and waits for it to end before the read returns.
2342
+ */
2343
+ async diff(ref, headSha, signal, base) {
828
2344
  const { host, owner, name } = checkedRepository(ref);
829
2345
  const failure = this.hostFailure(host);
830
2346
  if (failure !== void 0) return failure;
831
- return await this.read([
832
- "pr",
833
- "diff",
834
- String(ref.number),
835
- "--repo",
836
- `${host}/${owner}/${name}`,
837
- "--color",
838
- "never"
839
- ], signal);
2347
+ if (!isCommit(headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(headSha)}`);
2348
+ if (base !== void 0 && !isCommit(base)) throw new Error(`forge-github: invalid base commit ${JSON.stringify(base)}`);
2349
+ const compare = async (from, operation) => await readComparison(async (args, inner) => await this.read(args, inner), ref.repository, from, headSha, operation);
2350
+ const speculation = new AbortController();
2351
+ const early = base === void 0 ? void 0 : {
2352
+ base,
2353
+ patch: compare(base, AbortSignal.any([signal, speculation.signal]))
2354
+ };
2355
+ const settled = early?.patch.then(() => void 0, () => void 0);
2356
+ const discard = async () => {
2357
+ speculation.abort();
2358
+ await settled;
2359
+ };
2360
+ try {
2361
+ const output = await this.read([
2362
+ "api",
2363
+ "graphql",
2364
+ "--hostname",
2365
+ host,
2366
+ "-f",
2367
+ `query=${PULL_REQUEST_COMMITS_QUERY}`,
2368
+ "-f",
2369
+ `owner=${owner}`,
2370
+ "-f",
2371
+ `name=${name}`,
2372
+ "-F",
2373
+ `number=${ref.number}`
2374
+ ], signal);
2375
+ if (typeof output !== "string") return output;
2376
+ const commits = mapPullRequestCommitsResponse(parseJson(output));
2377
+ if (commits === void 0) return {
2378
+ code: "unavailable",
2379
+ message: "unexpected GitHub response to the pull request commit read"
2380
+ };
2381
+ if (commits.head.toLowerCase() !== headSha.toLowerCase()) return {
2382
+ code: "stale",
2383
+ message: `the pull request head moved from ${headSha} to ${commits.head}`
2384
+ };
2385
+ if (early?.base.toLowerCase() === commits.base.toLowerCase()) return await early.patch;
2386
+ await discard();
2387
+ return await compare(commits.base, signal);
2388
+ } finally {
2389
+ await discard();
2390
+ }
840
2391
  }
841
2392
  /** Read one file at a commit through the contents API in its raw form. */
842
2393
  async fileText(ref, commit, path, signal) {
843
2394
  const { host, owner, name } = checkedRepository(ref);
844
2395
  const failure = this.hostFailure(host);
845
2396
  if (failure !== void 0) return failure;
846
- if (!COMMIT.test(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`);
2397
+ if (!isCommit(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`);
847
2398
  return await this.read([
848
2399
  "api",
849
2400
  "--hostname",
@@ -853,6 +2404,111 @@ var GitHubProvider = class {
853
2404
  `repos/${owner}/${name}/contents/${encodedPath(path)}?ref=${commit}`
854
2405
  ], signal);
855
2406
  }
2407
+ /** List the pull request's commits through GraphQL, at most `maxCommits`, all read at one head. */
2408
+ async commits(ref, signal) {
2409
+ const { host } = checkedRepository(ref);
2410
+ const failure = this.hostFailure(host);
2411
+ if (failure !== void 0) return failure;
2412
+ return await listCommits(this.graphql, ref, this.limits.maxCommits, signal);
2413
+ }
2414
+ /** Read the changes between two commits through the compare API in its diff form. */
2415
+ async compare(ref, base, head, signal) {
2416
+ const failure = this.hostFailure(checkedRepository(ref).host);
2417
+ if (failure !== void 0) return failure;
2418
+ return await readComparison(async (args, operation) => await this.read(args, operation), ref.repository, base, head, signal);
2419
+ }
2420
+ /** Read the viewer's viewed marks through GraphQL, at most `maxViewedFiles`, every page at `headSha`. */
2421
+ async viewedFiles(ref, headSha, signal) {
2422
+ const failure = this.hostFailure(checkedRepository(ref).host);
2423
+ if (failure !== void 0) return failure;
2424
+ return await readViewed(this.graphql, ref, headSha, this.limits.maxViewedFiles, signal);
2425
+ }
2426
+ /** Set or clear the viewer's mark with `markFileAsViewed` or `unmarkFileAsViewed` after confirming the head. */
2427
+ async setViewed(ref, request, signal) {
2428
+ const failure = this.hostFailure(checkedRepository(ref).host);
2429
+ if (failure !== void 0) return {
2430
+ code: "failed",
2431
+ message: failure.message
2432
+ };
2433
+ return await writeViewed(this.graphql, this.mutate, ref, request, signal);
2434
+ }
2435
+ /**
2436
+ * Rerun every finished workflow run with a failed GitHub Actions job on the head commit through the REST API; GitHub
2437
+ * reruns its failed jobs with the jobs that depend on them. A run with a check still pending waits, as GitHub offers
2438
+ * no rerun of a run in progress. Every eligible run is tried, and a refusal of one is reported with the others' outcome.
2439
+ * Other checks name no rerun.
2440
+ */
2441
+ async rerunChecks(ref, request, signal) {
2442
+ const { host, owner, name } = checkedRepository(ref);
2443
+ const failure = this.hostFailure(host);
2444
+ if (failure !== void 0) return {
2445
+ code: "failed",
2446
+ message: failure.message
2447
+ };
2448
+ if (!isCommit(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`);
2449
+ const snapshot = await this.fetchChecks(ref, signal);
2450
+ if ("code" in snapshot) return {
2451
+ code: snapshot.code === "unauthenticated" ? "unauthenticated" : "failed",
2452
+ message: snapshot.message
2453
+ };
2454
+ if (snapshot.headSha.toLowerCase() !== request.headSha.toLowerCase()) return {
2455
+ code: "stale",
2456
+ message: `the pull request head moved from ${request.headSha} to ${snapshot.headSha}`
2457
+ };
2458
+ const endpoint = `repos/${owner}/${name}/actions`;
2459
+ const failed = /* @__PURE__ */ new Set();
2460
+ const running = /* @__PURE__ */ new Set();
2461
+ for (const check of snapshot.checks) {
2462
+ const run = check.rerun === null ? void 0 : actionsRunOf(check.rerun);
2463
+ if (run === void 0) continue;
2464
+ if (check.state === "failure") failed.add(run);
2465
+ else if (check.state === "pending") running.add(run);
2466
+ }
2467
+ const runs = [...failed].filter((run) => !running.has(run));
2468
+ if (runs.length === 0) return {
2469
+ code: "failed",
2470
+ message: failed.size === 0 ? "No failed GitHub Actions job of the head commit can be rerun" : "Every workflow run with a failed job is still running; rerun it once it finishes"
2471
+ };
2472
+ const refusals = [];
2473
+ for (const run of runs) {
2474
+ const refused = await this.act([
2475
+ "api",
2476
+ "--hostname",
2477
+ host,
2478
+ "--method",
2479
+ "POST",
2480
+ `${endpoint}/runs/${run}/rerun-failed-jobs`
2481
+ ], signal);
2482
+ if (refused === void 0) continue;
2483
+ if (refused.code === "unauthenticated") return refused;
2484
+ refusals.push(`run ${run}: ${refused.message}`);
2485
+ }
2486
+ return refusals.length === 0 ? void 0 : {
2487
+ code: "failed",
2488
+ message: `GitHub refused to rerun ${refusals.length} of ${runs.length} workflow runs: ${refusals.join("; ")}`
2489
+ };
2490
+ }
2491
+ async requestReviews(ref, request, signal) {
2492
+ const failure = this.hostFailure(checkedRepository(ref).host);
2493
+ if (failure !== void 0) return {
2494
+ code: "failed",
2495
+ message: failure.message
2496
+ };
2497
+ return await requestGitHubReviews(this.graphql, this.mutate, ref, request, signal);
2498
+ }
2499
+ async reviewerCandidates(ref, query, signal) {
2500
+ const failure = this.hostFailure(checkedRepository(ref).host);
2501
+ if (failure !== void 0) return failure;
2502
+ return await gitHubReviewerCandidates(this.graphql, ref, query, signal);
2503
+ }
2504
+ async updateBranch(ref, request, signal) {
2505
+ const failure = this.hostFailure(checkedRepository(ref).host);
2506
+ if (failure !== void 0) return {
2507
+ code: "failed",
2508
+ message: failure.message
2509
+ };
2510
+ return await updateGitHubBranch(this.graphql, this.mutate, ref, request, signal);
2511
+ }
856
2512
  fileUrl(ref, commit, path) {
857
2513
  const { host, owner, name } = ref.repository;
858
2514
  return `https://${host}/${owner}/${name}/blob/${commit}/${encodedPath(path)}`;
@@ -915,7 +2571,7 @@ var GitHubProvider = class {
915
2571
  code: "unauthenticated",
916
2572
  message
917
2573
  };
918
- if (TOO_LARGE.test(output.stderr) || TOO_LARGE.test(output.stdout)) return {
2574
+ if (status === NOT_ACCEPTABLE || TOO_LARGE.test(output.stderr) || TOO_LARGE.test(output.stdout)) return {
919
2575
  code: "too-large",
920
2576
  message
921
2577
  };
@@ -924,6 +2580,46 @@ var GitHubProvider = class {
924
2580
  message
925
2581
  };
926
2582
  }
2583
+ /** Run one GraphQL request; a refusal, a body that is not GraphQL, and GraphQL errors become failures. */
2584
+ graphql = async (args, signal) => {
2585
+ const output = await this.read(args, signal);
2586
+ if (typeof output !== "string") return {
2587
+ ok: false,
2588
+ failure: output
2589
+ };
2590
+ const body = parseJson(output);
2591
+ if (!hasGraphqlFields(body)) return {
2592
+ ok: false,
2593
+ failure: {
2594
+ code: "unavailable",
2595
+ message: "unexpected GitHub response"
2596
+ }
2597
+ };
2598
+ const errors = typeof body === "object" && body !== null && "errors" in body && Array.isArray(body.errors) ? body.errors : [];
2599
+ if (errors.length > 0) return {
2600
+ ok: false,
2601
+ failure: responseFailure({
2602
+ exitCode: 0,
2603
+ stdout: output,
2604
+ stderr: ""
2605
+ }, errors[0])
2606
+ };
2607
+ return {
2608
+ ok: true,
2609
+ body
2610
+ };
2611
+ };
2612
+ /**
2613
+ * Run one GraphQL mutation through {@link sendMutation}, which never retries it: a refusal or a `gh` that cannot
2614
+ * start is `failed`, and an answer that does not confirm the outcome is `unknown`.
2615
+ */
2616
+ mutate = async (host, mutation, signal) => {
2617
+ const sent = await sendMutation(this.gh, host, mutation, signal);
2618
+ return sent.ok ? void 0 : {
2619
+ code: sent.code,
2620
+ message: sent.message
2621
+ };
2622
+ };
927
2623
  /** Run one changing `gh` command; a refusal or a `gh` that cannot start becomes a failure. */
928
2624
  async act(args, signal) {
929
2625
  const output = await this.attempt(args, signal);
@@ -962,7 +2658,7 @@ var GitHubProvider = class {
962
2658
  };
963
2659
  }
964
2660
  async fetchHost(host, refs, signal, completeChecks = false) {
965
- const query = snapshotQuery(refs);
2661
+ const query = snapshotQuery(refs, this.limits.maxReviewThreads);
966
2662
  const output = await this.gh([
967
2663
  "api",
968
2664
  "graphql",
@@ -972,55 +2668,99 @@ var GitHubProvider = class {
972
2668
  `query=${query.document}`
973
2669
  ], signal);
974
2670
  const body = parseJson(output.stdout);
975
- if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query);
976
2671
  let bytes = Buffer.byteLength(output.stdout);
977
2672
  const tooLarge = {
978
2673
  code: "too-large",
979
2674
  message: "GitHub check details exceed the output size limit"
980
2675
  };
981
- if (bytes > this.maxOutputBytes) return new Map([...query.targets.values()].map((ref) => [changeRequestKey(ref), tooLarge]));
982
- if (hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, async (id, cursor) => {
983
- signal.throwIfAborted();
984
- let page;
985
- try {
986
- page = await this.gh([
987
- "api",
988
- "graphql",
989
- "--hostname",
990
- host,
991
- "-f",
992
- `query=${CHECKS_QUERY}`,
993
- "-f",
994
- `id=${id}`,
995
- "-f",
996
- `cursor=${cursor}`
997
- ], signal);
998
- } catch (error) {
999
- if (signal.aborted) throw signal.reason;
1000
- if (error instanceof GhUnavailableError || error instanceof GhTimeoutError || error instanceof GhOutputLimitError) return {
1001
- ok: false,
1002
- failure: {
1003
- code: error instanceof GhOutputLimitError ? "too-large" : "unavailable",
1004
- message: error.message
1005
- }
1006
- };
1007
- throw error;
1008
- }
2676
+ const overBudget = (page) => {
2677
+ if (!completeChecks) return false;
1009
2678
  bytes += Buffer.byteLength(page.stdout);
1010
- if (bytes > this.maxOutputBytes) return {
2679
+ return bytes > this.limits.maxOutputBytes;
2680
+ };
2681
+ const continuation = async (variables, map) => {
2682
+ const page = await this.continuation(host, variables, signal);
2683
+ if (!("stdout" in page)) return {
2684
+ ok: false,
2685
+ failure: page
2686
+ };
2687
+ if (overBudget(page)) return {
1011
2688
  ok: false,
1012
2689
  failure: tooLarge
1013
2690
  };
1014
2691
  const value = parseJson(page.stdout);
1015
- return hasGraphqlFields(value) ? mapCheckPageResponse(value) : {
2692
+ return hasGraphqlFields(value) ? map(value) : {
1016
2693
  ok: false,
1017
2694
  failure: responseFailure(page, value)
1018
2695
  };
2696
+ };
2697
+ const threads = async (id, cursor, first) => await continuation([
2698
+ "-f",
2699
+ `query=${THREADS_QUERY}`,
2700
+ "-f",
2701
+ `id=${id}`,
2702
+ "-f",
2703
+ `cursor=${cursor}`,
2704
+ "-F",
2705
+ `first=${first}`
2706
+ ], mapThreadPageResponse);
2707
+ if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, { threads });
2708
+ if (bytes > this.limits.maxOutputBytes) return new Map([...query.targets.values()].map((ref) => [changeRequestKey(ref), tooLarge]));
2709
+ if (hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, {
2710
+ threads,
2711
+ checks: async (id, cursor) => await continuation([
2712
+ "-f",
2713
+ `query=${CHECKS_QUERY}`,
2714
+ "-f",
2715
+ `id=${id}`,
2716
+ "-f",
2717
+ `cursor=${cursor}`
2718
+ ], mapCheckPageResponse)
1019
2719
  });
1020
2720
  const failure = responseFailure(output, body);
1021
2721
  return new Map([...query.targets.values()].map((ref) => [changeRequestKey(ref), failure]));
1022
2722
  }
2723
+ /**
2724
+ * Run one continuation query of a snapshot read.
2725
+ * @param host - host the snapshot was read from.
2726
+ * @param variables - `gh api graphql` field flags, the query first.
2727
+ * @param signal - cancellation of the snapshot read.
2728
+ * @returns the output, or the failure of a `gh` that cannot start, times out, or prints over its limit.
2729
+ * @throws with `signal.reason` when the read is cancelled.
2730
+ */
2731
+ async continuation(host, variables, signal) {
2732
+ signal.throwIfAborted();
2733
+ try {
2734
+ return await this.gh([
2735
+ "api",
2736
+ "graphql",
2737
+ "--hostname",
2738
+ host,
2739
+ ...variables
2740
+ ], signal);
2741
+ } catch (error) {
2742
+ if (signal.aborted) throw signal.reason;
2743
+ return processFailure(error);
2744
+ }
2745
+ }
1023
2746
  };
2747
+ /**
2748
+ * Report a `gh` invocation that did not run to an exit code.
2749
+ * @param error - what the runner threw.
2750
+ * @returns `too-large` for output over its limit, `unavailable` for a `gh` that cannot start or times out.
2751
+ * @throws `error` when it is any other failure.
2752
+ */
2753
+ function processFailure(error) {
2754
+ if (error instanceof GhOutputLimitError) return {
2755
+ code: "too-large",
2756
+ message: error.message
2757
+ };
2758
+ if (error instanceof GhUnavailableError || error instanceof GhTimeoutError) return {
2759
+ code: "unavailable",
2760
+ message: error.message
2761
+ };
2762
+ throw error;
2763
+ }
1024
2764
  /** Why `gh` refused: GitHub's message, else its first diagnostic line, with the HTTP status it names. */
1025
2765
  function refusal(output) {
1026
2766
  return {
@@ -1067,7 +2807,10 @@ const Config = z.object({
1067
2807
  ghCommand: z.string().default("gh"),
1068
2808
  hosts: z.array(z.string()).default(["github.com"]),
1069
2809
  timeoutMs: z.number().default(3e4),
1070
- maxOutputBytes: z.number().default(8388608)
2810
+ maxOutputBytes: z.number().default(8388608),
2811
+ maxReviewThreads: z.number().default(1e3),
2812
+ maxCommits: z.number().default(250),
2813
+ maxViewedFiles: z.number().default(3e3)
1071
2814
  });
1072
2815
  const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i;
1073
2816
  function apply(ctx, config) {
@@ -1076,8 +2819,13 @@ function apply(ctx, config) {
1076
2819
  if (resolved.hosts.length === 0) throw new Error("forge-github: hosts must list at least one host");
1077
2820
  for (const host of resolved.hosts) if (!HOST.test(host)) throw new Error(`forge-github: invalid host ${JSON.stringify(host)}`);
1078
2821
  if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0 || resolved.timeoutMs > MAX_TIMER_DELAY_MS) throw new Error(`forge-github: timeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`);
1079
- if (!Number.isSafeInteger(resolved.maxOutputBytes) || resolved.maxOutputBytes <= 0) throw new Error("forge-github: maxOutputBytes must be a positive safe integer");
1080
- ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved.maxOutputBytes));
2822
+ for (const key of [
2823
+ "maxOutputBytes",
2824
+ "maxReviewThreads",
2825
+ "maxCommits",
2826
+ "maxViewedFiles"
2827
+ ]) if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-github: ${key} must be a positive safe integer`);
2828
+ ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved));
1081
2829
  }
1082
2830
  //#endregion
1083
2831
  export { Config, apply, inject, name };