Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
6import {
7 NonNegativeInt,
8 resolvePullRequestAuthorFilter,
9 TrimmedNonEmptyString,
10 type PullRequestCapabilities,
11 type PullRequestListFilters,
12 type PullRequestStackHead,
13} from "@t3tools/contracts";
14import {
15 PullRequestProviderError,
16 type ProviderRepositoryRef,
17 type PullRequestProviderApi,
18} from "@t3tools/source-control-core/server/PullRequestProvider";
19
20import * as GitCafeApi from "./GitCafeApi.ts";
21import * as GitCafeHosts from "./gitCafeHosts.ts";
22import * as Json from "./gitCafePullRequestJson.ts";
23import { definition } from "../shared/definition.ts";
24
25const CAPABILITIES: PullRequestCapabilities = {
26 diff: true,
27 comment: true,
28 actions: [...definition.changeRequestActions],
29 mergeMethods: ["merge", "squash", "rebase"],
30 // Branch updates restack every layer above the target.
31 updateMethods: ["rebase"],
32 search: true,
33 stacks: true,
34 stackActions: true,
35 reactions: true,
36 labels: true,
37 // Line comments go through GitCafe's review drafts, which arrive with revision fencing.
38 review: {
39 inlineComment: false,
40 reply: true,
41 resolve: true,
42 verdicts: ["approve", "request-changes", "comment"],
43 },
44 reviewers: { request: true, listCandidates: true },
45 edit: { changeRequest: true, comment: true },
46};
47
48const PAGE_SIZE = 100;
49const MAX_PAGES = 10;
50/**
51 * Pages read looking for a GitHub-synced author before a listing filtered by them gives up. The
52 * login only appears on their pull requests, so one older than this many is out of reach.
53 */
54const AUTHOR_DISCOVERY_PAGES = 5;
55/** Bounds the logins remembered from listings; a repository's authors fit many times over. */
56const KNOWN_AUTHORS_LIMIT = 10_000;
57/** GitCafe's cap on paths per `/diff-files` read, and so one diff page. */
58const DIFF_FILES_BATCH = 64;
59/** Changed-path pages carry no hunks, so they can be read in larger pages. */
60const CHANGES_PAGE_LIMIT = 500;
61/** Line totals require hunk reads; omit them for large PRs. */
62const LINE_STATS_MAX_FILES = DIFF_FILES_BATCH * 4;
63const MAX_CHANGE_PAGES = 20;
64const LINE_STATS_CACHE_SIZE = 256;
65
66const chunk = <A>(items: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> =>
67 Array.from({ length: Math.ceil(items.length / size) }, (_, index) =>
68 items.slice(index * size, (index + 1) * size),
69 );
70
71const detailablePaths = (files: ReadonlyArray<Json.GitCafeDiffFile>) =>
72 files.filter((file) => !file.binary && !file.tooLarge).map((file) => file.path);
73
74const mergeStrategyOpen = (status: typeof Status.Type, strategy: string) =>
75 status.merge.permitted !== false &&
76 status.merge.strategies.includes(strategy) &&
77 !(status.merge.blockers ?? []).some((blocker) =>
78 (blocker.blockedStrategies ?? []).includes(strategy),
79 );
80
81const Id = TrimmedNonEmptyString.check(Schema.isPattern(/^[A-Za-z0-9_-]+$/u));
82const isId = Schema.is(Id);
83const isApiError = Schema.is(GitCafeApi.GitCafeApiError);
84const Principal = Schema.Struct({ actorId: TrimmedNonEmptyString, handle: TrimmedNonEmptyString });
85const User = Schema.Struct({ actorId: TrimmedNonEmptyString });
86const Written = Schema.Struct({ id: Id });
87const Versioned = Schema.Struct({ version: NonNegativeInt });
88const CommentDetail = Schema.Struct({ id: Id, version: NonNegativeInt });
89const Status = Schema.Struct({
90 merge: Schema.Struct({
91 // The API reference lists "unknown" and "conflicting", but git.cafe also sends "none" and
92 // "pending", so any state is read and only the known ones are mapped.
93 conflicts: Schema.String,
94 fastForward: Schema.NullOr(Schema.Boolean),
95 strategies: Schema.Array(Schema.String),
96 permitted: Schema.optional(Schema.Boolean),
97 reasons: Schema.optional(Schema.Array(Schema.String)),
98 blockers: Schema.optional(
99 Schema.Array(
100 Schema.Struct({ blockedStrategies: Schema.optional(Schema.Array(Schema.String)) }),
101 ),
102 ),
103 }),
104 checks: Schema.Struct({
105 pending: NonNegativeInt,
106 failing: NonNegativeInt,
107 total: NonNegativeInt,
108 }),
109});
110/** A merge GitCafe accepted runs on afterwards: on GitHub for a synced pull request, or natively. */
111const MERGE_IN_FLIGHT = new Set(["provider-merge-pending", "native-operation-pending"]);
112const Listed = Schema.Struct({
113 items: Schema.Array(Schema.Struct({ id: TrimmedNonEmptyString })),
114 next: Schema.NullOr(Schema.String),
115});
116const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
117const BranchCommit = Schema.Struct({ oid: TrimmedNonEmptyString });
118const CommitOid = Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u));
119const isCommitOid = Schema.is(CommitOid);
120const SourceSnapshot = Schema.Struct({
121 version: NonNegativeInt,
122 headOid: CommitOid,
123 comparisonBaseOid: CommitOid,
124});
125const SourceBlob = Schema.Struct({
126 commit: CommitOid,
127 path: Schema.String,
128 size: NonNegativeInt,
129 binary: Schema.Boolean,
130 content: Schema.NullOr(Schema.String),
131});
132const MAX_DIFF_FILE_BYTES = 1024 * 1024;
133
134class GitCafeDiffSourceUnavailableError extends Schema.TaggedError<GitCafeDiffSourceUnavailableError>()(
135 "GitCafeDiffSourceUnavailableError",
136 {
137 path: Schema.String,
138 reason: Schema.Literals(["oversized", "binary", "unavailable"]),
139 cause: Schema.optional(Schema.Defect()),
140 },
141) {}
142const Snapshot = {
143 version: NonNegativeInt,
144 headOid: TrimmedNonEmptyString,
145 comparisonBaseOid: TrimmedNonEmptyString,
146};
147const Changes = Schema.Struct({
148 ...Snapshot,
149 items: Json.GitCafeDiffFiles,
150 next: Schema.NullOr(TrimmedNonEmptyString),
151});
152const DiffFiles = Schema.Struct({ ...Snapshot, items: Json.GitCafeDiffFiles });
153const DiffCursor = Schema.Struct({
154 version: NonNegativeInt,
155 headOid: TrimmedNonEmptyString,
156 baseOid: TrimmedNonEmptyString,
157 after: TrimmedNonEmptyString,
158});
159const encodeDiffCursor = Schema.encodeSync(Schema.fromJsonString(DiffCursor));
160const decodeDiffCursor = Schema.decodeEffect(Schema.fromJsonString(DiffCursor));
161const MergeOutcome = Schema.Struct({
162 id: Schema.String,
163 state: Schema.Literals(["accepted", "completed", "failed"]),
164 reason: Schema.optional(Schema.String),
165});
166const StackOutcome = Schema.Struct({ id: Schema.String, state: Schema.String });
167const FAILED_STACK_STATES = new Set(["failed", "stopped", "cancelled", "reconciliation_required"]);
168
169type PullRef = ProviderRepositoryRef & { readonly number: number };
170
171/** GitHub's merge counts as soon as GitCafe records it, ahead of the sync that reports it. */
172const settledMerge = (pull: Json.GitCafePullDetail) =>
173 pull.state === "open" && pull.providerMerge != null
174 ? { state: "merged" as const, mergedAt: pull.providerMerge.mergedAt }
175 : {};
176type Paged<A> = { readonly items: ReadonlyArray<A>; readonly next: string | null };
177
178function stackHeadsCurrent(
179 stack: Json.GitCafeStack,
180 input: { readonly number: number; readonly merge: boolean },
181 expected: ReadonlyArray<PullRequestStackHead>,
182): boolean {
183 const members = stack.members.toSorted((a, b) => a.position - b.position);
184 const index = members.findIndex((member) => member.pullRequestNumber === input.number);
185 if (index === -1) return false;
186 const moved = (input.merge ? members.slice(0, index + 1) : members).filter(
187 (member) => member.state !== "merged",
188 );
189 return (
190 moved.length === expected.length &&
191 moved.every(
192 (member) =>
193 member.headOid !== undefined &&
194 expected.some(
195 (head) => head.number === member.pullRequestNumber && head.headSha === member.headOid,
196 ),
197 )
198 );
199}
200
201const POSITION = /^(.+)~(\d+)$/u;
202const parsePosition = (raw: string | undefined) => {
203 const match = raw === undefined ? null : POSITION.exec(raw);
204 const created = match === null ? Number.NaN : Date.parse(match[1]!);
205 return match === null || Number.isNaN(created) ? null : { created, number: Number(match[2]) };
206};
207
208const withDetails = (
209 files: ReadonlyArray<Json.GitCafeDiffFile>,
210 details: ReadonlyArray<Json.GitCafeDiffFile>,
211) => {
212 const byPath = new Map(details.map((file) => [file.path, file]));
213 return files.map((file) => byPath.get(file.path) ?? file);
214};
215
216/** @public */
217export const make = Effect.gen(function* () {
218 const api = yield* GitCafeApi.GitCafeApi;
219 // GitCafe filters by actor id and has no lookup from a GitHub login to the actor sync made for
220 // it, so the pairs are learned from the pull requests every listing reads.
221 const knownAuthors = new Map<string, string>();
222 const authorKey = (host: string, login: string) =>
223 `${host.toLowerCase()}\n${login.toLowerCase()}`;
224 const learnAuthors = (host: string, pulls: ReadonlyArray<Json.GitCafePull>) => {
225 for (const { author } of pulls) {
226 if (author.kind !== "github") continue;
227 if (knownAuthors.size >= KNOWN_AUTHORS_LIMIT) knownAuthors.clear();
228 knownAuthors.set(authorKey(host, author.login), author.actorId);
229 }
230 };
231
232 const failure = (operation: string, detail: string, cause?: unknown) =>
233 new PullRequestProviderError({
234 provider: SourceControlProviderKind.make("gitcafe"),
235 operation,
236 reason: "failed",
237 detail,
238 ...(cause === undefined ? {} : { cause }),
239 });
240
241 const repositoryPath = (
242 operation: string,
243 input: ProviderRepositoryRef,
244 ): Effect.Effect<string, PullRequestProviderError> =>
245 GitCafeHosts.isGitCafeHost(input.host) &&
246 GitCafeHosts.gitCafeRepositoryPath(input.repository) === input.repository
247 ? Effect.succeed(`/repos/${input.repository}`)
248 : Effect.fail(
249 failure(
250 operation,
251 `GitCafe serves owner/name repositories on ${GitCafeHosts.GITCAFE_HOSTS.join(" and ")}.`,
252 ),
253 );
254
255 const send = (
256 operation: string,
257 input: Pick<ProviderRepositoryRef, "host">,
258 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
259 ) =>
260 api.request({ ...request, host: input.host, operation }).pipe(
261 Effect.mapError(
262 (error) =>
263 new PullRequestProviderError({
264 provider: SourceControlProviderKind.make("gitcafe"),
265 operation,
266 reason: error.reason,
267 detail: error.detail,
268 cause: error,
269 }),
270 ),
271 );
272
273 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
274 operation: string,
275 input: Pick<ProviderRepositoryRef, "host">,
276 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
277 schema: S,
278 ) =>
279 send(operation, input, request).pipe(
280 Effect.flatMap((raw) =>
281 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
282 Effect.mapError((cause) =>
283 failure(operation, "GitCafe returned an unreadable response.", cause),
284 ),
285 ),
286 ),
287 );
288
289 const pullPath = (operation: string, input: PullRef) =>
290 repositoryPath(operation, input).pipe(Effect.map((base) => `${base}/pulls/${input.number}`));
291
292 const readPull = (operation: string, input: PullRef) =>
293 pullPath(operation, input).pipe(
294 Effect.flatMap((path) => read(operation, input, { path }, Json.GitCafePullDetail)),
295 );
296
297 const readDiffSource = Effect.fn("GitCafePullRequestProvider.readDiffSource")(function* (
298 input: ProviderRepositoryRef,
299 revision: string,
300 filePath: string,
301 ) {
302 const operation = "getDiffFileContents";
303 const base = yield* repositoryPath(operation, input);
304 const query = new URLSearchParams({ oid: revision, path: filePath });
305 const blob = yield* read(operation, input, { path: `${base}/blob?${query}` }, SourceBlob).pipe(
306 Effect.catchIf(
307 (error) =>
308 isApiError(error.cause) && (error.cause.status === 413 || error.cause.status === 501),
309 (error) =>
310 Effect.fail(
311 failure(
312 operation,
313 "GitCafe cannot provide this source file as bounded text.",
314 new GitCafeDiffSourceUnavailableError({
315 path: filePath,
316 reason:
317 isApiError(error.cause) && error.cause.status === 413
318 ? "oversized"
319 : "unavailable",
320 cause: error,
321 }),
322 ),
323 ),
324 ),
325 );
326 if (blob.commit !== revision || blob.path !== filePath)
327 return yield* failure(
328 operation,
329 "GitCafe answered with a different source revision or path.",
330 );
331 const reason =
332 blob.size > MAX_DIFF_FILE_BYTES ||
333 (blob.content !== null && Buffer.byteLength(blob.content, "utf8") > MAX_DIFF_FILE_BYTES)
334 ? "oversized"
335 : blob.binary || blob.content?.includes("\0")
336 ? "binary"
337 : blob.content === null
338 ? "unavailable"
339 : null;
340 if (reason !== null)
341 return yield* failure(
342 operation,
343 "GitCafe cannot provide this source file as bounded text.",
344 new GitCafeDiffSourceUnavailableError({ path: filePath, reason }),
345 );
346 return blob.content!;
347 });
348
349 const readPages = Effect.fn("GitCafePullRequestProvider.readPages")(function* <
350 S extends Schema.Codec<Paged<unknown>, unknown, never, never>,
351 >(operation: string, input: Pick<ProviderRepositoryRef, "host">, path: string, schema: S) {
352 const items: Array<S["Type"]["items"][number]> = [];
353 let next: string | null = null;
354 for (let page = 0; page < MAX_PAGES; page++) {
355 const query = new URLSearchParams({ limit: String(PAGE_SIZE) });
356 if (next !== null) query.set("after", next);
357 const batch: S["Type"] = yield* read(operation, input, { path: `${path}?${query}` }, schema);
358 items.push(...batch.items);
359 const previous: string | null = next;
360 next = batch.next;
361 if (next === null || next === previous || batch.items.length === 0) break;
362 }
363 return { items, next };
364 });
365
366 /**
367 * GitCafe filters by ids, so label names and the author's handle are looked up first. A label it
368 * cannot resolve is left out, and the service narrows the rows by name instead. An author it
369 * cannot resolve comes back as `unresolvedAuthor` for the listing to find.
370 */
371 const listFilterParams = Effect.fn("GitCafePullRequestProvider.listFilterParams")(function* (
372 input: ProviderRepositoryRef & {
373 readonly filters?: PullRequestListFilters | undefined;
374 readonly authorNarrowed: boolean;
375 readonly viewer: string;
376 },
377 base: string,
378 ) {
379 const filters = input.filters;
380 const params: Array<readonly [string, string]> = [];
381 if (filters === undefined) return { params, unresolvedAuthor: null };
382 if (filters.draft !== undefined)
383 params.push([filters.draft === "only" ? "states" : "stateNots", encodeIds(["draft"])]);
384 const groups = filters.labels ?? [];
385 const excluded = filters.excludedLabels ?? [];
386 if (groups.length > 0 || excluded.length > 0) {
387 const labels = yield* readPages(
388 "listChangeRequests",
389 input,
390 `${base}/labels`,
391 Json.GitCafeLabels,
392 );
393 const ids = new Map(labels.items.map((label) => [label.name.toLowerCase(), label.id]));
394 const idsOf = (names: ReadonlyArray<string>) =>
395 names.flatMap((name) => {
396 const id = ids.get(name.trim().toLowerCase());
397 return id === undefined ? [] : [id];
398 });
399 // Several ids in `labels` match a pull request holding any one of them, which is exactly
400 // one group; the remaining groups are the service's to narrow.
401 const group = groups.find((names) => idsOf(names).length === names.length);
402 if (group !== undefined) params.push(["labels", encodeIds(idsOf(group))]);
403 const excludedIds = idsOf(excluded);
404 if (excludedIds.length > 0) params.push(["labelNots", encodeIds(excludedIds)]);
405 }
406 if (filters.author !== undefined && !input.authorNarrowed) {
407 const handle = resolvePullRequestAuthorFilter(filters.author, input.viewer);
408 // A profile matches what GitHub sync authored for it too. A GitHub-synced author with no
409 // profile is known only by the actor on their pull requests.
410 const user = yield* read(
411 "listChangeRequests",
412 input,
413 { path: `/users/${encodeURIComponent(handle)}` },
414 User,
415 ).pipe(
416 Effect.asSome,
417 Effect.catchTags({
418 PullRequestProviderError: (error) =>
419 error.reason === "unauthenticated" || error.reason === "rate-limited"
420 ? Effect.fail(error)
421 : Effect.succeedNone,
422 }),
423 );
424 const actorId = Option.isSome(user)
425 ? user.value.actorId
426 : knownAuthors.get(authorKey(input.host, handle));
427 if (actorId === undefined) return { params, unresolvedAuthor: handle };
428 params.push(["authors", encodeIds([actorId])]);
429 }
430 return { params, unresolvedAuthor: null };
431 });
432
433 const readComments = (operation: string, input: PullRef) =>
434 pullPath(operation, input).pipe(
435 Effect.flatMap((path) =>
436 readPages(operation, input, `${path}/comments`, Json.GitCafeComments),
437 ),
438 );
439
440 const isForbidden = (error: PullRequestProviderError) =>
441 isApiError(error.cause) && error.cause.status === 403;
442
443 /**
444 * GitCafe offers no way to read a token's scopes, so reviewer controls show
445 * for anyone who may edit the pull request; a token without the reviewer
446 * scopes learns which ones it lacks when it uses them.
447 */
448 const explainReviewerScopes =
449 (operation: string) =>
450 <A, R>(effect: Effect.Effect<A, PullRequestProviderError, R>) =>
451 effect.pipe(
452 Effect.catchIf(isForbidden, (error) =>
453 Effect.fail(
454 failure(
455 operation,
456 "This GitCafe token cannot request reviewers. It needs the pr:review:read and pr:reviewers:write scopes.",
457 error,
458 ),
459 ),
460 ),
461 );
462
463 /**
464 * GitCafe replaces a pull request's whole reviewer or label list, so one toggle reads the
465 * list, changes it, and writes it back fenced on the pull request's version. The version is
466 * read first: a change landing between the two reads then fails the fence instead of being
467 * overwritten.
468 */
469 const toggleListed = Effect.fn("GitCafePullRequestProvider.toggleListed")(function* (
470 operation: string,
471 input: PullRef,
472 list: { readonly name: "reviewers" | "labels"; readonly key: "actorIds" | "labelIds" },
473 ids: ReadonlyArray<string>,
474 on: boolean,
475 ) {
476 const path = yield* pullPath(operation, input);
477 const pull = yield* readPull(operation, input);
478 const listed = yield* readPages(operation, input, `${path}/${list.name}`, Listed);
479 const current = listed.items.map((item) => item.id);
480 const next = on
481 ? [...new Set([...current, ...ids])]
482 : current.filter((id) => !ids.includes(id));
483 if (next.length === current.length) return;
484 yield* read(
485 operation,
486 input,
487 {
488 method: "PUT",
489 path: `${path}/${list.name}`,
490 body: { expectedVersion: pull.version, [list.key]: next },
491 },
492 Versioned,
493 );
494 });
495
496 /**
497 * GitCafe's stack lists no heads, and they are what a land or restack is fenced on, so each
498 * open layer's pull is read.
499 */
500 const readStack = Effect.fn("GitCafePullRequestProvider.readStack")(function* (
501 operation: string,
502 input: PullRef,
503 ) {
504 const path = yield* pullPath(operation, input);
505 const { stack } = yield* read(
506 operation,
507 input,
508 { path: `${path}/stack` },
509 Json.GitCafeStackEnvelope,
510 );
511 if (stack === null) return null;
512 const members = yield* Effect.forEach(
513 stack.members,
514 (member) =>
515 member.state === "merged"
516 ? Effect.succeed(member)
517 : readPull(operation, { ...input, number: member.pullRequestNumber }).pipe(
518 Effect.map((pull) =>
519 pull.headOid == null ? member : { ...member, headOid: pull.headOid },
520 ),
521 ),
522 { concurrency: 4 },
523 );
524 return { ...stack, members };
525 });
526
527 const readDiffPage = Effect.fn("GitCafePullRequestProvider.readDiffPage")(function* (
528 operation: string,
529 input: Parameters<PullRequestProviderApi["getDiff"]>[0],
530 limit: number,
531 ) {
532 if (input.commit !== undefined)
533 return yield* failure(operation, "GitCafe commit diffs are not supported yet.");
534 const cursor =
535 input.cursor === undefined
536 ? null
537 : yield* decodeDiffCursor(input.cursor).pipe(
538 Effect.mapError((cause) => failure(operation, "Invalid GitCafe diff cursor.", cause)),
539 );
540 // A pull without a head yet has nothing to pin; its version still is.
541 const expected = cursor ?? (yield* readPull(operation, input));
542 const version = expected.version;
543 const path = yield* pullPath(operation, input);
544 const query = new URLSearchParams({ expectedVersion: String(version), limit: String(limit) });
545 if (cursor !== null) query.set("after", cursor.after);
546 const page = yield* read(operation, input, { path: `${path}/changes?${query}` }, Changes);
547 if (
548 page.version !== version ||
549 (expected.headOid !== null && page.headOid !== expected.headOid) ||
550 (cursor !== null && cursor.baseOid !== page.comparisonBaseOid)
551 )
552 return yield* failure(
553 operation,
554 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
555 );
556 if (cursor !== null && page.next !== null && page.next === cursor.after)
557 return yield* failure(operation, "GitCafe returned a repeated diff page cursor.");
558 const revision = { version, headOid: page.headOid, baseOid: page.comparisonBaseOid };
559 return {
560 items: page.items,
561 revision,
562 nextCursor: page.next === null ? null : encodeDiffCursor({ ...revision, after: page.next }),
563 };
564 });
565
566 const readDiffFiles = Effect.fn("GitCafePullRequestProvider.readDiffFiles")(function* (
567 input: PullRef,
568 revision: { readonly version: number; readonly headOid: string; readonly baseOid: string },
569 paths: ReadonlyArray<string>,
570 ) {
571 if (paths.length === 0) return [];
572 const path = yield* pullPath("getDiff", input);
573 const files = yield* read(
574 "getDiff",
575 input,
576 {
577 method: "POST",
578 path: `${path}/diff-files`,
579 body: { paths, expectedVersion: revision.version },
580 },
581 DiffFiles,
582 );
583 if (
584 files.version !== revision.version ||
585 files.headOid !== revision.headOid ||
586 files.comparisonBaseOid !== revision.baseOid
587 )
588 return yield* failure(
589 "getDiff",
590 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
591 );
592 return files.items;
593 });
594
595 const runStackAction = Effect.fn("GitCafePullRequestProvider.runStackAction")(function* (
596 input: Parameters<PullRequestProviderApi["runAction"]>[0] & { readonly stackNumber: number },
597 ) {
598 const land = input.action === "merge";
599 const operation = land ? "landStackThrough" : "restackStack";
600 if (!land && input.action !== "update-branch")
601 return yield* failure(operation, `GitCafe cannot ${input.action} a stack.`);
602 const stack = yield* readStack(operation, input);
603 if (
604 stack === null ||
605 stack.number !== input.stackNumber ||
606 input.expectedStackHeads === undefined ||
607 !stackHeadsCurrent(stack, { number: input.number, merge: land }, input.expectedStackHeads)
608 )
609 return yield* failure(
610 operation,
611 "The stack changed since it was read. Refresh it and try again.",
612 );
613 const base = yield* repositoryPath(operation, input);
614 const outcome = yield* read(
615 operation,
616 input,
617 {
618 method: "POST",
619 path: `${base}/pulls/stacks/${stack.number}/${land ? "land-through" : "restack"}`,
620 body: land
621 ? {
622 expectedRevision: stack.revision,
623 requestId: yield* randomUuidV4,
624 throughPullRequestNumber: input.number,
625 strategy: input.mergeMethod ?? "merge",
626 }
627 : { expectedRevision: stack.revision, requestId: yield* randomUuidV4 },
628 },
629 StackOutcome,
630 );
631 if (FAILED_STACK_STATES.has(outcome.state))
632 return yield* failure(operation, `GitCafe's stack operation ${outcome.state}.`);
633 });
634
635 // GitCafe's pulls carry no line totals, and linked pull requests are summarized every minute,
636 // so hunk totals are held per compared pair of commits. The file list that names the pair is
637 // cheap; a retarget or a landed parent layer moves the base without moving the head.
638 const lineTotals = new Map<string, { readonly additions: number; readonly deletions: number }>();
639
640 const readLineStats = Effect.fn("GitCafePullRequestProvider.readLineStats")(function* (
641 input: PullRef,
642 version: number,
643 ) {
644 const path = yield* pullPath("getChangeRequest", input);
645 const files: Array<Json.GitCafeDiffFile> = [];
646 let revision: { version: number; headOid: string; baseOid: string } | undefined;
647 let after: string | null = null;
648 for (let page = 0; page < MAX_CHANGE_PAGES; page++) {
649 const query = new URLSearchParams({
650 expectedVersion: String(version),
651 limit: String(CHANGES_PAGE_LIMIT),
652 });
653 if (after !== null) query.set("after", after);
654 const batch: typeof Changes.Type = yield* read(
655 "getChangeRequest",
656 input,
657 { path: `${path}/changes?${query}` },
658 Changes,
659 );
660 revision ??= {
661 version: batch.version,
662 headOid: batch.headOid,
663 baseOid: batch.comparisonBaseOid,
664 };
665 files.push(...batch.items);
666 const previous: string | null = after;
667 after = batch.next;
668 if (after === null || after === previous || batch.items.length === 0) break;
669 }
670 if (revision === undefined) return { changedFiles: 0, additions: 0, deletions: 0 };
671 const key = `${input.host} ${input.repository.toLowerCase()} ${input.number} ${revision.baseOid} ${revision.headOid}`;
672 const held = lineTotals.get(key);
673 if (held !== undefined) return { changedFiles: files.length, ...held };
674 const details = files.some((file) => file.additions !== undefined)
675 ? Option.some(files)
676 : files.length > LINE_STATS_MAX_FILES
677 ? Option.none()
678 : yield* Effect.forEach(
679 chunk(detailablePaths(files), DIFF_FILES_BATCH),
680 (paths) => readDiffFiles(input, revision, paths),
681 { concurrency: 4 },
682 ).pipe(
683 Effect.map((batches) => batches.flat()),
684 Effect.option,
685 );
686 // Unread hunks leave the lines unknown rather than zero; the file count still stands.
687 if (Option.isNone(details)) return { changedFiles: files.length };
688 const counted = details.value;
689 const totals = {
690 additions: counted.reduce((total, file) => total + (file.additions ?? 0), 0),
691 deletions: counted.reduce((total, file) => total + (file.deletions ?? 0), 0),
692 };
693 if (lineTotals.size >= LINE_STATS_CACHE_SIZE)
694 lineTotals.delete(lineTotals.keys().next().value!);
695 lineTotals.set(key, totals);
696 return { changedFiles: files.length, ...totals };
697 });
698
699 const merge = Effect.fn("GitCafePullRequestProvider.merge")(function* (
700 input: Parameters<PullRequestProviderApi["runAction"]>[0],
701 ) {
702 const pull = yield* readPull("merge", input);
703 if (pull.state === "merged") return;
704 if (pull.mergeRoute === "unsupported")
705 return yield* failure("merge", "This GitCafe pull request has no supported merge route.");
706 const base = yield* repositoryPath("merge", input);
707 // Native merges fence on the current target commit; provider-routed merges supply the base.
708 const baseOid =
709 pull.mergeRoute === "provider"
710 ? pull.observedBaseOid
711 : (yield* read(
712 "merge",
713 input,
714 {
715 path: `${base}/commit?ref=${encodeURIComponent(`refs/heads/${pull.targetBranch}`)}`,
716 },
717 BranchCommit,
718 )).oid;
719 if (pull.headOid === null || baseOid == null)
720 return yield* failure(
721 "merge",
722 "GitCafe has not reported the pull request's head and base yet. Refresh and try again.",
723 );
724 const path = yield* pullPath("merge", input);
725 const outcome = yield* read(
726 "merge",
727 input,
728 {
729 method: "POST",
730 path: `${path}/merge`,
731 body: {
732 requestId: yield* randomUuidV4,
733 expectedVersion: pull.version,
734 headOid: pull.headOid,
735 baseOid,
736 strategy: input.mergeMethod ?? "merge",
737 },
738 },
739 MergeOutcome,
740 );
741 if (outcome.state === "failed")
742 return yield* failure("merge", outcome.reason ?? "GitCafe could not merge the pull request.");
743 });
744
745 const provider: PullRequestProviderApi = {
746 kind: SourceControlProviderKind.make("gitcafe"),
747 capabilities: CAPABILITIES,
748 getViewer: (input) =>
749 read(
750 "getViewer",
751 { host: input.host ?? "git.cafe" },
752 { path: "/auth/principal" },
753 Principal,
754 ).pipe(Effect.map((principal) => principal.handle)),
755 listChangeRequests: Effect.fn("GitCafePullRequestProvider.listChangeRequests")(
756 function* (input) {
757 const base = yield* repositoryPath("listChangeRequests", input);
758 const involved = input.involvement === "authored" || input.involvement === "reviewing";
759 let actorId: string | undefined;
760 if (involved) {
761 // The viewer is the token's principal, whose actor also matches the pull requests GitHub
762 // sync authored for its linked profile. When it can't be read, the listing comes back
763 // unnarrowed and the page's own involvement filter does the rest. A refused token or a
764 // rate limit still fails, since the service acts on those for the whole host.
765 const principal = yield* read(
766 "listChangeRequests",
767 input,
768 { path: "/auth/principal" },
769 Principal,
770 ).pipe(
771 Effect.asSome,
772 Effect.catchTags({
773 PullRequestProviderError: (error) =>
774 error.reason === "unauthenticated" || error.reason === "rate-limited"
775 ? Effect.fail(error)
776 : Effect.succeedNone,
777 }),
778 );
779 if (Option.isSome(principal)) {
780 if (principal.value.handle.toLowerCase() !== input.viewer.toLowerCase())
781 return { items: [], truncated: false, continues: false };
782 actorId = principal.value.actorId;
783 }
784 }
785 const { params: filterParams, unresolvedAuthor } = yield* listFilterParams(
786 { ...input, authorNarrowed: actorId !== undefined && input.involvement === "authored" },
787 base,
788 );
789 const readPage = (rows: number, after: string | null) => {
790 const query = new URLSearchParams({ limit: String(rows), sort: "newest" });
791 if (input.state !== "all") query.set("state", input.state);
792 if (input.query?.trim()) query.set("q", input.query.trim());
793 for (const [key, value] of filterParams) query.set(key, value);
794 if (actorId !== undefined)
795 query.set(
796 input.involvement === "reviewing" ? "reviewers" : "authors",
797 encodeIds([actorId]),
798 );
799 if (after !== null) query.set("after", after);
800 return read(
801 "listChangeRequests",
802 input,
803 { path: `${base}/pulls?${query}` },
804 Json.GitCafePulls,
805 ).pipe(Effect.tap((page) => Effect.sync(() => learnAuthors(input.host, page.items))));
806 };
807 if (unresolvedAuthor !== null) {
808 // Rows are only ever handed out narrowed by actor, so a continuation always carries on
809 // the same narrowed listing.
810 const key = authorKey(input.host, unresolvedAuthor);
811 let after: string | null = null;
812 let pages = 0;
813 do {
814 const page: typeof Json.GitCafePulls.Type = yield* readPage(PAGE_SIZE, after);
815 pages += 1;
816 after = page.items.length === 0 ? null : page.next;
817 } while (!knownAuthors.has(key) && after !== null && pages < AUTHOR_DISCOVERY_PAGES);
818 const found = knownAuthors.get(key);
819 if (found === undefined)
820 return { items: [], truncated: after !== null, continues: false };
821 filterParams.push(["authors", encodeIds([found])]);
822 }
823 const limit = Math.max(1, input.limit);
824 const items: Array<Json.GitCafePull> = [];
825 // GitCafe pages by an opaque token and orders by creation, so a continuation reads from the
826 // top and keeps only the rows created after the last one delivered. A count of rows would
827 // skip one for every row above it that closed in between.
828 const resume = parsePosition(input.cursor?.resumeAfter);
829 const isNew = (pull: Json.GitCafePull) => {
830 if (resume === null) return true;
831 const created = Date.parse(pull.createdAt);
832 return (
833 created < resume.created || (created === resume.created && pull.number < resume.number)
834 );
835 };
836 let next: string | null = null;
837 do {
838 const page: typeof Json.GitCafePulls.Type = yield* readPage(
839 resume === null ? Math.min(PAGE_SIZE, limit - items.length) : PAGE_SIZE,
840 next,
841 );
842 items.push(...page.items.filter(isNew));
843 next = page.items.length === 0 ? null : page.next;
844 } while (next !== null && items.length < limit);
845 const delivered = items.slice(0, limit);
846 const last = delivered.at(-1);
847 return {
848 ...(last === undefined ? {} : { resumeAfter: `${last.createdAt}~${last.number}` }),
849 items: delivered.map((pull) => {
850 const item = Json.toChangeRequest(pull, input);
851 return input.involvement === "reviewing" && actorId !== undefined
852 ? {
853 ...item,
854 reviewRequestLogins: [...new Set([...item.reviewRequestLogins, input.viewer])],
855 }
856 : item;
857 }),
858 truncated: next !== null || items.length > limit,
859 continues: true,
860 };
861 },
862 ),
863 getChangeRequestPreview: (input) =>
864 readPull("getChangeRequestPreview", input).pipe(
865 Effect.map((pull) => Json.toChangeRequest(pull, input)),
866 ),
867 getChangeRequestSummary: Effect.fn("GitCafePullRequestProvider.getChangeRequestSummary")(
868 function* (input) {
869 const pull = yield* readPull("getChangeRequestSummary", input);
870 const changes =
871 pull.headOid === null
872 ? null
873 : yield* readLineStats(input, pull.version).pipe(Effect.orElseSucceed(() => null));
874 // A count that could not be read is absent rather than zero.
875 const {
876 additions: _additions,
877 deletions: _deletions,
878 ...summary
879 } = Json.toChangeRequest(pull, input);
880 return {
881 ...summary,
882 ...(changes === null ? {} : changes),
883 closedAt: pull.closedAt,
884 mergedAt: pull.mergedAt,
885 ...settledMerge(pull),
886 };
887 },
888 ),
889 getChangeRequest: Effect.fn("GitCafePullRequestProvider.getChangeRequest")(function* (input) {
890 const pull = yield* readPull("getChangeRequest", input);
891 const path = yield* pullPath("getChangeRequest", input);
892 const base = yield* repositoryPath("getChangeRequest", input);
893 // A single pull request read carries neither its reviewers nor its labels.
894 const [status, checks, changes, reviewers, labels] = yield* Effect.all(
895 [
896 read("getChangeRequest", input, { path: `${path}/status` }, Status),
897 pull.headOid === null
898 ? Effect.succeed(null)
899 : readPages(
900 "getChangeRequest",
901 input,
902 `${base}/commits/${encodeURIComponent(pull.headOid)}/checks`,
903 Json.GitCafeChecks,
904 ),
905 pull.headOid === null
906 ? Effect.succeed(null)
907 : readLineStats(input, pull.version).pipe(Effect.orElseSucceed(() => null)),
908 // Reviewers need `pr:review:read`, which a contents-only token lacks.
909 readPages("getChangeRequest", input, `${path}/reviewers`, Json.GitCafeActorEntries).pipe(
910 Effect.catch((error) =>
911 isForbidden(error) ? Effect.succeed({ items: [], next: null }) : Effect.fail(error),
912 ),
913 ),
914 readPages("getChangeRequest", input, `${path}/labels`, Json.GitCafeLabels),
915 ],
916 { concurrency: 5 },
917 );
918 const listed = { ...pull, reviewers: reviewers.items, labels: labels.items };
919 const checkList = checks === null ? [] : Json.toChecks(checks);
920 // GitCafe's own counts include runs a re-run replaced, so the newest runs are the state. A
921 // truncated listing may be missing a failure; the counts never call failing checks passing.
922 const checksState =
923 checks !== null && checks.next === null
924 ? Json.checksStateOf(checkList)
925 : status.checks.total === 0
926 ? null
927 : status.checks.failing > 0
928 ? ("failing" as const)
929 : status.checks.pending > 0
930 ? ("pending" as const)
931 : ("passing" as const);
932 const permissions = Json.toViewerPermissions(pull);
933 const merging = status.merge.reasons?.some((reason) => MERGE_IN_FLIGHT.has(reason)) ?? false;
934 return {
935 ...Json.toChangeRequest(listed, input),
936 autoMergeEnabled: merging,
937 headSha: pull.headOid,
938 body: pull.description ?? "",
939 ...(pull.sourceRepo === null
940 ? {}
941 : { headRepositoryNameWithOwner: `${pull.sourceRepo.owner}/${pull.sourceRepo.name}` }),
942 additions: changes?.additions ?? 0,
943 deletions: changes?.deletions ?? 0,
944 changedFiles: changes?.changedFiles ?? 0,
945 closedAt: pull.closedAt,
946 mergedAt: pull.mergedAt,
947 ...settledMerge(pull),
948 reviewers: Json.toReviewers(listed, input.host),
949 checks: checkList,
950 ...(checksState === null ? {} : { checksState }),
951 mergeability:
952 status.merge.conflicts === "conflicting"
953 ? ("conflicting" as const)
954 : status.merge.conflicts === "none"
955 ? ("mergeable" as const)
956 : ("unknown" as const),
957 baseComparison:
958 status.merge.fastForward === null
959 ? ("unknown" as const)
960 : status.merge.fastForward
961 ? ("up-to-date" as const)
962 : ("behind" as const),
963 mergeCapabilities: {
964 merge: mergeStrategyOpen(status, "merge"),
965 squash: mergeStrategyOpen(status, "squash"),
966 rebase: mergeStrategyOpen(status, "rebase"),
967 },
968 viewerPermissions:
969 status.merge.permitted === false || merging
970 ? { ...permissions, actions: permissions.actions.filter((a) => a !== "merge") }
971 : permissions,
972 };
973 }),
974 getChangeRequestStack: (input) =>
975 readStack("getChangeRequestStack", input).pipe(
976 Effect.map((stack) => (stack === null ? null : Json.toStack(stack, input))),
977 ),
978 getChangeRequestActivity: Effect.fn("GitCafePullRequestProvider.getChangeRequestActivity")(
979 function* (input) {
980 const pull = yield* readPull("getChangeRequestActivity", input);
981 const path = yield* pullPath("getChangeRequestActivity", input);
982 const operation = "getChangeRequestActivity";
983 const [comments, reviews, commits, reactions] = yield* Effect.all(
984 [
985 readComments(operation, input),
986 readPages(operation, input, `${path}/reviews`, Json.GitCafeReviews),
987 pull.headOid === null
988 ? Effect.succeed({ items: [], next: null })
989 : // A closed pull request whose branch is gone keeps its head, but git.cafe answers
990 // 404 for commits it no longer has; the conversation still stands without them.
991 readPages(operation, input, `${path}/commits`, Json.GitCafeCommits).pipe(
992 Effect.catch((error) =>
993 error.reason === "not-found"
994 ? Effect.succeed({ items: [], next: null })
995 : Effect.fail(error),
996 ),
997 ),
998 readPages(operation, input, `${path}/reactions/`, Json.GitCafeReactions).pipe(
999 Effect.orElseSucceed(() => undefined),
1000 ),
1001 ],
1002 { concurrency: 4 },
1003 );
1004 return Json.toActivity({
1005 comments,
1006 reviews,
1007 commits: { ...commits, truncated: commits.next !== null, headOid: pull.headOid ?? "" },
1008 host: input.host,
1009 ...(pull.headOid === null ? {} : { headOid: pull.headOid }),
1010 ...(reactions === undefined ? {} : { reactions }),
1011 });
1012 },
1013 ),
1014 getViewerPermissions: (input) =>
1015 readPull("getViewerPermissions", input).pipe(Effect.map(Json.toViewerPermissions)),
1016 getDiff: Effect.fn("GitCafePullRequestProvider.getDiff")(function* (input) {
1017 const page = yield* readDiffPage("getDiff", input, DIFF_FILES_BATCH);
1018 const details = yield* readDiffFiles(input, page.revision, detailablePaths(page.items));
1019 return {
1020 ...Json.toDiff({ items: withDetails(page.items, details) }),
1021 nextCursor: page.nextCursor,
1022 };
1023 }),
1024 getDiffFilePaths: Effect.fn("GitCafePullRequestProvider.getDiffFilePaths")(function* (input) {
1025 const page = yield* readDiffPage("getDiffFilePaths", input, CHANGES_PAGE_LIMIT);
1026 return {
1027 files: page.items.map((file) => ({
1028 oldPath: file.oldPath ?? file.path,
1029 newPath: file.path,
1030 })),
1031 nextCursor: page.nextCursor,
1032 };
1033 }),
1034 getDiffFileContents: Effect.fn("GitCafePullRequestProvider.getDiffFileContents")(
1035 function* (input) {
1036 const operation = "getDiffFileContents";
1037 if (input.commit !== undefined)
1038 return yield* failure(operation, "GitCafe commit diff contents are not supported yet.");
1039 const pull = yield* readPull(operation, input);
1040 if (!isCommitOid(pull.headOid))
1041 return yield* failure(
1042 operation,
1043 "GitCafe has not reported an immutable pull request head.",
1044 );
1045 const path = yield* pullPath(operation, input);
1046 const query = new URLSearchParams({ expectedVersion: String(pull.version), limit: "1" });
1047 // observedBaseOid is the target tip, not necessarily the diff's merge base.
1048 const snapshot = yield* read(
1049 operation,
1050 input,
1051 { path: `${path}/changes?${query}` },
1052 SourceSnapshot,
1053 );
1054 if (snapshot.version !== pull.version || snapshot.headOid !== pull.headOid)
1055 return yield* failure(
1056 operation,
1057 "GitCafe changed the pull request revision. Refresh the diff.",
1058 );
1059 const sourceRepository =
1060 pull.sourceRepo === null
1061 ? input.repository
1062 : `${pull.sourceRepo.owner}/${pull.sourceRepo.name}`;
1063 const [oldContents, newContents] = yield* Effect.all(
1064 [
1065 input.changeType === "new"
1066 ? Effect.succeed("")
1067 : readDiffSource(input, snapshot.comparisonBaseOid, input.oldPath),
1068 input.changeType === "deleted"
1069 ? Effect.succeed("")
1070 : readDiffSource(
1071 { ...input, repository: sourceRepository },
1072 snapshot.headOid,
1073 input.newPath,
1074 ),
1075 ],
1076 { concurrency: 2 },
1077 );
1078 return { oldContents, newContents };
1079 },
1080 ),
1081 runAction: Effect.fn("GitCafePullRequestProvider.runAction")(function* (input) {
1082 if (input.stackNumber !== undefined)
1083 return yield* runStackAction({ ...input, stackNumber: input.stackNumber });
1084 switch (input.action) {
1085 case "merge":
1086 return yield* merge(input);
1087 case "ready":
1088 case "draft":
1089 case "close":
1090 case "reopen": {
1091 const pull = yield* readPull(input.action, input);
1092 const path = yield* pullPath(input.action, input);
1093 yield* send(input.action, input, {
1094 method: "POST",
1095 path: `${path}/${input.action}`,
1096 body: { expectedVersion: pull.version },
1097 });
1098 return;
1099 }
1100 default:
1101 return yield* failure(input.action, `GitCafe cannot ${input.action} from T3 Code.`);
1102 }
1103 }),
1104 updateChangeRequest: Effect.fn("GitCafePullRequestProvider.updateChangeRequest")(
1105 function* (input) {
1106 const pull = yield* readPull("updateChangeRequest", input);
1107 const path = yield* pullPath("updateChangeRequest", input);
1108 yield* read(
1109 "updateChangeRequest",
1110 input,
1111 {
1112 method: "PATCH",
1113 path,
1114 body: {
1115 expectedVersion: pull.version,
1116 ...(input.title === undefined ? {} : { title: input.title }),
1117 ...(input.body === undefined ? {} : { description: input.body }),
1118 },
1119 },
1120 Versioned,
1121 );
1122 },
1123 ),
1124 comment: (input) =>
1125 pullPath("comment", input).pipe(
1126 Effect.flatMap((path) =>
1127 read(
1128 "comment",
1129 input,
1130 { method: "POST", path: `${path}/comments/`, body: { body: input.body } },
1131 Written,
1132 ),
1133 ),
1134 Effect.asVoid,
1135 ),
1136 updateComment: Effect.fn("GitCafePullRequestProvider.updateComment")(function* (input) {
1137 if (!isId(input.commentId))
1138 return yield* failure("updateComment", "GitCafe comment ids are opaque slugs.");
1139 const path = `${yield* pullPath("updateComment", input)}/comments/${input.commentId}`;
1140 const detail = yield* read("updateComment", input, { path: `${path}/detail` }, CommentDetail);
1141 yield* read(
1142 "updateComment",
1143 input,
1144 { method: "PATCH", path, body: { body: input.body, expectedVersion: detail.version } },
1145 Written,
1146 );
1147 }),
1148 submitReview: Effect.fn("GitCafePullRequestProvider.submitReview")(function* (input) {
1149 if (input.comments.length > 0)
1150 return yield* failure("submitReview", "GitCafe line comments are not supported yet.");
1151 const pull = yield* readPull("submitReview", input);
1152 if (pull.headOid === null)
1153 return yield* failure("submitReview", "GitCafe has not reported the pull request's head.");
1154 const path = yield* pullPath("submitReview", input);
1155 yield* read(
1156 "submitReview",
1157 input,
1158 {
1159 method: "POST",
1160 path: `${path}/reviews`,
1161 body: {
1162 verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict,
1163 ...(input.body.length === 0 ? {} : { body: input.body }),
1164 commitOid: pull.headOid,
1165 expectedVersion: pull.version,
1166 requestId: yield* randomUuidV4,
1167 },
1168 },
1169 Written,
1170 );
1171 }),
1172 listReviewerCandidates: Effect.fn("GitCafePullRequestProvider.listReviewerCandidates")(
1173 function* (input) {
1174 const operation = "listReviewerCandidates";
1175 const path = yield* pullPath(operation, input);
1176 const [pull, candidates, reviewers] = yield* Effect.all(
1177 [
1178 readPull(operation, input),
1179 readPages(
1180 operation,
1181 input,
1182 `${path}/reviewer-candidates`,
1183 Json.GitCafeActorEntries,
1184 ).pipe(explainReviewerScopes(operation)),
1185 readPages(operation, input, `${path}/reviewers`, Listed).pipe(
1186 explainReviewerScopes(operation),
1187 ),
1188 ],
1189 { concurrency: 3 },
1190 );
1191 return {
1192 candidates: Json.toReviewerCandidates(candidates, {
1193 requested: new Set(reviewers.items.map((reviewer) => reviewer.id)),
1194 authorActorId: pull.author.actorId,
1195 host: input.host,
1196 }),
1197 truncated: candidates.next !== null,
1198 };
1199 },
1200 ),
1201 setReviewerRequest: (input) =>
1202 toggleListed(
1203 "setReviewerRequest",
1204 input,
1205 { name: "reviewers", key: "actorIds" },
1206 input.reviewers.map((reviewer) => reviewer.id),
1207 input.requested,
1208 ).pipe(explainReviewerScopes("setReviewerRequest")),
1209 listLabelCandidates: Effect.fn("GitCafePullRequestProvider.listLabelCandidates")(
1210 function* (input) {
1211 const operation = "listLabelCandidates";
1212 const base = yield* repositoryPath(operation, input);
1213 const [labels, applied] = yield* Effect.all(
1214 [
1215 readPages(operation, input, `${base}/labels`, Json.GitCafeLabels),
1216 readPages(operation, input, `${base}/pulls/${input.number}/labels`, Listed),
1217 ],
1218 { concurrency: 2 },
1219 );
1220 const appliedIds = new Set(applied.items.map((label) => label.id));
1221 return {
1222 candidates: labels.items.map((label) => ({
1223 name: label.name,
1224 color: label.color,
1225 description: label.description ?? null,
1226 isApplied: appliedIds.has(label.id),
1227 })),
1228 truncated: labels.next !== null,
1229 };
1230 },
1231 ),
1232 listRepositoryLabels: Effect.fn("GitCafePullRequestProvider.listRepositoryLabels")(
1233 function* (input) {
1234 const operation = "listRepositoryLabels";
1235 const base = yield* repositoryPath(operation, input);
1236 const labels = yield* readPages(operation, input, `${base}/labels`, Json.GitCafeLabels);
1237 return {
1238 items: labels.items.map((label) => ({ name: label.name, color: label.color })),
1239 truncated: labels.next !== null,
1240 };
1241 },
1242 ),
1243 searchRepositoryAuthors: Effect.fn("GitCafePullRequestProvider.searchRepositoryAuthors")(
1244 function* (input) {
1245 const operation = "searchRepositoryAuthors";
1246 const query = input.query?.trim() ?? "";
1247 // User search needs two characters; before that the repository's own people stand in.
1248 const path =
1249 query.length < 2
1250 ? `${yield* repositoryPath(operation, input)}/collaborators?${new URLSearchParams({ limit: "50" })}`
1251 : `/users?${new URLSearchParams({ q: query, limit: "50" })}`;
1252 const people = yield* read(operation, input, { path }, Json.GitCafePeople);
1253 return { items: Json.toPeople(people, input.host), truncated: people.next !== null };
1254 },
1255 ),
1256 setLabels: Effect.fn("GitCafePullRequestProvider.setLabels")(function* (input) {
1257 const base = yield* repositoryPath("setLabels", input);
1258 const labels = yield* readPages("setLabels", input, `${base}/labels`, Json.GitCafeLabels);
1259 const selected = labels.items.filter((label) => input.labels.includes(label.name));
1260 if (selected.length !== input.labels.length)
1261 return yield* failure("setLabels", "One or more requested labels could not be found.");
1262 yield* toggleListed(
1263 "setLabels",
1264 input,
1265 { name: "labels", key: "labelIds" },
1266 selected.map((label) => label.id),
1267 input.applied,
1268 );
1269 }),
1270 replyToThread: Effect.fn("GitCafePullRequestProvider.replyToThread")(function* (input) {
1271 if (!isId(input.threadId))
1272 return yield* failure("replyToThread", "GitCafe thread ids are opaque slugs.");
1273 const path = yield* pullPath("replyToThread", input);
1274 yield* read(
1275 "replyToThread",
1276 input,
1277 {
1278 method: "POST",
1279 path: `${path}/comments/${input.threadId}/replies`,
1280 body: { body: input.body },
1281 },
1282 Written,
1283 );
1284 }),
1285 setReaction: Effect.fn("GitCafePullRequestProvider.setReaction")(function* (input) {
1286 const path = `${yield* pullPath("setReaction", input)}/reactions/`;
1287 const subject =
1288 input.subjectId === undefined
1289 ? { kind: "pull_request" as const, id: (yield* readPull("setReaction", input)).id }
1290 : { kind: "pull_request_comment" as const, id: input.subjectId };
1291 const reactions = yield* readPages("setReaction", input, path, Json.GitCafeReactions);
1292 const mine = reactions.items.find(
1293 (item) =>
1294 item.subject.kind === subject.kind &&
1295 item.subject.id === subject.id &&
1296 item.emoji.kind === "unicode" &&
1297 Json.reactionContent(item.emoji.value) === input.content,
1298 )?.viewerReactionId;
1299 if (input.reacted === (mine != null)) return;
1300 if (input.reacted) {
1301 yield* send("setReaction", input, {
1302 method: "POST",
1303 path,
1304 body: { subject, emoji: { kind: "unicode", value: Json.REACTION_EMOJI[input.content] } },
1305 });
1306 return;
1307 }
1308 if (mine == null) return;
1309 if (!isId(mine))
1310 return yield* failure("setReaction", "GitCafe returned an unreadable reaction id.");
1311 yield* send("setReaction", input, { method: "DELETE", path: `${path}${mine}` });
1312 }),
1313 setThreadResolution: Effect.fn("GitCafePullRequestProvider.setThreadResolution")(
1314 function* (input) {
1315 const comments = yield* readComments("setThreadResolution", input);
1316 const root = comments.items.find(
1317 (comment) => comment.id === input.threadId && comment.threadId === input.threadId,
1318 );
1319 if (root === undefined || root.version === undefined || !isId(root.id))
1320 return yield* failure("setThreadResolution", "GitCafe did not return the thread root.");
1321 if (input.resolved === (root.resolvedAt !== null)) return;
1322 const path = yield* pullPath("setThreadResolution", input);
1323 yield* read(
1324 "setThreadResolution",
1325 input,
1326 {
1327 method: "POST",
1328 path: `${path}/comments/${root.id}/${input.resolved ? "resolve" : "unresolve"}`,
1329 body: { expectedVersion: root.version },
1330 },
1331 Written,
1332 );
1333 },
1334 ),
1335 };
1336 return provider;
1337});