@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.
- package/README.i18n.yaml +6 -6
- package/README.md +27 -6
- package/README.zh.md +27 -6
- package/lib/index.js +1860 -112
- package/lib/types/commits.d.ts +24 -0
- package/lib/types/commits.d.ts.map +1 -0
- package/lib/types/commits.js.map +1 -0
- package/lib/types/compare.d.ts +23 -0
- package/lib/types/compare.d.ts.map +1 -0
- package/lib/types/compare.js.map +1 -0
- package/lib/types/gh.d.ts.map +1 -0
- package/lib/types/gh.js.map +1 -0
- package/lib/types/graphql.d.ts +66 -10
- package/lib/types/graphql.d.ts.map +1 -0
- package/lib/types/graphql.js.map +1 -0
- package/lib/types/index.d.ts +10 -1
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/mutation.d.ts +40 -0
- package/lib/types/mutation.d.ts.map +1 -0
- package/lib/types/mutation.js.map +1 -0
- package/lib/types/overview.d.ts +51 -0
- package/lib/types/overview.d.ts.map +1 -0
- package/lib/types/overview.js.map +1 -0
- package/lib/types/provider.d.ts +71 -6
- package/lib/types/provider.d.ts.map +1 -0
- package/lib/types/provider.js.map +1 -0
- package/lib/types/pull-request-node.d.ts +15 -0
- package/lib/types/pull-request-node.d.ts.map +1 -0
- package/lib/types/pull-request-node.js.map +1 -0
- package/lib/types/review-writes.d.ts +44 -0
- package/lib/types/review-writes.d.ts.map +1 -0
- package/lib/types/review-writes.js.map +1 -0
- package/lib/types/review.d.ts.map +1 -0
- package/lib/types/review.js.map +1 -0
- package/lib/types/threads.d.ts +37 -0
- package/lib/types/threads.d.ts.map +1 -0
- package/lib/types/threads.js.map +1 -0
- package/lib/types/urls.d.ts +6 -0
- package/lib/types/urls.d.ts.map +1 -0
- package/lib/types/urls.js.map +1 -0
- package/lib/types/viewed.d.ts +37 -0
- package/lib/types/viewed.d.ts.map +1 -0
- package/lib/types/viewed.js.map +1 -0
- package/package.json +13 -9
- package/src/commits.ts +102 -0
- package/src/compare.ts +43 -0
- package/src/gh.ts +71 -0
- package/src/graphql.ts +685 -0
- package/src/index.ts +60 -0
- package/src/mutation.ts +86 -0
- package/src/overview.ts +197 -0
- package/src/provider.ts +534 -0
- package/src/pull-request-node.ts +42 -0
- package/src/review-writes.ts +192 -0
- package/src/review.ts +59 -0
- package/src/threads.ts +262 -0
- package/src/urls.ts +89 -0
- package/src/viewed.ts +132 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/** GitHub writes to review threads and the pending review through GraphQL mutations, each after a check of the head. */
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
ChangeRequestRef, ForgeLineComment, ForgeReviewId, ForgeReviewWrite, ForgeReviewWriteResult,
|
|
5
|
+
} from '@deepseek-ai/dsh-experimental-forge'
|
|
6
|
+
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
|
7
|
+
import { z } from 'zod'
|
|
8
|
+
import type { GraphqlReader } from './commits.ts'
|
|
9
|
+
import type { GhRunner } from './gh.ts'
|
|
10
|
+
import { sendMutation, type GraphqlMutation, type MutationResult } from './mutation.ts'
|
|
11
|
+
import { checkedRepository } from './urls.ts'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Pull request fields every write checks: its id, its head, and its pending reviews. GitHub lists a pending review only
|
|
15
|
+
* to its author, who has at most one per pull request; the page reads the most GitHub returns, so the viewer's review is
|
|
16
|
+
* found by `viewerDidAuthor` even if another user's were listed first.
|
|
17
|
+
*/
|
|
18
|
+
const CHECKED_PULL = 'id headRefOid reviews(states: PENDING, first: 100) { nodes { id viewerDidAuthor } }'
|
|
19
|
+
|
|
20
|
+
/** The pull request, its head, and the signed-in user's pending review; variables `owner` and `name` are strings, `number` an integer. */
|
|
21
|
+
export const WRITE_CHECK_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
|
|
22
|
+
repository(owner: $owner, name: $name) { pullRequest(number: $number) { ${CHECKED_PULL} } }
|
|
23
|
+
}`
|
|
24
|
+
|
|
25
|
+
/** The same check plus the pull request that holds the thread or comment `target`, a string variable. */
|
|
26
|
+
export const WRITE_TARGET_CHECK_QUERY = `query($owner: String!, $name: String!, $number: Int!, $target: ID!) {
|
|
27
|
+
repository(owner: $owner, name: $name) { pullRequest(number: $number) { ${CHECKED_PULL} } }
|
|
28
|
+
target: node(id: $target) { ... on PullRequestReviewThread { pullRequest { id } } ... on PullRequestReviewComment { pullRequest { id } } }
|
|
29
|
+
}`
|
|
30
|
+
|
|
31
|
+
/** Start a pending review at a commit, with the line threads of `threads`. */
|
|
32
|
+
export const ADD_REVIEW_MUTATION = `mutation($pull: ID!, $commit: GitObjectID!, $threads: [DraftPullRequestReviewThread]) {
|
|
33
|
+
addPullRequestReview(input: { pullRequestId: $pull, commitOID: $commit, threads: $threads }) { pullRequestReview { id } }
|
|
34
|
+
}`
|
|
35
|
+
|
|
36
|
+
/** Add one line thread to a pending review. */
|
|
37
|
+
export const ADD_THREAD_MUTATION = `mutation($review: ID!, $path: String!, $body: String!, $line: Int!, $side: DiffSide!, $startLine: Int, $startSide: DiffSide) {
|
|
38
|
+
addPullRequestReviewThread(input: {
|
|
39
|
+
pullRequestReviewId: $review, path: $path, body: $body, line: $line, side: $side, startLine: $startLine, startSide: $startSide
|
|
40
|
+
}) { thread { id } }
|
|
41
|
+
}`
|
|
42
|
+
|
|
43
|
+
/** Reply to a thread, inside the pending review `review` when it is set. */
|
|
44
|
+
export const REPLY_MUTATION = `mutation($thread: ID!, $body: String!, $review: ID) {
|
|
45
|
+
addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $thread, body: $body, pullRequestReviewId: $review }) { comment { id } }
|
|
46
|
+
}`
|
|
47
|
+
|
|
48
|
+
/** Mark a thread resolved. */
|
|
49
|
+
export const RESOLVE_MUTATION = 'mutation($thread: ID!) { resolveReviewThread(input: { threadId: $thread }) { thread { id } } }'
|
|
50
|
+
|
|
51
|
+
/** Mark a thread unresolved. */
|
|
52
|
+
export const UNRESOLVE_MUTATION = 'mutation($thread: ID!) { unresolveReviewThread(input: { threadId: $thread }) { thread { id } } }'
|
|
53
|
+
|
|
54
|
+
/** Replace the text of a review comment. */
|
|
55
|
+
export const EDIT_COMMENT_MUTATION = `mutation($comment: ID!, $body: String!) {
|
|
56
|
+
updatePullRequestReviewComment(input: { pullRequestReviewCommentId: $comment, body: $body }) { pullRequestReviewComment { id } }
|
|
57
|
+
}`
|
|
58
|
+
|
|
59
|
+
/** Delete a review comment. */
|
|
60
|
+
export const DELETE_COMMENT_MUTATION = 'mutation($comment: ID!) { deletePullRequestReviewComment(input: { id: $comment }) { clientMutationId } }'
|
|
61
|
+
|
|
62
|
+
/** Submit a pending review with a decision and summary. */
|
|
63
|
+
export const SUBMIT_REVIEW_MUTATION = `mutation($review: ID!, $event: PullRequestReviewEvent!, $body: String) {
|
|
64
|
+
submitPullRequestReview(input: { pullRequestReviewId: $review, event: $event, body: $body }) { pullRequestReview { id } }
|
|
65
|
+
}`
|
|
66
|
+
|
|
67
|
+
/** Delete a pending review with its comments. */
|
|
68
|
+
export const DELETE_REVIEW_MUTATION = 'mutation($review: ID!) { deletePullRequestReview(input: { pullRequestReviewId: $review }) { pullRequestReview { id } } }'
|
|
69
|
+
|
|
70
|
+
const EVENTS = { comment: 'COMMENT', approve: 'APPROVE', 'request-changes': 'REQUEST_CHANGES' } as const
|
|
71
|
+
|
|
72
|
+
const checkSchema = z.object({ data: z.object({
|
|
73
|
+
repository: z.object({ pullRequest: z.object({
|
|
74
|
+
id: z.string(),
|
|
75
|
+
headRefOid: z.string(),
|
|
76
|
+
reviews: z.object({ nodes: z.array(z.object({ id: z.string(), viewerDidAuthor: z.boolean() })) }),
|
|
77
|
+
}) }),
|
|
78
|
+
target: z.object({ pullRequest: z.object({ id: z.string() }).optional() }).nullable().optional(),
|
|
79
|
+
}) })
|
|
80
|
+
|
|
81
|
+
const stringId = z.object({ id: z.string() })
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Write to the review threads or the pending review of a pull request. One read first checks that the head is still
|
|
85
|
+
* `write.headSha`, finds the signed-in user's pending review, and, for a write to a thread or comment, that the pull
|
|
86
|
+
* request holds it; a moved head returns `stale` and a thread or comment elsewhere `failed`, both without writing. A
|
|
87
|
+
* pending reply without a pending review first starts an empty one at `write.headSha`; when the reply then fails, that
|
|
88
|
+
* empty review stays. A reply at once is refused with `failed` while the user has a pending review, since GitHub would
|
|
89
|
+
* add it to that review. Mutations send their variables as JSON on stdin, and none is retried: a refusal GitHub reports
|
|
90
|
+
* returns `failed`, and an answer that does not show whether GitHub applied a mutation returns `unknown`.
|
|
91
|
+
* @param read - runs the check as one GraphQL request.
|
|
92
|
+
* @param gh - bounded, cancellable GitHub CLI runner for the mutations.
|
|
93
|
+
* @param ref - pull request, with an owner and name already checked for inlining.
|
|
94
|
+
* @param write - the write and the head commit the user saw.
|
|
95
|
+
* @param signal - cancellation of the check and the mutations.
|
|
96
|
+
* @returns whether GitHub took the write.
|
|
97
|
+
* @throws with `signal.reason` when the signal aborts before a mutation is sent.
|
|
98
|
+
*/
|
|
99
|
+
export async function writeGitHubReview(
|
|
100
|
+
read: GraphqlReader, gh: GhRunner, ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal,
|
|
101
|
+
): Promise<ForgeReviewWriteResult> {
|
|
102
|
+
const { host, owner, name } = checkedRepository(ref)
|
|
103
|
+
const target = targetOf(write)
|
|
104
|
+
const checked = await read(['api', 'graphql', '--hostname', host,
|
|
105
|
+
'-f', `query=${target === null ? WRITE_CHECK_QUERY : WRITE_TARGET_CHECK_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`,
|
|
106
|
+
'-F', `number=${ref.number}`, ...target === null ? [] : ['-f', `target=${target}`]], signal)
|
|
107
|
+
if (!checked.ok) return { ok: false, code: 'failed', message: checked.failure.message }
|
|
108
|
+
const parsed = checkSchema.safeParse(checked.body)
|
|
109
|
+
if (!parsed.success) return { ok: false, code: 'failed', message: 'unexpected GitHub response to the pull request check' }
|
|
110
|
+
const pull = parsed.data.data.repository.pullRequest
|
|
111
|
+
if (pull.headRefOid.toLowerCase() !== write.headSha.toLowerCase()) {
|
|
112
|
+
return { ok: false, code: 'stale', message: `the pull request head moved from ${write.headSha} to ${pull.headRefOid}` }
|
|
113
|
+
}
|
|
114
|
+
if (target !== null && parsed.data.data.target?.pullRequest?.id !== pull.id) {
|
|
115
|
+
return { ok: false, code: 'failed', message: `${target} is not a review thread or comment of pull request ${ref.number}` }
|
|
116
|
+
}
|
|
117
|
+
const pending = pull.reviews.nodes.find(review => review.viewerDidAuthor)?.id ?? null
|
|
118
|
+
signal.throwIfAborted()
|
|
119
|
+
const send = async (mutation: GraphqlMutation): Promise<MutationResult> => await sendMutation(gh, host, mutation, signal)
|
|
120
|
+
const done = (sent: MutationResult): ForgeReviewWriteResult => sent.ok ? { ok: true } : sent
|
|
121
|
+
/** Find the pending review, starting one at the head without threads when the user has none. */
|
|
122
|
+
const pendingReview = async (): Promise<{ readonly ok: true; readonly id: string } | Extract<MutationResult, { readonly ok: false }>> => {
|
|
123
|
+
if (pending !== null) return { ok: true, id: pending }
|
|
124
|
+
const started = await send({ query: ADD_REVIEW_MUTATION, field: 'addPullRequestReview',
|
|
125
|
+
variables: { pull: pull.id, commit: write.headSha, threads: null } })
|
|
126
|
+
if (!started.ok) return started
|
|
127
|
+
const review = z.object({ pullRequestReview: stringId }).safeParse(started.payload)
|
|
128
|
+
return review.success ? { ok: true, id: review.data.pullRequestReview.id }
|
|
129
|
+
: { ok: false, code: 'unknown', message: 'unexpected GitHub response to starting a pending review' }
|
|
130
|
+
}
|
|
131
|
+
switch (write.kind) {
|
|
132
|
+
case 'reply': {
|
|
133
|
+
// GitHub adds every reply of a user with a pending review to that review, even one sent without its id.
|
|
134
|
+
if (!write.pending && pending !== null) {
|
|
135
|
+
return { ok: false, code: 'failed', message: 'GitHub adds a reply to the pending review while one exists; submit or discard it first' }
|
|
136
|
+
}
|
|
137
|
+
const review = write.pending ? await pendingReview() : { ok: true as const, id: null }
|
|
138
|
+
if (!review.ok) return review
|
|
139
|
+
return done(await send({ query: REPLY_MUTATION, field: 'addPullRequestReviewThreadReply',
|
|
140
|
+
variables: { thread: write.thread, body: write.body, review: review.id } }))
|
|
141
|
+
}
|
|
142
|
+
case 'resolve':
|
|
143
|
+
return done(await send(write.resolved
|
|
144
|
+
? { query: RESOLVE_MUTATION, field: 'resolveReviewThread', variables: { thread: write.thread } }
|
|
145
|
+
: { query: UNRESOLVE_MUTATION, field: 'unresolveReviewThread', variables: { thread: write.thread } }))
|
|
146
|
+
case 'edit-comment':
|
|
147
|
+
return done(await send({ query: EDIT_COMMENT_MUTATION, field: 'updatePullRequestReviewComment',
|
|
148
|
+
variables: { comment: write.comment, body: write.body } }))
|
|
149
|
+
case 'delete-comment':
|
|
150
|
+
return done(await send({ query: DELETE_COMMENT_MUTATION, field: 'deletePullRequestReviewComment', variables: { comment: write.comment } }))
|
|
151
|
+
case 'add-pending':
|
|
152
|
+
return done(await send(pending === null
|
|
153
|
+
? { query: ADD_REVIEW_MUTATION, field: 'addPullRequestReview',
|
|
154
|
+
variables: { pull: pull.id, commit: write.headSha, threads: [draftThread(write.comment)] } }
|
|
155
|
+
: { query: ADD_THREAD_MUTATION, field: 'addPullRequestReviewThread', variables: { review: pending, ...draftThread(write.comment) } }))
|
|
156
|
+
case 'submit-pending':
|
|
157
|
+
if (pending !== write.review) return missingReview(write.review)
|
|
158
|
+
return done(await send({ query: SUBMIT_REVIEW_MUTATION, field: 'submitPullRequestReview',
|
|
159
|
+
variables: { review: write.review, event: EVENTS[write.event], body: write.body } }))
|
|
160
|
+
case 'discard-pending':
|
|
161
|
+
if (pending !== write.review) return missingReview(write.review)
|
|
162
|
+
return done(await send({ query: DELETE_REVIEW_MUTATION, field: 'deletePullRequestReview', variables: { review: write.review } }))
|
|
163
|
+
/* v8 ignore next -- closed ForgeReviewWrite kind union exhaustiveness guard */
|
|
164
|
+
default: return assertNever(write, 'ForgeReviewWrite.kind')
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The thread or comment a write changes, or null for a write to the pull request's pending review. */
|
|
169
|
+
function targetOf(write: ForgeReviewWrite): string | null {
|
|
170
|
+
switch (write.kind) {
|
|
171
|
+
case 'reply':
|
|
172
|
+
case 'resolve': return write.thread
|
|
173
|
+
case 'edit-comment':
|
|
174
|
+
case 'delete-comment': return write.comment
|
|
175
|
+
case 'add-pending':
|
|
176
|
+
case 'submit-pending':
|
|
177
|
+
case 'discard-pending': return null
|
|
178
|
+
/* v8 ignore next -- closed ForgeReviewWrite kind union exhaustiveness guard */
|
|
179
|
+
default: return assertNever(write, 'ForgeReviewWrite.kind')
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The fields of a line thread in a pending review, for one side of the diff. */
|
|
184
|
+
function draftThread(comment: ForgeLineComment): Readonly<Record<string, unknown>> {
|
|
185
|
+
const side = comment.side === 'L' ? 'LEFT' : 'RIGHT'
|
|
186
|
+
return { path: comment.path, body: comment.body, line: comment.endLine, side,
|
|
187
|
+
...comment.startLine === comment.endLine ? { startLine: null, startSide: null } : { startLine: comment.startLine, startSide: side } }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function missingReview(review: ForgeReviewId): ForgeReviewWriteResult {
|
|
191
|
+
return { ok: false, code: 'failed', message: `the pending review ${review} is no longer the signed-in user's pending review` }
|
|
192
|
+
}
|
package/src/review.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/** GitHub review writes with commit checks and explicit treatment of uncertain outcomes. */
|
|
2
|
+
|
|
3
|
+
import { z } from 'zod'
|
|
4
|
+
import type { ChangeRequestRef, ForgeLineComment, ForgeReviewRequest, ForgeReviewResult } from '@deepseek-ai/dsh-experimental-forge'
|
|
5
|
+
import { GhUnavailableError, type GhOutput, type GhRunner } from './gh.ts'
|
|
6
|
+
import { checkedRepository } from './urls.ts'
|
|
7
|
+
|
|
8
|
+
const pull = z.object({ head: z.object({ sha: z.string() }), state: z.string() })
|
|
9
|
+
const receipt = z.object({ html_url: z.url() })
|
|
10
|
+
const EVENTS = { comment: 'COMMENT', approve: 'APPROVE', 'request-changes': 'REQUEST_CHANGES' } as const
|
|
11
|
+
|
|
12
|
+
function inline(comment: ForgeLineComment): object {
|
|
13
|
+
const side = comment.side === 'L' ? 'LEFT' : 'RIGHT'
|
|
14
|
+
return { path: comment.path, side, line: comment.endLine, body: comment.body,
|
|
15
|
+
...comment.startLine === comment.endLine ? {} : { start_line: comment.startLine, start_side: side } }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function failed(output: GhOutput, write: boolean): ForgeReviewResult {
|
|
19
|
+
const known = /\(HTTP (?:400|401|403|404|409|422)\)/.test(output.stderr)
|
|
20
|
+
return { ok: false, code: write && !known ? 'unknown' : 'failed', message: output.stderr.trim() || output.stdout.trim() || 'GitHub request failed' }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Send one review mutation using JSON on stdin, never shell or argument interpolation.
|
|
25
|
+
* @param gh - bounded, cancellable GitHub CLI runner.
|
|
26
|
+
* @param ref - validated pull request address.
|
|
27
|
+
* @param request - frozen commit and comment ranges.
|
|
28
|
+
* @param signal - cancellation of preflight and mutation.
|
|
29
|
+
* @returns a confirmed receipt, refusal, stale commit, or uncertain outcome; never retries a write.
|
|
30
|
+
*/
|
|
31
|
+
export async function submitGitHubReview(
|
|
32
|
+
gh: GhRunner, ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal,
|
|
33
|
+
): Promise<ForgeReviewResult> {
|
|
34
|
+
const { host, owner, name } = checkedRepository(ref)
|
|
35
|
+
const endpoint = `repos/${owner}/${name}/pulls/${ref.number}`
|
|
36
|
+
let writing = false
|
|
37
|
+
try {
|
|
38
|
+
const read = await gh(['api', '--hostname', host, endpoint], signal)
|
|
39
|
+
if (read.exitCode !== 0) return failed(read, false)
|
|
40
|
+
const current = pull.parse(JSON.parse(read.stdout))
|
|
41
|
+
if (current.head.sha !== request.headSha) return { ok: false, code: 'stale', message: 'The pull request head has changed' }
|
|
42
|
+
if (current.state !== 'open') return { ok: false, code: 'failed', message: 'The pull request is not open' }
|
|
43
|
+
signal.throwIfAborted()
|
|
44
|
+
const body = request.kind === 'comment'
|
|
45
|
+
? { commit_id: request.headSha, ...inline(request.comment) }
|
|
46
|
+
: { commit_id: request.headSha, event: EVENTS[request.event], body: request.body, comments: request.comments.map(inline) }
|
|
47
|
+
writing = true
|
|
48
|
+
const output = await gh(['api', '--hostname', host, '--method', 'POST', `${endpoint}/${request.kind === 'comment' ? 'comments' : 'reviews'}`, '--input', '-'], signal, JSON.stringify(body))
|
|
49
|
+
if (output.exitCode !== 0) return failed(output, true)
|
|
50
|
+
const result = receipt.parse(JSON.parse(output.stdout))
|
|
51
|
+
const url = new URL(result.html_url)
|
|
52
|
+
if (url.protocol !== 'https:' || url.host !== host) throw new Error('GitHub returned an invalid review URL')
|
|
53
|
+
return { ok: true, url: result.html_url }
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (!writing && signal.aborted) throw signal.reason
|
|
56
|
+
return { ok: false, code: writing && !(error instanceof GhUnavailableError) ? 'unknown' : 'failed',
|
|
57
|
+
message: error instanceof Error ? error.message : String(error) }
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/threads.ts
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/** Reads the review threads of a GitHub pull request at one head commit through GraphQL. */
|
|
2
|
+
|
|
3
|
+
import { Buffer } from 'node:buffer'
|
|
4
|
+
import type {
|
|
5
|
+
ChangeRequestRef, ForgeAnchor, ForgeCommentId, ForgeFailure, ForgeReviewComment, ForgeReviewData, ForgeReviewId, ForgeReviewThread,
|
|
6
|
+
ForgeThreadId,
|
|
7
|
+
} from '@deepseek-ai/dsh-experimental-forge'
|
|
8
|
+
import { z } from 'zod'
|
|
9
|
+
import type { GraphqlReader } from './commits.ts'
|
|
10
|
+
import { checkedRepository, isCommit } from './urls.ts'
|
|
11
|
+
|
|
12
|
+
/** Most nodes GitHub returns in one connection page. */
|
|
13
|
+
const PAGE_SIZE = 100
|
|
14
|
+
|
|
15
|
+
/** Repository permissions that may comment on a locked conversation. */
|
|
16
|
+
const WRITERS: ReadonlySet<string> = new Set(['ADMIN', 'MAINTAIN', 'WRITE'])
|
|
17
|
+
|
|
18
|
+
const COMMENT_FIELDS = 'id state createdAt url body viewerCanUpdate viewerCanDelete author { __typename login avatarUrl(size: 48) }'
|
|
19
|
+
|
|
20
|
+
const COMMENT_PAGE = `comments(first: ${PAGE_SIZE}, after: $cursor) { pageInfo { hasNextPage endCursor } nodes { ${COMMENT_FIELDS} } }`
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Thread fields. `root` reads the commits and diff hunk of the first comment once, since replies repeat them; the
|
|
24
|
+
* first page of comments starts without a cursor.
|
|
25
|
+
*/
|
|
26
|
+
const THREAD_FIELDS = `id isOutdated isResolved path diffSide startDiffSide line startLine originalLine originalStartLine subjectType
|
|
27
|
+
viewerCanReply viewerCanResolve viewerCanUnresolve
|
|
28
|
+
root: comments(first: 1) { nodes { diffHunk commit { oid } originalCommit { oid } } }
|
|
29
|
+
${COMMENT_PAGE.replace(', after: $cursor', '')}`
|
|
30
|
+
|
|
31
|
+
const THREAD_PAGE = `pageInfo { hasNextPage endCursor } nodes { ${THREAD_FIELDS} }`
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* First thread page with the head, the viewer, whether the viewer may comment, and the viewer's pending review; variables
|
|
35
|
+
* `owner` and `name` are strings, `number` and `first` integers.
|
|
36
|
+
*/
|
|
37
|
+
export const REVIEW_QUERY = `query($owner: String!, $name: String!, $number: Int!, $first: Int!) {
|
|
38
|
+
viewer { login }
|
|
39
|
+
repository(owner: $owner, name: $name) {
|
|
40
|
+
isArchived viewerPermission
|
|
41
|
+
pullRequest(number: $number) {
|
|
42
|
+
id headRefOid locked
|
|
43
|
+
reviews(states: PENDING, first: 100) { nodes { id viewerDidAuthor comments { totalCount } } }
|
|
44
|
+
reviewThreads(first: $first) { ${THREAD_PAGE} }
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}`
|
|
48
|
+
|
|
49
|
+
/** Following thread page with the head it was read at; variables `id` and `cursor` are strings, `first` an integer. */
|
|
50
|
+
export const REVIEW_THREADS_QUERY = `query($id: ID!, $cursor: String!, $first: Int!) {
|
|
51
|
+
node(id: $id) { ... on PullRequest { headRefOid reviewThreads(first: $first, after: $cursor) { ${THREAD_PAGE} } } }
|
|
52
|
+
}`
|
|
53
|
+
|
|
54
|
+
/** Following comment page of one thread; variables `id` and `cursor` are strings. */
|
|
55
|
+
export const THREAD_COMMENTS_QUERY = `query($id: ID!, $cursor: String!) {
|
|
56
|
+
node(id: $id) { ... on PullRequestReviewThread { ${COMMENT_PAGE} } }
|
|
57
|
+
}`
|
|
58
|
+
|
|
59
|
+
/** Bounds of one review read. */
|
|
60
|
+
export interface ReviewLimits {
|
|
61
|
+
/** Most threads read. */
|
|
62
|
+
readonly maxReviewThreads: number
|
|
63
|
+
/**
|
|
64
|
+
* Most JSON bytes of all pages together: a later page that would pass it ends the read as truncated, and a first
|
|
65
|
+
* page whose output alone passes it fails the read as `too-large`.
|
|
66
|
+
*/
|
|
67
|
+
readonly maxOutputBytes: number
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const pageInfoSchema = z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() })
|
|
71
|
+
|
|
72
|
+
const commitSchema = z.object({ oid: z.string().refine(isCommit) }).nullable()
|
|
73
|
+
|
|
74
|
+
const commentSchema = z.object({
|
|
75
|
+
id: z.string(),
|
|
76
|
+
state: z.string(),
|
|
77
|
+
createdAt: z.string(),
|
|
78
|
+
url: z.string().nullable(),
|
|
79
|
+
body: z.string(),
|
|
80
|
+
viewerCanUpdate: z.boolean(),
|
|
81
|
+
viewerCanDelete: z.boolean(),
|
|
82
|
+
author: z.object({ __typename: z.string(), login: z.string(), avatarUrl: z.string().nullable() }).nullable(),
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
const commentPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(commentSchema) })
|
|
86
|
+
|
|
87
|
+
const threadSchema = z.object({
|
|
88
|
+
id: z.string(),
|
|
89
|
+
isOutdated: z.boolean(),
|
|
90
|
+
isResolved: z.boolean(),
|
|
91
|
+
path: z.string(),
|
|
92
|
+
diffSide: z.string(),
|
|
93
|
+
startDiffSide: z.string().nullable(),
|
|
94
|
+
line: z.number().int().nullable(),
|
|
95
|
+
startLine: z.number().int().nullable(),
|
|
96
|
+
originalLine: z.number().int().nullable(),
|
|
97
|
+
originalStartLine: z.number().int().nullable(),
|
|
98
|
+
subjectType: z.string(),
|
|
99
|
+
viewerCanReply: z.boolean(),
|
|
100
|
+
viewerCanResolve: z.boolean(),
|
|
101
|
+
viewerCanUnresolve: z.boolean(),
|
|
102
|
+
root: z.object({ nodes: z.array(z.object({ diffHunk: z.string(), commit: commitSchema, originalCommit: commitSchema })) }),
|
|
103
|
+
comments: commentPageSchema,
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
const threadPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(threadSchema) })
|
|
107
|
+
|
|
108
|
+
const pendingSchema = z.object({
|
|
109
|
+
id: z.string(),
|
|
110
|
+
viewerDidAuthor: z.boolean(),
|
|
111
|
+
comments: z.object({ totalCount: z.number().int().nonnegative() }),
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
const pullRequestSchema = z.object({
|
|
115
|
+
id: z.string(),
|
|
116
|
+
headRefOid: z.string(),
|
|
117
|
+
locked: z.boolean(),
|
|
118
|
+
reviews: z.object({ nodes: z.array(pendingSchema) }),
|
|
119
|
+
reviewThreads: threadPageSchema,
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
const firstPageSchema = z.object({ data: z.object({
|
|
123
|
+
viewer: z.object({ login: z.string() }).nullable(),
|
|
124
|
+
repository: z.object({
|
|
125
|
+
isArchived: z.boolean(),
|
|
126
|
+
viewerPermission: z.string().nullable(),
|
|
127
|
+
pullRequest: pullRequestSchema.nullable(),
|
|
128
|
+
}).nullable(),
|
|
129
|
+
}) })
|
|
130
|
+
|
|
131
|
+
const nextPageSchema = z.object({ data: z.object({ node: z.object({ headRefOid: z.string(), reviewThreads: threadPageSchema }) }) })
|
|
132
|
+
|
|
133
|
+
const commentsPageSchema = z.object({ data: z.object({ node: z.object({ comments: commentPageSchema }) }) })
|
|
134
|
+
|
|
135
|
+
type ThreadNode = z.infer<typeof threadSchema>
|
|
136
|
+
type CommentNode = z.infer<typeof commentSchema>
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Read the review threads of a pull request while its head is `headSha`. The first page also names the head; every
|
|
140
|
+
* following thread page names the head again, so a head that moves during the read returns
|
|
141
|
+
* `stale`, while a thread's comment pages do not. Threads are read up to `maxReviewThreads`, each with all of its
|
|
142
|
+
* comments. A later page that would bring the pages read, measured as JSON, past `maxOutputBytes` is dropped with the
|
|
143
|
+
* threads after it, and the result is marked truncated; `read` fails a first page whose output alone passes the limit.
|
|
144
|
+
* @param read - runs one GraphQL request.
|
|
145
|
+
* @param ref - pull request, with an owner and name already checked for inlining.
|
|
146
|
+
* @param headSha - head commit the threads must be read at.
|
|
147
|
+
* @param limits - thread and byte bounds.
|
|
148
|
+
* @param signal - cancellation of the read.
|
|
149
|
+
* @returns the threads, or why GitHub did not provide them at `headSha`.
|
|
150
|
+
*/
|
|
151
|
+
export async function readReviewThreads(
|
|
152
|
+
read: GraphqlReader, ref: ChangeRequestRef, headSha: string, limits: ReviewLimits, signal: AbortSignal,
|
|
153
|
+
): Promise<ForgeReviewData | ForgeFailure> {
|
|
154
|
+
const { host, owner, name } = checkedRepository(ref)
|
|
155
|
+
const graphql = async (variables: readonly string[]): Promise<{ readonly body: unknown; readonly bytes: number } | ForgeFailure> => {
|
|
156
|
+
const output = await read(['api', 'graphql', '--hostname', host, ...variables], signal)
|
|
157
|
+
if (!output.ok) return output.failure
|
|
158
|
+
return { body: output.body, bytes: Buffer.byteLength(JSON.stringify(output.body)) }
|
|
159
|
+
}
|
|
160
|
+
const unexpected: ForgeFailure = { code: 'unavailable', message: 'unexpected GitHub response to the review thread read' }
|
|
161
|
+
const stale = (head: string): ForgeFailure | undefined => head.toLowerCase() === headSha.toLowerCase() ? undefined
|
|
162
|
+
: { code: 'stale', message: `the pull request head moved from ${headSha} to ${head}` }
|
|
163
|
+
const first = await graphql(['-f', `query=${REVIEW_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`,
|
|
164
|
+
'-F', `number=${ref.number}`, '-F', `first=${Math.min(PAGE_SIZE, limits.maxReviewThreads)}`])
|
|
165
|
+
if ('code' in first) return first
|
|
166
|
+
const parsed = firstPageSchema.safeParse(first.body)
|
|
167
|
+
if (!parsed.success) return unexpected
|
|
168
|
+
const repository = parsed.data.data.repository
|
|
169
|
+
const pull = repository?.pullRequest
|
|
170
|
+
if (repository == null || pull == null) return { code: 'not-found', message: `pull request ${ref.number} was not found` }
|
|
171
|
+
const moved = stale(pull.headRefOid)
|
|
172
|
+
if (moved !== undefined) return moved
|
|
173
|
+
let bytes = first.bytes
|
|
174
|
+
let page = pull.reviewThreads
|
|
175
|
+
const threads: ForgeReviewThread[] = []
|
|
176
|
+
const viewer = parsed.data.data.viewer?.login ?? null
|
|
177
|
+
// GitHub lists a pending review only to its author; reading up to 100 finds the viewer's even if others were listed first.
|
|
178
|
+
const pending = pull.reviews.nodes.find(review => review.viewerDidAuthor)
|
|
179
|
+
const pendingReview = pending === undefined ? null : { id: pending.id as ForgeReviewId, comments: pending.comments.totalCount }
|
|
180
|
+
// GitHub refuses every write to an archived repository, and comments on a locked conversation from anyone without write access.
|
|
181
|
+
const viewerCanReview = !repository.isArchived && (!pull.locked || WRITERS.has(repository.viewerPermission ?? ''))
|
|
182
|
+
const result = (truncated: boolean): ForgeReviewData => ({ headSha, viewer, threads, truncated, pendingReview, viewerCanReview })
|
|
183
|
+
const cursors = new Set<string>()
|
|
184
|
+
for (;;) {
|
|
185
|
+
for (const node of page.nodes.slice(0, limits.maxReviewThreads - threads.length)) {
|
|
186
|
+
const comments = [...node.comments.nodes]
|
|
187
|
+
const commentCursors = new Set<string>()
|
|
188
|
+
let more = node.comments.pageInfo
|
|
189
|
+
while (more.hasNextPage) {
|
|
190
|
+
const cursor = more.endCursor
|
|
191
|
+
if (cursor === null || commentCursors.has(cursor)) return { code: 'unavailable', message: 'GitHub review comment pagination did not advance' }
|
|
192
|
+
commentCursors.add(cursor)
|
|
193
|
+
const next = await graphql(['-f', `query=${THREAD_COMMENTS_QUERY}`, '-f', `id=${node.id}`, '-f', `cursor=${cursor}`])
|
|
194
|
+
if ('code' in next) return next
|
|
195
|
+
const comment = commentsPageSchema.safeParse(next.body)
|
|
196
|
+
if (!comment.success) return unexpected
|
|
197
|
+
bytes += next.bytes
|
|
198
|
+
if (bytes > limits.maxOutputBytes) return result(true)
|
|
199
|
+
comments.push(...comment.data.data.node.comments.nodes)
|
|
200
|
+
more = comment.data.data.node.comments.pageInfo
|
|
201
|
+
}
|
|
202
|
+
if (comments.length > 0) threads.push(toThread(node, comments, headSha))
|
|
203
|
+
}
|
|
204
|
+
if (threads.length >= limits.maxReviewThreads || !page.pageInfo.hasNextPage) return result(page.pageInfo.hasNextPage)
|
|
205
|
+
const cursor = page.pageInfo.endCursor
|
|
206
|
+
if (cursor === null || cursors.has(cursor)) return { code: 'unavailable', message: 'GitHub review thread pagination did not advance' }
|
|
207
|
+
cursors.add(cursor)
|
|
208
|
+
const next = await graphql(['-f', `query=${REVIEW_THREADS_QUERY}`, '-f', `id=${pull.id}`, '-f', `cursor=${cursor}`,
|
|
209
|
+
'-F', `first=${Math.min(PAGE_SIZE, limits.maxReviewThreads - threads.length)}`])
|
|
210
|
+
if ('code' in next) return next
|
|
211
|
+
const following = nextPageSchema.safeParse(next.body)
|
|
212
|
+
if (!following.success) return unexpected
|
|
213
|
+
const movedLater = stale(following.data.data.node.headRefOid)
|
|
214
|
+
if (movedLater !== undefined) return movedLater
|
|
215
|
+
bytes += next.bytes
|
|
216
|
+
if (bytes > limits.maxOutputBytes) return result(true)
|
|
217
|
+
page = following.data.data.node.reviewThreads
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Map one thread. GitHub keeps a thread's `line` on the commit of its first comment, which stays an older commit for
|
|
223
|
+
* a comment written on a commit the head no longer is; such a thread, like one GitHub marks outdated or leaves
|
|
224
|
+
* without a line, has no position at `head`. A range whose start is on the other side of the diff keeps its last line.
|
|
225
|
+
*/
|
|
226
|
+
function toThread(node: ThreadNode, comments: readonly CommentNode[], head: string): ForgeReviewThread {
|
|
227
|
+
const root = node.root.nodes[0]
|
|
228
|
+
const line = node.subjectType !== 'FILE'
|
|
229
|
+
const sameSide = node.startDiffSide === null || node.startDiffSide === node.diffSide
|
|
230
|
+
const placed = line && !node.isOutdated && node.line !== null && root?.commit?.oid.toLowerCase() === head.toLowerCase()
|
|
231
|
+
return {
|
|
232
|
+
id: node.id as ForgeThreadId,
|
|
233
|
+
path: node.path,
|
|
234
|
+
side: node.diffSide === 'LEFT' ? 'L' : 'R',
|
|
235
|
+
subject: line ? 'line' : 'file',
|
|
236
|
+
current: placed && node.line !== null ? anchor(head, sameSide ? node.startLine : null, node.line) : null,
|
|
237
|
+
original: line && node.originalLine !== null && root?.originalCommit != null
|
|
238
|
+
? anchor(root.originalCommit.oid, sameSide ? node.originalStartLine : null, node.originalLine) : null,
|
|
239
|
+
diffHunk: root === undefined || root.diffHunk === '' ? null : root.diffHunk,
|
|
240
|
+
resolved: node.isResolved,
|
|
241
|
+
viewerCanReply: node.viewerCanReply,
|
|
242
|
+
viewerCanResolve: node.isResolved ? node.viewerCanUnresolve : node.viewerCanResolve,
|
|
243
|
+
comments: comments.map(toComment),
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function anchor(commit: string, start: number | null, end: number): ForgeAnchor {
|
|
248
|
+
return { commit, startLine: start !== null && start >= 1 && start <= end ? start : end, endLine: end }
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function toComment(node: CommentNode): ForgeReviewComment {
|
|
252
|
+
return {
|
|
253
|
+
id: node.id as ForgeCommentId,
|
|
254
|
+
author: node.author === null ? null : { login: node.author.login, avatarUrl: node.author.avatarUrl, bot: node.author.__typename === 'Bot' },
|
|
255
|
+
body: node.body,
|
|
256
|
+
createdAt: node.createdAt,
|
|
257
|
+
pending: node.state === 'PENDING',
|
|
258
|
+
url: node.url,
|
|
259
|
+
viewerCanEdit: node.viewerCanUpdate,
|
|
260
|
+
viewerCanDelete: node.viewerCanDelete,
|
|
261
|
+
}
|
|
262
|
+
}
|
package/src/urls.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/** GitHub remote URL and pull request URL parsing, and validation of the parts inlined into requests. */
|
|
2
|
+
|
|
3
|
+
import type { ChangeRequestRef, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge'
|
|
4
|
+
|
|
5
|
+
/** Characters GitHub permits in owner and repository names. */
|
|
6
|
+
const SEGMENT = /^[A-Za-z0-9_.-]+$/
|
|
7
|
+
|
|
8
|
+
/** A full SHA-1 or SHA-256 object name. */
|
|
9
|
+
const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i
|
|
10
|
+
|
|
11
|
+
/** Host, owner, and repository name addressed by a URL. */
|
|
12
|
+
export interface GitHubLocation {
|
|
13
|
+
/** Lowercase host name. */
|
|
14
|
+
readonly host: string
|
|
15
|
+
/** Owner as the URL spells it. */
|
|
16
|
+
readonly owner: string
|
|
17
|
+
/** Repository name without a `.git` suffix. */
|
|
18
|
+
readonly name: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Check one owner or repository name segment.
|
|
23
|
+
* @param value - candidate segment.
|
|
24
|
+
* @returns whether GitHub permits the segment and it is not a dot path.
|
|
25
|
+
*/
|
|
26
|
+
export function isSegment(value: string): boolean {
|
|
27
|
+
return SEGMENT.test(value) && value !== '.' && value !== '..'
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Validate a pull request before its owner, name, and number are inlined into
|
|
32
|
+
* a GraphQL document, a `gh` argument, or an API path.
|
|
33
|
+
* @param ref - pull request on a GitHub host.
|
|
34
|
+
* @returns its repository.
|
|
35
|
+
* @throws when the owner or name is not a permitted segment or the number is not a positive integer.
|
|
36
|
+
*/
|
|
37
|
+
export function checkedRepository(ref: ChangeRequestRef): ForgeRepository {
|
|
38
|
+
const { owner, name } = ref.repository
|
|
39
|
+
if (!isSegment(owner) || !isSegment(name)) throw new Error(`forge-github: invalid repository ${JSON.stringify(`${owner}/${name}`)}`)
|
|
40
|
+
if (!Number.isSafeInteger(ref.number) || ref.number <= 0) throw new Error(`forge-github: invalid pull request number ${ref.number}`)
|
|
41
|
+
return ref.repository
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Whether a value is a full commit object name that can be inlined into a request.
|
|
46
|
+
* @param value - candidate commit.
|
|
47
|
+
* @returns whether it is 40 or 64 hexadecimal digits.
|
|
48
|
+
*/
|
|
49
|
+
export function isCommit(value: string): boolean {
|
|
50
|
+
return COMMIT.test(value)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Parse a Git remote URL. Accepts `http(s)://[user@]host[:port]/owner/name`,
|
|
55
|
+
* `ssh://[user@]host[:port]/owner/name`, `git://host/owner/name`, and the
|
|
56
|
+
* scp-like `[user@]host:owner/name`, each with an optional `.git` suffix or
|
|
57
|
+
* trailing slash. HTTP(S) ports belong to the host identity; SSH and Git
|
|
58
|
+
* transport ports do not.
|
|
59
|
+
* @param url - fetch or push URL as Git reports it.
|
|
60
|
+
* @returns the location, or undefined for other URL shapes.
|
|
61
|
+
*/
|
|
62
|
+
export function parseRemoteUrl(url: string): GitHubLocation | undefined {
|
|
63
|
+
const trimmed = url.trim()
|
|
64
|
+
const scheme = /^https?:\/\/(?:[^@/]+@)?([^/:]+(?::\d+)?)\/(.+)$/i.exec(trimmed)
|
|
65
|
+
?? /^(?:ssh|git):\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/i.exec(trimmed)
|
|
66
|
+
const scp = scheme === null ? /^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.+)$/.exec(trimmed) : null
|
|
67
|
+
const match = scheme ?? scp
|
|
68
|
+
if (match === null) return undefined
|
|
69
|
+
const [, host = '', path = ''] = match
|
|
70
|
+
const parts = path.replace(/\/+$/, '').replace(/\.git$/i, '').split('/')
|
|
71
|
+
if (parts.length !== 2) return undefined
|
|
72
|
+
const [owner = '', name = ''] = parts
|
|
73
|
+
if (!isSegment(owner) || !isSegment(name)) return undefined
|
|
74
|
+
return { host: host.toLowerCase(), owner, name }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Parse a pull request web URL such as `https://github.com/owner/name/pull/12/files`.
|
|
79
|
+
* @param url - web URL of a pull request.
|
|
80
|
+
* @returns the location and number, or undefined for other URLs.
|
|
81
|
+
*/
|
|
82
|
+
export function parsePullRequestUrl(url: string): (GitHubLocation & { readonly number: number }) | undefined {
|
|
83
|
+
const match = /^https?:\/\/([^/]+)\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[/?#].*)?$/i.exec(url.trim())
|
|
84
|
+
if (match === null) return undefined
|
|
85
|
+
const [, host = '', owner = '', name = '', digits = ''] = match
|
|
86
|
+
const number = Number(digits)
|
|
87
|
+
if (!isSegment(owner) || !isSegment(name) || !Number.isSafeInteger(number) || number <= 0) return undefined
|
|
88
|
+
return { host: host.toLowerCase(), owner, name, number }
|
|
89
|
+
}
|