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

GitCafePullRequestProvider.ts

1,304 lines52.1 KB

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