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

pullRequest.ts

800 lines34.5 KB

1import * as Schema from "effect/Schema";
2import * as HttpServerRespondable from "effect/unstable/http/HttpServerRespondable";
3import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
4​
5import {
6 IsoDateTime,
7 NonNegativeInt,
8 PositiveInt,
9 ProjectId,
10 TrimmedNonEmptyString,
11} from "./baseSchemas.ts";
12import { SourceControlProviderKind } from "./sourceControl.ts";
13​
14export const PullRequestInvolvement = Schema.Literals(["all", "reviewing", "authored"]);
15export type PullRequestInvolvement = typeof PullRequestInvolvement.Type;
16​
17export const PullRequestState = Schema.Literals(["open", "closed", "merged"]);
18export type PullRequestState = typeof PullRequestState.Type;
19​
20/**
21 * What a listing asks for, which is the three states a change request can be in plus the option
22 * to span them. Separate from `PullRequestState` because a change request is never "all" — only
23 * a request for one can be.
24 */
25export const PullRequestListState = Schema.Literals(["all", "open", "closed", "merged"]);
26export type PullRequestListState = typeof PullRequestListState.Type;
27​
28export const PullRequestMergeability = Schema.Literals(["mergeable", "conflicting", "unknown"]);
29export type PullRequestMergeability = typeof PullRequestMergeability.Type;
30​
31export const PullRequestMergeMethod = Schema.Literals(["merge", "squash", "rebase"]);
32export type PullRequestMergeMethod = typeof PullRequestMergeMethod.Type;
33​
34export const PullRequestAction = Schema.Literals(["merge", "ready", "draft", "close", "reopen"]);
35export type PullRequestAction = typeof PullRequestAction.Type;
36​
37export const PullRequestActor = Schema.Struct({
38 login: TrimmedNonEmptyString,
39 name: Schema.NullOr(Schema.String),
40 /** Null where a host does not report one, which is what the initials fall back to. */
41 avatarUrl: Schema.NullOr(Schema.String),
42});
43export type PullRequestActor = typeof PullRequestActor.Type;
44​
45export const PullRequestLabel = Schema.Struct({
46 name: TrimmedNonEmptyString,
47 color: Schema.NullOr(Schema.String),
48});
49export type PullRequestLabel = typeof PullRequestLabel.Type;
50​
51export const PullRequestCheckStatus = Schema.Literals([
52 "pending",
53 "success",
54 "failure",
55 "skipped",
56 "neutral",
57 "cancelled",
58]);
59export type PullRequestCheckStatus = typeof PullRequestCheckStatus.Type;
60​
61export const PullRequestCheck = Schema.Struct({
62 name: TrimmedNonEmptyString,
63 status: PullRequestCheckStatus,
64 description: Schema.NullOr(Schema.String),
65 url: Schema.NullOr(Schema.String),
66});
67export type PullRequestCheck = typeof PullRequestCheck.Type;
68​
69export const PullRequestCommentKind = Schema.Literals([
70 "issue-comment",
71 "review-comment",
72 "review",
73]);
74export type PullRequestCommentKind = typeof PullRequestCommentKind.Type;
75​
76export const PullRequestComment = Schema.Struct({
77 id: TrimmedNonEmptyString,
78 kind: PullRequestCommentKind,
79 author: Schema.NullOr(PullRequestActor),
80 body: Schema.String,
81 createdAt: IsoDateTime,
82 url: Schema.NullOr(Schema.String),
83 path: Schema.NullOr(Schema.String),
84 reviewState: Schema.NullOr(Schema.String),
85});
86export type PullRequestComment = typeof PullRequestComment.Type;
87​
88/**
89 * Which file a diff line belongs to: `left` is the version before the change, `right` the
90 * version after. A comment has to name one, because a unified diff shows both at once and the
91 * same line number means two different lines.
92 */
93export const PullRequestDiffSide = Schema.Literals(["left", "right"]);
94export type PullRequestDiffSide = typeof PullRequestDiffSide.Type;
95​
96/** What submitting a review says about the change, beyond the words in it. */
97export const PullRequestReviewVerdict = Schema.Literals(["comment", "approve", "request-changes"]);
98export type PullRequestReviewVerdict = typeof PullRequestReviewVerdict.Type;
99​
100export const PullRequestThreadComment = Schema.Struct({
101 id: TrimmedNonEmptyString,
102 author: Schema.NullOr(PullRequestActor),
103 body: Schema.String,
104 createdAt: IsoDateTime,
105 url: Schema.NullOr(Schema.String),
106});
107export type PullRequestThreadComment = typeof PullRequestThreadComment.Type;
108​
109/**
110 * A conversation anchored to a line of the diff. The detail carries these alongside `comments`
111 * rather than instead of them: the timeline wants one flat, chronological list, and the diff
112 * wants whole threads pinned to their line — the same remarks, read two different ways.
113 */
114export const PullRequestReviewThread = Schema.Struct({
115 id: TrimmedNonEmptyString,
116 path: TrimmedNonEmptyString,
117 /** Null when the host anchors the thread to a file rather than to a line. */
118 line: Schema.NullOr(PositiveInt),
119 side: PullRequestDiffSide,
120 isResolved: Schema.Boolean,
121 /**
122 * The line the thread was written against is no longer in the diff, so it cannot be shown
123 * against the code. Such a thread is listed separately rather than pinned to the wrong line.
124 */
125 isOutdated: Schema.Boolean,
126 comments: Schema.Array(PullRequestThreadComment),
127});
128export type PullRequestReviewThread = typeof PullRequestReviewThread.Type;
129​
130/**
131 * Whether a reviewer is a person or a group of them the host addresses as one. GitHub is the only
132 * host here that takes a review request for a team; the others name individuals only, so nothing
133 * they report is ever anything but a user.
134 */
135export const PullRequestReviewerKind = Schema.Literals(["user", "team"]);
136export type PullRequestReviewerKind = typeof PullRequestReviewerKind.Type;
137​
138/**
139 * Somebody a review may be asked of. Carries the actor fields so the menu shows the same face and
140 * handle the rest of the page does, and a team wears them too — its slug stands in for a login.
141 */
142export const PullRequestReviewerCandidate = Schema.Struct({
143 ...PullRequestActor.fields,
144 /**
145 * How the host addresses this reviewer when a review is requested, which is not always the
146 * handle it shows: GitHub takes a login or a team slug, GitLab a numeric user id, Bitbucket an
147 * account uuid. Opaque to the page, which sends back whatever the candidate arrived with.
148 */
149 id: TrimmedNonEmptyString,
150 kind: PullRequestReviewerKind,
151 /** A review has already been asked of them, so pressing them takes the request back. */
152 isRequested: Schema.Boolean,
153});
154export type PullRequestReviewerCandidate = typeof PullRequestReviewerCandidate.Type;
155​
156export const PullRequestReviewerCandidateList = Schema.Struct({
157 /** Never includes the author: nobody is asked to review their own change request. */
158 candidates: Schema.Array(PullRequestReviewerCandidate),
159 /**
160 * The host has more people with access than the read asked for, so somebody missing from the
161 * menu may still be somebody this change request can be sent to. Nothing is wrong with the
162 * list; it is simply not all of it.
163 */
164 truncated: Schema.Boolean,
165});
166export type PullRequestReviewerCandidateList = typeof PullRequestReviewerCandidateList.Type;
167​
168export const PullRequestCommit = Schema.Struct({
169 oid: TrimmedNonEmptyString,
170 messageHeadline: Schema.String,
171 committedDate: IsoDateTime,
172 /** Per-commit line counts where the host can return them without a request per commit. */
173 additions: Schema.optional(NonNegativeInt),
174 deletions: Schema.optional(NonNegativeInt),
175 /**
176 * Everyone the host attributes the commit to. Optional because older servers and hosts that
177 * do not expose commit authors still produce a useful timeline entry.
178 */
179 authors: Schema.optional(Schema.Array(PullRequestActor)),
180});
181export type PullRequestCommit = typeof PullRequestCommit.Type;
182​
183/**
184 * What a host can do with a review, which is where the four differ most. GitLab has no way to
185 * say "changes requested", and Azure DevOps exposes no diff through its CLI, so it has no lines
186 * to write against at all.
187 */
188export const PullRequestReviewCapabilities = Schema.Struct({
189 /** A new comment can be anchored to a line of the diff. */
190 inlineComment: Schema.Boolean,
191 /** An existing thread can be replied to. */
192 reply: Schema.Boolean,
193 /** A thread can be marked resolved, and unresolved again. */
194 resolve: Schema.Boolean,
195 /** The verdicts a submitted review can carry. Empty means reviews cannot be submitted. */
196 verdicts: Schema.Array(PullRequestReviewVerdict),
197});
198export type PullRequestReviewCapabilities = typeof PullRequestReviewCapabilities.Type;
199​
200/**
201 * What a host can do about who reviews. The two are independent: a host can take a request without
202 * publishing who may receive one, which is Azure DevOps.
203 */
204export const PullRequestReviewerCapabilities = Schema.Struct({
205 /** A review can be asked of somebody, and the request taken back. */
206 request: Schema.Boolean,
207 /**
208 * The people who may be asked can be listed. False where the host has no such list to give,
209 * which leaves the page to take a name rather than offer a menu — a guessed list would be worse,
210 * because a name missing from it reads as a name that cannot be asked.
211 */
212 listCandidates: Schema.Boolean,
213});
214export type PullRequestReviewerCapabilities = typeof PullRequestReviewerCapabilities.Type;
215​
216/**
217 * What a provider can actually do, so a surface can hide what is missing rather than offer an
218 * action that would fail. Every provider fills this in for itself; nothing is assumed.
219 *
220 * Hosts differ more than they look: Azure DevOps exposes no patch through its CLI, and
221 * Bitbucket has no endpoint that reopens a declined pull request. Both would otherwise be dead
222 * buttons.
223 */
224export const PullRequestCapabilities = Schema.Struct({
225 /** A unified patch can be fetched for the change request. */
226 diff: Schema.Boolean,
227 /** A comment can be posted, and the conversation read back. */
228 comment: Schema.Boolean,
229 /** The actions this host can carry out; anything absent is never offered. */
230 actions: Schema.Array(PullRequestAction),
231 /** Merge strategies the provider itself offers, before repository settings narrow them. */
232 mergeMethods: Schema.Array(PullRequestMergeMethod),
233 /**
234 * The host can narrow a listing by free text. False means it answers unnarrowed and whoever
235 * asked has to do the narrowing — which is a different promise, so the page is told rather
236 * than left to show every change request on that host as a search result.
237 */
238 search: Schema.Boolean,
239 review: PullRequestReviewCapabilities,
240 reviewers: PullRequestReviewerCapabilities,
241});
242export type PullRequestCapabilities = typeof PullRequestCapabilities.Type;
243​
244/**
245 * What the signed-in account may do with this change request, which is a different question from
246 * `capabilities`: that says what the host is able to do at all, and this says whether this viewer
247 * is allowed to ask for it. A host that merges pull requests still will not let a stranger merge
248 * one, so a control belongs on the page only where the two agree.
249 *
250 * A permission the host reports nothing about is granted rather than withheld. Hiding a control
251 * from someone who may in fact use it leaves them no way through and no reason given, while
252 * offering one they may not use ends in the host's own refusal — which at least says why.
253 */
254export const PullRequestViewerPermissions = Schema.Struct({
255 /** Which of the actions this viewer may take; anything absent is theirs to look at only. */
256 actions: Schema.Array(PullRequestAction),
257 /** This viewer may write a remark: a comment, a reply, or a note against a line. */
258 comment: Schema.Boolean,
259 /** This viewer may mark a review conversation resolved, and unresolved again. */
260 resolve: Schema.Boolean,
261 /** The verdicts this viewer may submit a review with. Empty means they may not review. */
262 verdicts: Schema.Array(PullRequestReviewVerdict),
263 /** This viewer may ask somebody for a review, and take the request back again. */
264 requestReviewers: Schema.Boolean,
265});
266export type PullRequestViewerPermissions = typeof PullRequestViewerPermissions.Type;
267​
268export const PullRequestMergeCapabilities = Schema.Struct({
269 merge: Schema.Boolean,
270 squash: Schema.Boolean,
271 rebase: Schema.Boolean,
272});
273export type PullRequestMergeCapabilities = typeof PullRequestMergeCapabilities.Type;
274​
275export const PullRequestListEntry = Schema.Struct({
276 provider: SourceControlProviderKind,
277 /**
278 * The host below which `repository` is addressed, so the same provider kind can serve more
279 * than one account — github.com and a GitHub Enterprise install are different identities.
280 */
281 host: TrimmedNonEmptyString,
282 projectId: ProjectId,
283 projectTitle: TrimmedNonEmptyString,
284 repository: TrimmedNonEmptyString,
285 number: PositiveInt,
286 title: TrimmedNonEmptyString,
287 url: TrimmedNonEmptyString,
288 author: Schema.NullOr(PullRequestActor),
289 headBranch: TrimmedNonEmptyString,
290 baseBranch: TrimmedNonEmptyString,
291 state: PullRequestState,
292 isDraft: Schema.Boolean,
293 mergeability: PullRequestMergeability,
294 /**
295 * Zero where the host has not been asked for the counts yet, which on GitHub is every row a
296 * listing hands over: they are read afterwards, through `PullRequestListStatsInput`. Zero is
297 * what a host that reports no counts at all has always sent, and what the page already draws
298 * as no stat rather than as an empty change.
299 */
300 additions: NonNegativeInt,
301 deletions: NonNegativeInt,
302 createdAt: IsoDateTime,
303 updatedAt: IsoDateTime,
304 viewerReviewRequested: Schema.Boolean,
305 labels: Schema.Array(PullRequestLabel),
306});
307export type PullRequestListEntry = typeof PullRequestListEntry.Type;
308​
309/**
310 * Where each repository a listing already reached carries on from, keyed `"<host> <repository>"`
311 * — which is how a listing tells two repositories apart, since the same `owner/repo` exists on
312 * github.com and on an Enterprise install at once.
313 *
314 * Each value is opaque: only the provider that issued one knows what it means, and the page hands
315 * back exactly what it was given rather than composing one.
316 */
317export const PullRequestListCursors = Schema.Record(
318 TrimmedNonEmptyString,
319 // Bounded because it arrives from the page and is unfolded into a host's own filter.
320 TrimmedNonEmptyString.check(Schema.isMaxLength(4096)),
321);
322export type PullRequestListCursors = typeof PullRequestListCursors.Type;
323​
324export const PullRequestListInput = Schema.Struct({
325 state: PullRequestListState,
326 involvement: Schema.optional(PullRequestInvolvement),
327 projectId: Schema.optional(ProjectId),
328 /**
329 * Narrows the listing to one host, named as the host itself rather than as its provider kind:
330 * github.com and a GitHub Enterprise install are two accounts, and a kind cannot tell them
331 * apart. Absent means every host the workspace has.
332 */
333 host: Schema.optional(TrimmedNonEmptyString),
334 /** Rows to return per repository, which with a continuation is rows per slice. */
335 limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 500 }))),
336 /**
337 * Carry on from an answer already on the page rather than read the listing again. Only the
338 * repositories named here are read, one slice each — which is what makes a further page cost
339 * one slice rather than every repository over again at a larger size. A repository the page has
340 * enough of is simply left out.
341 *
342 * Absent asks for the listing from the top, which is what raising `limit` alone has always
343 * done and still does.
344 */
345 cursors: Schema.optional(PullRequestListCursors),
346 /**
347 * Free text the hosts themselves are asked to match, rather than a filter over the rows that
348 * have already arrived: a listing only ever holds a page per repository, so a search that
349 * never leaves the client can only find what happened to be loaded. What a match means is the
350 * host's own business — GitHub reads a body, GitLab a description — and a host with no text
351 * filter answers unnarrowed rather than pretending.
352 *
353 * Bounded because it travels into a CLI argument and a query string, and no host makes
354 * anything of a search term this long.
355 */
356 query: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(200))),
357});
358export type PullRequestListInput = typeof PullRequestListInput.Type;
359​
360/**
361 * A host the workspace has projects on, and whether it can be read right now. Drives the host
362 * switcher and explains projects the list leaves out.
363 *
364 * One per host rather than per provider kind, because signing in is a question about the host:
365 * a workspace can hold repositories on github.com and on a GitHub Enterprise install at once,
366 * and the two are separate accounts that succeed and fail independently.
367 */
368export const PullRequestProviderSummary = Schema.Struct({
369 host: TrimmedNonEmptyString,
370 kind: SourceControlProviderKind,
371 /** False where a search has to be applied to the rows after they arrive. */
372 searchesOnHost: Schema.Boolean,
373 projectCount: PositiveInt,
374 /** False when the provider's CLI or credentials are missing, with `detail` saying which. */
375 configured: Schema.Boolean,
376 detail: Schema.NullOr(TrimmedNonEmptyString),
377});
378export type PullRequestProviderSummary = typeof PullRequestProviderSummary.Type;
379​
380/** One project whose repository could not be read; healthy projects still return entries. */
381export const PullRequestListProjectError = Schema.Struct({
382 projectId: ProjectId,
383 projectTitle: TrimmedNonEmptyString,
384 message: TrimmedNonEmptyString,
385});
386export type PullRequestListProjectError = typeof PullRequestListProjectError.Type;
387​
388export const PullRequestListResult = Schema.Struct({
389 /**
390 * The signed-in account per host, with `host owner/repository` entries where one host uses
391 * several credentials. A target that could not be read is absent rather than
392 * present-and-undefined, because an open-keyed record cannot carry an optional value through
393 * the JSON codec.
394 */
395 viewers: Schema.Record(TrimmedNonEmptyString, TrimmedNonEmptyString),
396 providers: Schema.Array(PullRequestProviderSummary),
397 /**
398 * By update, newest first, across every repository this answer covers. A page that appends a
399 * continuation sorts what it then holds the same way: a repository's next slice is older than
400 * that repository's last row, but can still be newer than another repository's.
401 */
402 entries: Schema.Array(PullRequestListEntry),
403 errors: Schema.Array(PullRequestListProjectError),
404 /** At least one repository hit the per-repository listing cap. */
405 truncated: Schema.Boolean,
406 /**
407 * Where each repository carries on, to be sent straight back as `cursors`. A repository is
408 * absent from this once it has nothing more to give, and also where its host could not be asked
409 * in an order a continuation means anything in — so an empty record beside `truncated` means
410 * more rows are only reachable by raising `limit`, the way they always were.
411 */
412 nextCursors: PullRequestListCursors,
413});
414export type PullRequestListResult = typeof PullRequestListResult.Type;
415​
416export const PullRequestRef = Schema.Struct({
417 projectId: ProjectId,
418 repository: TrimmedNonEmptyString,
419 number: PositiveInt,
420});
421export type PullRequestRef = typeof PullRequestRef.Type;
422​
423/**
424 * One row's line counts, read after the listing rather than inside it. On GitHub the pair is
425 * 40-60% of the wall clock of the search that answers the whole page — measured over twelve
426 * repositories, 7.1s with it and 4.0s without — for two small numbers at the end of a row.
427 *
428 * So the listing answers without them and the page asks for them next, which is what puts the
429 * rows on screen at the speed of everything else on them.
430 */
431export const PullRequestDiffStat = Schema.Struct({
432 projectId: ProjectId,
433 repository: TrimmedNonEmptyString,
434 number: PositiveInt,
435 additions: NonNegativeInt,
436 deletions: NonNegativeInt,
437});
438export type PullRequestDiffStat = typeof PullRequestDiffStat.Type;
439​
440/**
441 * The rows whose line counts are wanted, which is the rows the page is showing.
442 *
443 * Bounded at the largest listing a page can hold, since each ref becomes a lookup of its own on
444 * the host.
445 */
446export const PullRequestListStatsInput = Schema.Struct({
447 refs: Schema.Array(PullRequestRef).check(Schema.isMaxLength(500)),
448});
449export type PullRequestListStatsInput = typeof PullRequestListStatsInput.Type;
450​
451/**
452 * Only the rows that could be answered for. A host with no batched stat read of its own — every
453 * one but GitHub, which all report the counts in the listing itself — is simply absent here, and
454 * the numbers its listing already carried stand.
455 */
456export const PullRequestListStatsResult = Schema.Struct({
457 stats: Schema.Array(PullRequestDiffStat),
458});
459export type PullRequestListStatsResult = typeof PullRequestListStatsResult.Type;
460​
461/**
462 * Forget what the server has cached, so the next read asks the host. With a reference it
463 * forgets that one change request's detail and diff; without one it forgets the listings.
464 * A separate request rather than a flag on the reads, so an explicit "refresh" one person
465 * presses is the only thing that spends host requests — every ordinary read shares.
466 */
467export const PullRequestInvalidateInput = Schema.Struct({
468 reference: Schema.optional(PullRequestRef),
469});
470export type PullRequestInvalidateInput = typeof PullRequestInvalidateInput.Type;
471​
472export const PullRequestDetail = Schema.Struct({
473 provider: SourceControlProviderKind,
474 capabilities: PullRequestCapabilities,
475 /** What this viewer may do, which `capabilities` says nothing about. Both narrow the page. */
476 viewerPermissions: PullRequestViewerPermissions,
477 projectId: ProjectId,
478 projectTitle: TrimmedNonEmptyString,
479 workspaceRoot: TrimmedNonEmptyString,
480 repository: TrimmedNonEmptyString,
481 number: PositiveInt,
482 title: TrimmedNonEmptyString,
483 body: Schema.String,
484 url: TrimmedNonEmptyString,
485 author: Schema.NullOr(PullRequestActor),
486 state: PullRequestState,
487 isDraft: Schema.Boolean,
488 mergeability: PullRequestMergeability,
489 additions: NonNegativeInt,
490 deletions: NonNegativeInt,
491 changedFiles: NonNegativeInt,
492 headBranch: TrimmedNonEmptyString,
493 baseBranch: TrimmedNonEmptyString,
494 createdAt: IsoDateTime,
495 updatedAt: IsoDateTime,
496 mergedAt: Schema.NullOr(IsoDateTime),
497 closedAt: Schema.NullOr(IsoDateTime),
498 reviewers: Schema.Array(PullRequestActor),
499 labels: Schema.Array(PullRequestLabel),
500 checks: Schema.Array(PullRequestCheck),
501 mergeCapabilities: PullRequestMergeCapabilities,
502});
503export type PullRequestDetail = typeof PullRequestDetail.Type;
504​
505/**
506 * The slower, conversation-shaped half of a change request. It is read independently from the
507 * core detail so a host with a deeply paginated review history cannot hold the title, body,
508 * checks, and actions off screen. `author` and `reviewers` are optional enrichments: GitHub's
509 * conversation query carries avatars and completed reviewers that its basic detail does not.
510 */
511export const PullRequestActivity = Schema.Struct({
512 author: Schema.optional(Schema.NullOr(PullRequestActor)),
513 reviewers: Schema.optional(Schema.Array(PullRequestActor)),
514 comments: Schema.Array(PullRequestComment),
515 /**
516 * How many remarks the host itself counts in the conversation, which is the number a surface
517 * showing a count has to show: `comments` carries what was read, and a reader who can see 225
518 * on the host is not reassured by a page that says 10. Never less than `comments` holds, and
519 * equal to it wherever the host was read to the end.
520 */
521 commentCount: NonNegativeInt,
522 /**
523 * The read stopped at a bound of its own before the host ran out, so `comments` holds less
524 * than `commentCount` counts. Nothing else: a conversation read whole is never truncated,
525 * however long it is.
526 */
527 commentsTruncated: Schema.Boolean,
528 reviewThreads: Schema.Array(PullRequestReviewThread),
529 commits: Schema.Array(PullRequestCommit),
530});
531export type PullRequestActivity = typeof PullRequestActivity.Type;
532​
533/** The complete detail shape after the independently loaded activity has been applied. */
534export const PullRequestDetailView = Schema.Struct({
535 ...PullRequestDetail.fields,
536 ...PullRequestActivity.fields,
537 // A composed view always has the core identity fields, even when the activity did not enrich
538 // them. Re-declare them as required after the activity's optional overrides.
539 author: Schema.NullOr(PullRequestActor),
540 reviewers: Schema.Array(PullRequestActor),
541});
542export type PullRequestDetailView = typeof PullRequestDetailView.Type;
543​
544/**
545 * A diff arrives a slice at a time, because a large change is more than any host will hand over
546 * at once — GitHub refuses outright past 300 files — and more than a viewer can lay out in one
547 * go. A slice is a whole number of files, never a file cut in half, so each one parses on its
548 * own and the reader can start on the first while the rest is still coming.
549 */
550export const PullRequestDiffInput = Schema.Struct({
551 ...PullRequestRef.fields,
552 /**
553 * Where to carry on from. Absent asks for the first slice. Opaque to the reader: each host
554 * counts its files its own way, and only the provider that issued one knows what it means.
555 */
556 cursor: Schema.optional(TrimmedNonEmptyString),
557 /**
558 * One commit of the change rather than the whole of it. A large pull request is easier to
559 * read a commit at a time, and the author's own commits are the boundaries they chose.
560 */
561 commit: Schema.optional(TrimmedNonEmptyString),
562});
563export type PullRequestDiffInput = typeof PullRequestDiffInput.Type;
564​
565export const PullRequestDiffResult = Schema.Struct({
566 patch: Schema.String,
567 /**
568 * Something inside this slice could not be shown — a binary file, or a hunk the host declined
569 * to inline. Not the same as there being more slices, which `nextCursor` answers.
570 */
571 truncated: Schema.Boolean,
572 /** Where the next slice starts, or null once the diff is whole. */
573 nextCursor: Schema.NullOr(TrimmedNonEmptyString),
574});
575export type PullRequestDiffResult = typeof PullRequestDiffResult.Type;
576​
577/** The complete old and new files Pierre needs to open omitted context in a host-backed patch. */
578export const PullRequestDiffFileContentsInput = Schema.Struct({
579 ...PullRequestRef.fields,
580 /** One commit's own comparison; absent means the whole change request. */
581 commit: Schema.optional(TrimmedNonEmptyString),
582 changeType: Schema.Literals(["change", "rename-pure", "rename-changed", "new", "deleted"]),
583 oldPath: TrimmedNonEmptyString,
584 newPath: TrimmedNonEmptyString,
585});
586export type PullRequestDiffFileContentsInput = typeof PullRequestDiffFileContentsInput.Type;
587​
588export const PullRequestDiffFileContentsResult = Schema.Struct({
589 oldContents: Schema.String,
590 newContents: Schema.String,
591});
592export type PullRequestDiffFileContentsResult = typeof PullRequestDiffFileContentsResult.Type;
593​
594export const PullRequestActionInput = Schema.Struct({
595 ...PullRequestRef.fields,
596 action: PullRequestAction,
597 mergeMethod: Schema.optional(PullRequestMergeMethod),
598});
599export type PullRequestActionInput = typeof PullRequestActionInput.Type;
600​
601// Not trimmed: the body is markdown, where leading spaces open a code block and two trailing
602// spaces are a line break. GitHub rejects bodies past 65536 characters, so that bound is
603// enforced here to keep oversized payloads off the wire and out of subprocess plumbing; the
604// service rejects a body that is only whitespace.
605const CommentBody = Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536));
606​
607export const PullRequestCommentInput = Schema.Struct({
608 ...PullRequestRef.fields,
609 body: CommentBody,
610});
611export type PullRequestCommentInput = typeof PullRequestCommentInput.Type;
612​
613/** One remark in a review that has not been sent yet, anchored to a line of the diff. */
614export const PullRequestReviewCommentDraft = Schema.Struct({
615 path: TrimmedNonEmptyString,
616 /**
617 * What the file was called before the change, sent only when it differs. GitLab resolves a
618 * position against both sides of the diff, so a comment on a renamed file needs both names;
619 * the hosts that address a comment by one path ignore this.
620 */
621 oldPath: Schema.optional(TrimmedNonEmptyString),
622 line: PositiveInt,
623 side: PullRequestDiffSide,
624 body: CommentBody,
625});
626export type PullRequestReviewCommentDraft = typeof PullRequestReviewCommentDraft.Type;
627​
628/**
629 * A whole review, sent in one go. The line comments travel with the verdict rather than being
630 * posted as they are written, so a half-finished review is never visible to anyone else — and
631 * so hosts with no notion of a pending review behave the same as the ones that have it.
632 */
633export const PullRequestSubmitReviewInput = Schema.Struct({
634 ...PullRequestRef.fields,
635 verdict: PullRequestReviewVerdict,
636 /** The review's own words. May be empty, which is how an approval with no remarks is sent. */
637 body: Schema.String.check(Schema.isMaxLength(65_536)),
638 comments: Schema.Array(PullRequestReviewCommentDraft),
639});
640export type PullRequestSubmitReviewInput = typeof PullRequestSubmitReviewInput.Type;
641​
642export const PullRequestThreadReplyInput = Schema.Struct({
643 ...PullRequestRef.fields,
644 threadId: TrimmedNonEmptyString,
645 body: CommentBody,
646});
647export type PullRequestThreadReplyInput = typeof PullRequestThreadReplyInput.Type;
648​
649export const PullRequestThreadResolutionInput = Schema.Struct({
650 ...PullRequestRef.fields,
651 threadId: TrimmedNonEmptyString,
652 resolved: Schema.Boolean,
653});
654export type PullRequestThreadResolutionInput = typeof PullRequestThreadResolutionInput.Type;
655​
656/**
657 * Asking for a review and taking the request back are one operation with `requested` turned
658 * around, and asking again somebody who has already reviewed is what a re-request is — so that is
659 * the same operation once more rather than a third one.
660 */
661export const PullRequestReviewerRequestInput = Schema.Struct({
662 ...PullRequestRef.fields,
663 /**
664 * Who, as the candidate list named them. Bounded because every host bounds it as well — GitHub
665 * refuses past fifteen — and because these travel into a request body a page composed.
666 */
667 reviewers: Schema.Array(
668 Schema.Struct({ id: TrimmedNonEmptyString, kind: PullRequestReviewerKind }),
669 ).check(Schema.isMinLength(1), Schema.isMaxLength(25)),
670 requested: Schema.Boolean,
671});
672export type PullRequestReviewerRequestInput = typeof PullRequestReviewerRequestInput.Type;
673​
674export const PullRequestUnavailableReason = Schema.Literals([
675 "cli-missing",
676 "cli-unauthenticated",
677 "provider-unsupported",
678]);
679export type PullRequestUnavailableReason = typeof PullRequestUnavailableReason.Type;
680​
681/**
682 * What each host needs before it can be read, so a failure names the fix rather than the
683 * symptom. Bitbucket is credentials on the server rather than a signed-in CLI, which is why
684 * these are whole sentences instead of a tool name to interpolate.
685 */
686const PROVIDER_REQUIREMENT: Partial<
687 Record<SourceControlProviderKind, { readonly missing: string; readonly unauthenticated: string }>
688> = {
689 github: {
690 missing:
691 "GitHub CLI (`gh`) is required to browse change requests on this host. Install it from https://cli.github.com/ and reload.",
692 unauthenticated: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
693 },
694 gitlab: {
695 missing:
696 "GitLab CLI (`glab`) is required to browse change requests on this host. Install it from https://gitlab.com/gitlab-org/cli and reload.",
697 unauthenticated: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
698 },
699 "azure-devops": {
700 missing:
701 "Azure CLI (`az`) with the Azure DevOps extension is required. Install `az`, then run `az extension add --name azure-devops`.",
702 unauthenticated: "Azure CLI is not signed in. Run `az login` and retry.",
703 },
704 bitbucket: {
705 missing:
706 "Bitbucket needs API credentials on the server. Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.",
707 unauthenticated:
708 "Bitbucket rejected the configured credentials. Check T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN.",
709 },
710};
711​
712/**
713 * The host a project's repository is addressed below. `canonicalKey` is the normalized remote,
714 * `host/owner/repo`, so its first segment is the host; the provider kind stands in when there is
715 * no key to read, which keeps one bucket per kind for identities recorded before it existed.
716 *
717 * Shared between the server and the page so both bucket a workspace the same way — the page
718 * knows its hosts before the listing answers, and the two must agree on what they are called.
719 */
720export function pullRequestHostOf(
721 identity: { readonly canonicalKey?: string | undefined } | null | undefined,
722 kind: SourceControlProviderKind,
723): string {
724 const host = identity?.canonicalKey?.split("/")[0]?.trim();
725 return host === undefined || host.length === 0 ? kind : host.toLowerCase();
727​
728/**
729 * What a host needs before it can be read, as a sentence to show wherever that host is reported
730 * as unusable — the whole page when nothing can be read, and one entry in the host switcher when
731 * only that host cannot. Null when the reason is not about setting a host up.
732 */
733export function pullRequestProviderRequirement(
734 provider: SourceControlProviderKind,
735 reason: PullRequestUnavailableReason,
736): string | null {
737 const requirement = PROVIDER_REQUIREMENT[provider];
738 if (requirement === undefined) return null;
739 switch (reason) {
740 case "cli-missing":
741 return requirement.missing;
742 case "cli-unauthenticated":
743 return requirement.unauthenticated;
744 case "provider-unsupported":
745 return null;
746 }
748​
749/**
750 * The feature is switched off entirely. The message is derived from `reason` and the host
751 * rather than from whatever the CLI printed, so it stays a stable sentence the UI can show
752 * as-is; the underlying failure travels in `cause` (absent for `provider-unsupported`, which
753 * has none).
754 */
755export class PullRequestUnavailableError extends Schema.TaggedErrorClass<PullRequestUnavailableError>()(
756 "PullRequestUnavailableError",
757 {
758 reason: PullRequestUnavailableReason,
759 provider: Schema.optional(SourceControlProviderKind),
760 cause: Schema.optional(Schema.Defect()),
761 },
762 { httpApiStatus: 503 },
763) {
764 [HttpServerRespondable.symbol]() {
765 return HttpServerResponse.schemaJson(PullRequestUnavailableError)(this, { status: 503 });
766 }
767​
768 override get message(): string {
769 const requirement =
770 this.provider === undefined ? undefined : PROVIDER_REQUIREMENT[this.provider];
771 switch (this.reason) {
772 case "cli-missing":
773 return (
774 requirement?.missing ?? "The tool this host is read through is not installed or set up."
775 );
776 case "cli-unauthenticated":
777 return requirement?.unauthenticated ?? "This host has no working credentials.";
778 case "provider-unsupported":
779 return "Change requests cannot be browsed for this project's host yet.";
780 }
781 }
783​
784export class PullRequestOperationError extends Schema.TaggedErrorClass<PullRequestOperationError>()(
785 "PullRequestOperationError",
786 {
787 operation: Schema.String,
788 detail: TrimmedNonEmptyString,
789 cause: Schema.optional(Schema.Defect()),
790 },
791 { httpApiStatus: 502 },
792) {
793 [HttpServerRespondable.symbol]() {
794 return HttpServerResponse.schemaJson(PullRequestOperationError)(this, { status: 502 });
795 }
796​
797 override get message(): string {
798 return `Pull request operation ${this.operation} failed: ${this.detail}`;
799 }