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 TrimmedNonEmptyString,
9 type PullRequestCapabilities,
10 type PullRequestStackHead,
11} from "@t3tools/contracts";
12import {
13 PullRequestProviderError,
14 type ProviderRepositoryRef,
15 type PullRequestProviderApi,
16} from "@t3tools/source-control-core/server/PullRequestProvider";
17
18import * as GitCafeApi from "./GitCafeApi.ts";
19import * as GitCafeHosts from "./gitCafeHosts.ts";
20import * as Json from "./gitCafePullRequestJson.ts";
21import { definition } from "../client/definition.ts";
22
23const CAPABILITIES: PullRequestCapabilities = {
24 diff: true,
25 comment: true,
26 actions: [...definition.changeRequestActions],
27 mergeMethods: ["merge", "squash", "rebase"],
28 // Only through a stack: GitCafe's one branch update restacks every layer above it.
29 updateMethods: ["rebase"],
30 search: true,
31 stacks: true,
32 stackActions: true,
33 reactions: true,
34 labels: false,
35 // Line comments go through GitCafe's review drafts, which arrive with revision fencing.
36 review: {
37 inlineComment: false,
38 reply: true,
39 resolve: true,
40 verdicts: ["approve", "request-changes", "comment"],
41 },
42 reviewers: { request: false, listCandidates: false },
43 edit: { changeRequest: true, comment: true },
44};
45
46const PAGE_SIZE = 100;
47const MAX_PAGES = 10;
48/** GitCafe's cap on paths per `/diff-files` read, and so one diff page. */
49const DIFF_FILES_BATCH = 64;
50/**
51 * Line totals cost one hunk read per batch, so a pull request larger than this reports none
52 * rather than reading every file.
53 */
54const LINE_STATS_MAX_FILES = DIFF_FILES_BATCH * 4;
55const MAX_CHANGE_PAGES = 20;
56
57const chunk = <A>(items: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> =>
58 Array.from({ length: Math.ceil(items.length / size) }, (_, index) =>
59 items.slice(index * size, (index + 1) * size),
60 );
61
62const detailablePaths = (files: ReadonlyArray<Json.GitCafeDiffFile>) =>
63 files.filter((file) => !file.binary && !file.tooLarge).map((file) => file.path);
64
65const mergeStrategyOpen = (status: typeof Status.Type, strategy: string) =>
66 status.merge.permitted !== false &&
67 status.merge.strategies.includes(strategy) &&
68 !(status.merge.blockers ?? []).some((blocker) =>
69 (blocker.blockedStrategies ?? []).includes(strategy),
70 );
71
72const Id = TrimmedNonEmptyString.check(Schema.isPattern(/^[A-Za-z0-9_-]+$/u));
73const isId = Schema.is(Id);
74const Principal = Schema.Struct({ handle: TrimmedNonEmptyString });
75const Written = Schema.Struct({ id: Id });
76const Versioned = Schema.Struct({ version: NonNegativeInt });
77const CommentDetail = Schema.Struct({ id: Id, version: NonNegativeInt });
78const Status = Schema.Struct({
79 merge: Schema.Struct({
80 conflicts: Schema.Literals(["unknown", "conflicting"]),
81 fastForward: Schema.NullOr(Schema.Boolean),
82 strategies: Schema.Array(Schema.String),
83 permitted: Schema.optional(Schema.Boolean),
84 blockers: Schema.optional(
85 Schema.Array(
86 Schema.Struct({ blockedStrategies: Schema.optional(Schema.Array(Schema.String)) }),
87 ),
88 ),
89 }),
90 checks: Schema.Struct({
91 pending: NonNegativeInt,
92 failing: NonNegativeInt,
93 total: NonNegativeInt,
94 }),
95});
96const FilterOptions = Schema.Struct({
97 actors: Schema.Array(
98 Schema.Struct({ actorId: TrimmedNonEmptyString, handle: TrimmedNonEmptyString }),
99 ),
100});
101const encodeActorIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
102const BranchCommit = Schema.Struct({ oid: TrimmedNonEmptyString });
103const Snapshot = {
104 version: NonNegativeInt,
105 headOid: TrimmedNonEmptyString,
106 comparisonBaseOid: TrimmedNonEmptyString,
107};
108const Changes = Schema.Struct({
109 ...Snapshot,
110 items: Json.GitCafeDiffFiles,
111 next: Schema.NullOr(TrimmedNonEmptyString),
112});
113const DiffFiles = Schema.Struct({ ...Snapshot, items: Json.GitCafeDiffFiles });
114const DiffCursor = Schema.Struct({
115 version: NonNegativeInt,
116 headOid: TrimmedNonEmptyString,
117 baseOid: TrimmedNonEmptyString,
118 after: TrimmedNonEmptyString,
119});
120const encodeDiffCursor = Schema.encodeSync(Schema.fromJsonString(DiffCursor));
121const decodeDiffCursor = Schema.decodeEffect(Schema.fromJsonString(DiffCursor));
122const MergeOutcome = Schema.Struct({
123 id: Schema.String,
124 state: Schema.Literals(["accepted", "completed", "failed"]),
125 reason: Schema.optional(Schema.String),
126});
127const StackOutcome = Schema.Struct({ id: Schema.String, state: Schema.String });
128const FAILED_STACK_STATES = new Set(["failed", "stopped", "cancelled", "reconciliation_required"]);
129
130type PullRef = ProviderRepositoryRef & { readonly number: number };
131type Paged<A> = { readonly items: ReadonlyArray<A>; readonly next: string | null };
132
133function stackHeadsCurrent(
134 stack: Json.GitCafeStack,
135 input: { readonly number: number; readonly merge: boolean },
136 expected: ReadonlyArray<PullRequestStackHead>,
137): boolean {
138 const members = stack.members.toSorted((a, b) => a.position - b.position);
139 const index = members.findIndex((member) => member.pullRequestNumber === input.number);
140 if (index === -1) return false;
141 const moved = (input.merge ? members.slice(0, index + 1) : members).filter(
142 (member) => member.state !== "merged",
143 );
144 return (
145 moved.length === expected.length &&
146 moved.every(
147 (member) =>
148 member.headOid !== undefined &&
149 expected.some(
150 (head) => head.number === member.pullRequestNumber && head.headSha === member.headOid,
151 ),
152 )
153 );
154}
155
156const withDetails = (
157 files: ReadonlyArray<Json.GitCafeDiffFile>,
158 details: ReadonlyArray<Json.GitCafeDiffFile>,
159) => {
160 const byPath = new Map(details.map((file) => [file.path, file]));
161 return files.map((file) => byPath.get(file.path) ?? file);
162};
163
164/** @public Service construction is part of the canonical Effect module API. */
165export const make = Effect.gen(function* () {
166 const api = yield* GitCafeApi.GitCafeApi;
167
168 const failure = (operation: string, detail: string, cause?: unknown) =>
169 new PullRequestProviderError({
170 provider: SourceControlProviderKind.make("gitcafe"),
171 operation,
172 reason: "failed",
173 detail,
174 ...(cause === undefined ? {} : { cause }),
175 });
176
177 const repositoryPath = (
178 operation: string,
179 input: ProviderRepositoryRef,
180 ): Effect.Effect<string, PullRequestProviderError> =>
181 GitCafeHosts.isGitCafeHost(input.host) &&
182 GitCafeHosts.gitCafeRepositoryPath(input.repository) === input.repository
183 ? Effect.succeed(`/repos/${input.repository}`)
184 : Effect.fail(
185 failure(
186 operation,
187 `GitCafe serves owner/name repositories on ${GitCafeHosts.GITCAFE_HOSTS.join(" and ")}.`,
188 ),
189 );
190
191 const send = (
192 operation: string,
193 input: Pick<ProviderRepositoryRef, "host">,
194 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
195 ) =>
196 api.request({ ...request, host: input.host, operation }).pipe(
197 Effect.mapError(
198 (error) =>
199 new PullRequestProviderError({
200 provider: SourceControlProviderKind.make("gitcafe"),
201 operation,
202 reason: error.reason,
203 detail: error.detail,
204 cause: error,
205 }),
206 ),
207 );
208
209 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
210 operation: string,
211 input: Pick<ProviderRepositoryRef, "host">,
212 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
213 schema: S,
214 ) =>
215 send(operation, input, request).pipe(
216 Effect.flatMap((raw) =>
217 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
218 Effect.mapError((cause) =>
219 failure(operation, "GitCafe returned an unreadable response.", cause),
220 ),
221 ),
222 ),
223 );
224
225 const pullPath = (operation: string, input: PullRef) =>
226 repositoryPath(operation, input).pipe(Effect.map((base) => `${base}/pulls/${input.number}`));
227
228 const readPull = (operation: string, input: PullRef) =>
229 pullPath(operation, input).pipe(
230 Effect.flatMap((path) => read(operation, input, { path }, Json.GitCafePullDetail)),
231 );
232
233 const readPages = <S extends Schema.Codec<Paged<unknown>, unknown, never, never>>(
234 operation: string,
235 input: Pick<ProviderRepositoryRef, "host">,
236 path: string,
237 schema: S,
238 ) =>
239 Effect.gen(function* () {
240 const items: Array<S["Type"]["items"][number]> = [];
241 let next: string | null = null;
242 for (let page = 0; page < MAX_PAGES; page++) {
243 const query = new URLSearchParams({ limit: String(PAGE_SIZE) });
244 if (next !== null) query.set("after", next);
245 const batch: S["Type"] = yield* read(
246 operation,
247 input,
248 { path: `${path}?${query}` },
249 schema,
250 );
251 items.push(...batch.items);
252 const previous: string | null = next;
253 next = batch.next;
254 if (next === null || next === previous || batch.items.length === 0) break;
255 }
256 return { items, next };
257 });
258
259 const readComments = (operation: string, input: PullRef) =>
260 pullPath(operation, input).pipe(
261 Effect.flatMap((path) =>
262 readPages(operation, input, `${path}/comments`, Json.GitCafeComments),
263 ),
264 );
265
266 /**
267 * GitCafe's stack lists no heads, and they are what a land or restack is fenced on, so each
268 * open layer's pull is read.
269 */
270 const readStack = Effect.fn("GitCafePullRequestProvider.readStack")(function* (
271 operation: string,
272 input: PullRef,
273 ) {
274 const path = yield* pullPath(operation, input);
275 const { stack } = yield* read(
276 operation,
277 input,
278 { path: `${path}/stack` },
279 Json.GitCafeStackEnvelope,
280 );
281 if (stack === null) return null;
282 const members = yield* Effect.forEach(
283 stack.members,
284 (member) =>
285 member.state === "merged"
286 ? Effect.succeed(member)
287 : readPull(operation, { ...input, number: member.pullRequestNumber }).pipe(
288 Effect.map((pull) =>
289 pull.headOid == null ? member : { ...member, headOid: pull.headOid },
290 ),
291 ),
292 { concurrency: 4 },
293 );
294 return { ...stack, members };
295 });
296
297 const readDiffFiles = Effect.fn("GitCafePullRequestProvider.readDiffFiles")(function* (
298 input: PullRef,
299 revision: { readonly version: number; readonly headOid: string; readonly baseOid: string },
300 paths: ReadonlyArray<string>,
301 ) {
302 if (paths.length === 0) return [];
303 const path = yield* pullPath("getDiff", input);
304 const files = yield* read(
305 "getDiff",
306 input,
307 {
308 method: "POST",
309 path: `${path}/diff-files`,
310 body: { paths, expectedVersion: revision.version },
311 },
312 DiffFiles,
313 );
314 if (
315 files.version !== revision.version ||
316 files.headOid !== revision.headOid ||
317 files.comparisonBaseOid !== revision.baseOid
318 )
319 return yield* failure(
320 "getDiff",
321 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
322 );
323 return files.items;
324 });
325
326 const runStackAction = Effect.fn("GitCafePullRequestProvider.runStackAction")(function* (
327 input: Parameters<PullRequestProviderApi["runAction"]>[0] & { readonly stackNumber: number },
328 ) {
329 const land = input.action === "merge";
330 const operation = land ? "landStackThrough" : "restackStack";
331 if (!land && input.action !== "update-branch")
332 return yield* failure(operation, `GitCafe cannot ${input.action} a stack.`);
333 const stack = yield* readStack(operation, input);
334 if (
335 stack === null ||
336 stack.number !== input.stackNumber ||
337 input.expectedStackHeads === undefined ||
338 !stackHeadsCurrent(stack, { number: input.number, merge: land }, input.expectedStackHeads)
339 )
340 return yield* failure(
341 operation,
342 "The stack changed since it was read. Refresh it and try again.",
343 );
344 const base = yield* repositoryPath(operation, input);
345 const outcome = yield* read(
346 operation,
347 input,
348 {
349 method: "POST",
350 path: `${base}/pulls/stacks/${stack.number}/${land ? "land-through" : "restack"}`,
351 body: land
352 ? {
353 expectedRevision: stack.revision,
354 requestId: yield* randomUuidV4,
355 throughPullRequestNumber: input.number,
356 strategy: input.mergeMethod ?? "merge",
357 }
358 : { expectedRevision: stack.revision, requestId: yield* randomUuidV4 },
359 },
360 StackOutcome,
361 );
362 if (FAILED_STACK_STATES.has(outcome.state))
363 return yield* failure(operation, `GitCafe's stack operation ${outcome.state}.`);
364 });
365
366 const readLineStats = Effect.fn("GitCafePullRequestProvider.readLineStats")(function* (
367 input: PullRef,
368 version: number,
369 ) {
370 const path = yield* pullPath("getChangeRequest", input);
371 const files: Array<Json.GitCafeDiffFile> = [];
372 let revision: { version: number; headOid: string; baseOid: string } | undefined;
373 let after: string | null = null;
374 for (let page = 0; page < MAX_CHANGE_PAGES; page++) {
375 const query = new URLSearchParams({ expectedVersion: String(version), limit: "500" });
376 if (after !== null) query.set("after", after);
377 const batch: typeof Changes.Type = yield* read(
378 "getChangeRequest",
379 input,
380 { path: `${path}/changes?${query}` },
381 Changes,
382 );
383 revision ??= {
384 version: batch.version,
385 headOid: batch.headOid,
386 baseOid: batch.comparisonBaseOid,
387 };
388 files.push(...batch.items);
389 const previous: string | null = after;
390 after = batch.next;
391 if (after === null || after === previous || batch.items.length === 0) break;
392 }
393 const counted =
394 files.some((file) => file.additions !== undefined) ||
395 files.length > LINE_STATS_MAX_FILES ||
396 revision === undefined
397 ? files
398 : (yield* Effect.forEach(
399 chunk(detailablePaths(files), DIFF_FILES_BATCH),
400 (paths) => readDiffFiles(input, revision, paths),
401 { concurrency: 4 },
402 ).pipe(Effect.orElseSucceed(() => [[]]))).flat();
403 return {
404 changedFiles: files.length,
405 additions: counted.reduce((total, file) => total + (file.additions ?? 0), 0),
406 deletions: counted.reduce((total, file) => total + (file.deletions ?? 0), 0),
407 };
408 });
409
410 const merge = Effect.fn("GitCafePullRequestProvider.merge")(function* (
411 input: Parameters<PullRequestProviderApi["runAction"]>[0],
412 ) {
413 const pull = yield* readPull("merge", input);
414 if (pull.state === "merged") return;
415 if (pull.mergeRoute === "unsupported")
416 return yield* failure("merge", "This GitCafe pull request has no supported merge route.");
417 const base = yield* repositoryPath("merge", input);
418 // GitCafe observes the base only for merges it routes to the provider; a native merge is
419 // fenced on the target branch's current commit.
420 const baseOid =
421 pull.mergeRoute === "provider"
422 ? pull.observedBaseOid
423 : (yield* read(
424 "merge",
425 input,
426 {
427 path: `${base}/commit?ref=${encodeURIComponent(`refs/heads/${pull.targetBranch}`)}`,
428 },
429 BranchCommit,
430 )).oid;
431 if (pull.headOid === null || baseOid == null)
432 return yield* failure(
433 "merge",
434 "GitCafe has not reported the pull request's head and base yet. Refresh and try again.",
435 );
436 const path = yield* pullPath("merge", input);
437 const outcome = yield* read(
438 "merge",
439 input,
440 {
441 method: "POST",
442 path: `${path}/merge`,
443 body: {
444 requestId: yield* randomUuidV4,
445 expectedVersion: pull.version,
446 headOid: pull.headOid,
447 baseOid,
448 strategy: input.mergeMethod ?? "merge",
449 },
450 },
451 MergeOutcome,
452 );
453 if (outcome.state === "failed")
454 return yield* failure("merge", outcome.reason ?? "GitCafe could not merge the pull request.");
455 });
456
457 const provider: PullRequestProviderApi = {
458 kind: SourceControlProviderKind.make("gitcafe"),
459 capabilities: CAPABILITIES,
460 getViewer: (input) =>
461 read(
462 "getViewer",
463 { host: input.host ?? "git.cafe" },
464 { path: "/auth/principal" },
465 Principal,
466 ).pipe(Effect.map((principal) => principal.handle)),
467 listChangeRequests: Effect.fn("GitCafePullRequestProvider.listChangeRequests")(
468 function* (input) {
469 const base = yield* repositoryPath("listChangeRequests", input);
470 const involved = input.involvement === "authored" || input.involvement === "reviewing";
471 let actorId: string | undefined;
472 if (involved) {
473 // A host narrows as far as it can: when the actor list can't be read, the listing comes
474 // back unnarrowed and the page's own involvement filter does the rest. A refused token
475 // or a rate limit still fails, since the service acts on those for the whole host.
476 const options = yield* read(
477 "listChangeRequests",
478 input,
479 { path: `${base}/filter-options` },
480 FilterOptions,
481 ).pipe(
482 Effect.map(Option.some),
483 Effect.catchTags({
484 PullRequestProviderError: (error) =>
485 error.reason === "unauthenticated" || error.reason === "rate-limited"
486 ? Effect.fail(error)
487 : Effect.succeed(Option.none()),
488 }),
489 );
490 if (Option.isSome(options)) {
491 actorId = options.value.actors.find(
492 (actor) => actor.handle.toLowerCase() === input.viewer.toLowerCase(),
493 )?.actorId;
494 if (actorId === undefined) return { items: [], truncated: false, continues: false };
495 }
496 }
497 const limit = Math.max(1, input.limit);
498 const items: Array<Json.GitCafePull> = [];
499 let next: string | null = null;
500 do {
501 const query = new URLSearchParams({
502 limit: String(Math.min(PAGE_SIZE, limit - items.length)),
503 sort: "newest",
504 });
505 if (input.state !== "all") query.set("state", input.state);
506 if (input.query?.trim()) query.set("q", input.query.trim());
507 if (actorId !== undefined)
508 query.set(
509 input.involvement === "reviewing" ? "reviewers" : "authors",
510 encodeActorIds([actorId]),
511 );
512 if (next !== null) query.set("after", next);
513 const page: typeof Json.GitCafePulls.Type = yield* read(
514 "listChangeRequests",
515 input,
516 { path: `${base}/pulls?${query}` },
517 Json.GitCafePulls,
518 );
519 items.push(...page.items);
520 next = page.items.length === 0 ? null : page.next;
521 } while (next !== null && items.length < limit);
522 return {
523 items: items.slice(0, limit).map((pull) => {
524 const item = Json.toChangeRequest(pull, input);
525 return input.involvement === "reviewing" && actorId !== undefined
526 ? {
527 ...item,
528 reviewRequestLogins: [...new Set([...item.reviewRequestLogins, input.viewer])],
529 }
530 : item;
531 }),
532 truncated: next !== null,
533 continues: false,
534 };
535 },
536 ),
537 getChangeRequestSummary: (input) =>
538 readPull("getChangeRequestSummary", input).pipe(
539 Effect.map((pull) => ({
540 ...Json.toChangeRequest(pull, input),
541 closedAt: pull.closedAt,
542 mergedAt: pull.mergedAt,
543 })),
544 ),
545 getChangeRequest: Effect.fn("GitCafePullRequestProvider.getChangeRequest")(function* (input) {
546 const pull = yield* readPull("getChangeRequest", input);
547 const path = yield* pullPath("getChangeRequest", input);
548 const base = yield* repositoryPath("getChangeRequest", input);
549 const [status, checks, changes] = yield* Effect.all(
550 [
551 read("getChangeRequest", input, { path: `${path}/status` }, Status),
552 pull.headOid === null
553 ? Effect.succeed(null)
554 : readPages(
555 "getChangeRequest",
556 input,
557 `${base}/commits/${encodeURIComponent(pull.headOid)}/checks`,
558 Json.GitCafeChecks,
559 ),
560 pull.headOid === null
561 ? Effect.succeed(null)
562 : readLineStats(input, pull.version).pipe(Effect.orElseSucceed(() => null)),
563 ],
564 { concurrency: 3 },
565 );
566 const permissions = Json.toViewerPermissions(pull);
567 return {
568 ...Json.toChangeRequest(pull, input),
569 headSha: pull.headOid,
570 body: pull.description ?? "",
571 ...(pull.sourceRepo === null
572 ? {}
573 : { headRepositoryNameWithOwner: `${pull.sourceRepo.owner}/${pull.sourceRepo.name}` }),
574 additions: changes?.additions ?? 0,
575 deletions: changes?.deletions ?? 0,
576 changedFiles: changes?.changedFiles ?? 0,
577 closedAt: pull.closedAt,
578 mergedAt: pull.mergedAt,
579 reviewers: Json.toReviewers(pull, input.host),
580 checks: checks === null ? [] : Json.toChecks(checks),
581 ...(status.checks.total === 0
582 ? {}
583 : {
584 checksState:
585 status.checks.failing > 0
586 ? ("failing" as const)
587 : status.checks.pending > 0
588 ? ("pending" as const)
589 : ("passing" as const),
590 }),
591 mergeability:
592 status.merge.conflicts === "conflicting"
593 ? ("conflicting" as const)
594 : ("unknown" as const),
595 baseComparison:
596 status.merge.fastForward === null
597 ? ("unknown" as const)
598 : status.merge.fastForward
599 ? ("up-to-date" as const)
600 : ("behind" as const),
601 mergeCapabilities: {
602 merge: mergeStrategyOpen(status, "merge"),
603 squash: mergeStrategyOpen(status, "squash"),
604 rebase: mergeStrategyOpen(status, "rebase"),
605 },
606 viewerPermissions:
607 status.merge.permitted === false
608 ? { ...permissions, actions: permissions.actions.filter((a) => a !== "merge") }
609 : permissions,
610 };
611 }),
612 getChangeRequestStack: (input) =>
613 readStack("getChangeRequestStack", input).pipe(
614 Effect.map((stack) => (stack === null ? null : Json.toStack(stack, input))),
615 ),
616 getChangeRequestActivity: Effect.fn("GitCafePullRequestProvider.getChangeRequestActivity")(
617 function* (input) {
618 const pull = yield* readPull("getChangeRequestActivity", input);
619 const path = yield* pullPath("getChangeRequestActivity", input);
620 const operation = "getChangeRequestActivity";
621 const [comments, reviews, commits, reactions] = yield* Effect.all(
622 [
623 readComments(operation, input),
624 readPages(operation, input, `${path}/reviews`, Json.GitCafeReviews),
625 pull.headOid === null
626 ? Effect.succeed({ items: [], next: null })
627 : readPages(operation, input, `${path}/commits`, Json.GitCafeCommits),
628 readPages(operation, input, `${path}/reactions/`, Json.GitCafeReactions).pipe(
629 Effect.orElseSucceed(() => undefined),
630 ),
631 ],
632 { concurrency: 4 },
633 );
634 return Json.toActivity({
635 comments,
636 reviews,
637 commits: { ...commits, truncated: commits.next !== null, headOid: pull.headOid ?? "" },
638 host: input.host,
639 ...(pull.headOid === null ? {} : { headOid: pull.headOid }),
640 ...(reactions === undefined ? {} : { reactions }),
641 });
642 },
643 ),
644 getViewerPermissions: (input) =>
645 readPull("getViewerPermissions", input).pipe(Effect.map(Json.toViewerPermissions)),
646 getDiff: Effect.fn("GitCafePullRequestProvider.getDiff")(function* (input) {
647 if (input.commit !== undefined)
648 return yield* failure("getDiff", "GitCafe commit diffs are not supported yet.");
649 const cursor =
650 input.cursor === undefined
651 ? null
652 : yield* decodeDiffCursor(input.cursor).pipe(
653 Effect.mapError((cause) => failure("getDiff", "Invalid GitCafe diff cursor.", cause)),
654 );
655 const version = cursor?.version ?? (yield* readPull("getDiff", input)).version;
656 const path = yield* pullPath("getDiff", input);
657 const query = new URLSearchParams({
658 expectedVersion: String(version),
659 limit: String(DIFF_FILES_BATCH),
660 });
661 if (cursor !== null) query.set("after", cursor.after);
662 const page = yield* read("getDiff", input, { path: `${path}/changes?${query}` }, Changes);
663 if (
664 page.version !== version ||
665 (cursor !== null &&
666 (cursor.headOid !== page.headOid || cursor.baseOid !== page.comparisonBaseOid))
667 )
668 return yield* failure(
669 "getDiff",
670 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
671 );
672 const revision = { version, headOid: page.headOid, baseOid: page.comparisonBaseOid };
673 const details = yield* readDiffFiles(input, revision, detailablePaths(page.items));
674 return {
675 ...Json.toDiff({ items: withDetails(page.items, details) }),
676 nextCursor: page.next === null ? null : encodeDiffCursor({ ...revision, after: page.next }),
677 };
678 }),
679 runAction: Effect.fn("GitCafePullRequestProvider.runAction")(function* (input) {
680 if (input.stackNumber !== undefined)
681 return yield* runStackAction({ ...input, stackNumber: input.stackNumber });
682 switch (input.action) {
683 case "merge":
684 return yield* merge(input);
685 case "ready":
686 case "draft":
687 case "close":
688 case "reopen": {
689 const pull = yield* readPull(input.action, input);
690 const path = yield* pullPath(input.action, input);
691 yield* send(input.action, input, {
692 method: "POST",
693 path: `${path}/${input.action}`,
694 body: { expectedVersion: pull.version },
695 });
696 return;
697 }
698 default:
699 return yield* failure(input.action, `GitCafe cannot ${input.action} from T3 Code.`);
700 }
701 }),
702 updateChangeRequest: Effect.fn("GitCafePullRequestProvider.updateChangeRequest")(
703 function* (input) {
704 const pull = yield* readPull("updateChangeRequest", input);
705 const path = yield* pullPath("updateChangeRequest", input);
706 yield* read(
707 "updateChangeRequest",
708 input,
709 {
710 method: "PATCH",
711 path,
712 body: {
713 expectedVersion: pull.version,
714 ...(input.title === undefined ? {} : { title: input.title }),
715 ...(input.body === undefined ? {} : { description: input.body }),
716 },
717 },
718 Versioned,
719 );
720 },
721 ),
722 comment: (input) =>
723 pullPath("comment", input).pipe(
724 Effect.flatMap((path) =>
725 read(
726 "comment",
727 input,
728 { method: "POST", path: `${path}/comments/`, body: { body: input.body } },
729 Written,
730 ),
731 ),
732 Effect.asVoid,
733 ),
734 updateComment: Effect.fn("GitCafePullRequestProvider.updateComment")(function* (input) {
735 if (!isId(input.commentId))
736 return yield* failure("updateComment", "GitCafe comment ids are opaque slugs.");
737 const path = `${yield* pullPath("updateComment", input)}/comments/${input.commentId}`;
738 const detail = yield* read("updateComment", input, { path: `${path}/detail` }, CommentDetail);
739 yield* read(
740 "updateComment",
741 input,
742 { method: "PATCH", path, body: { body: input.body, expectedVersion: detail.version } },
743 Written,
744 );
745 }),
746 submitReview: Effect.fn("GitCafePullRequestProvider.submitReview")(function* (input) {
747 if (input.comments.length > 0)
748 return yield* failure("submitReview", "GitCafe line comments are not supported yet.");
749 const pull = yield* readPull("submitReview", input);
750 if (pull.headOid === null)
751 return yield* failure("submitReview", "GitCafe has not reported the pull request's head.");
752 const path = yield* pullPath("submitReview", input);
753 yield* read(
754 "submitReview",
755 input,
756 {
757 method: "POST",
758 path: `${path}/reviews`,
759 body: {
760 verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict,
761 ...(input.body.length === 0 ? {} : { body: input.body }),
762 commitOid: pull.headOid,
763 expectedVersion: pull.version,
764 requestId: yield* randomUuidV4,
765 },
766 },
767 Written,
768 );
769 }),
770 listReviewerCandidates: () =>
771 Effect.fail(
772 failure("listReviewerCandidates", "GitCafe reviewer requests are not supported."),
773 ),
774 setReviewerRequest: () =>
775 Effect.fail(failure("setReviewerRequest", "GitCafe reviewer requests are not supported.")),
776 replyToThread: Effect.fn("GitCafePullRequestProvider.replyToThread")(function* (input) {
777 if (!isId(input.threadId))
778 return yield* failure("replyToThread", "GitCafe thread ids are opaque slugs.");
779 const path = yield* pullPath("replyToThread", input);
780 yield* read(
781 "replyToThread",
782 input,
783 {
784 method: "POST",
785 path: `${path}/comments/${input.threadId}/replies`,
786 body: { body: input.body },
787 },
788 Written,
789 );
790 }),
791 setReaction: Effect.fn("GitCafePullRequestProvider.setReaction")(function* (input) {
792 const path = `${yield* pullPath("setReaction", input)}/reactions/`;
793 const subject =
794 input.subjectId === undefined
795 ? { kind: "pull_request" as const, id: (yield* readPull("setReaction", input)).id }
796 : { kind: "pull_request_comment" as const, id: input.subjectId };
797 const reactions = yield* readPages("setReaction", input, path, Json.GitCafeReactions);
798 const mine = reactions.items.find(
799 (item) =>
800 item.subject.kind === subject.kind &&
801 item.subject.id === subject.id &&
802 item.emoji.kind === "unicode" &&
803 Json.reactionContent(item.emoji.value) === input.content,
804 )?.viewerReactionId;
805 if (input.reacted === (mine != null)) return;
806 if (input.reacted) {
807 yield* send("setReaction", input, {
808 method: "POST",
809 path,
810 body: { subject, emoji: { kind: "unicode", value: Json.REACTION_EMOJI[input.content] } },
811 });
812 return;
813 }
814 if (mine == null) return;
815 if (!isId(mine))
816 return yield* failure("setReaction", "GitCafe returned an unreadable reaction id.");
817 yield* send("setReaction", input, { method: "DELETE", path: `${path}${mine}` });
818 }),
819 setThreadResolution: Effect.fn("GitCafePullRequestProvider.setThreadResolution")(
820 function* (input) {
821 const comments = yield* readComments("setThreadResolution", input);
822 const root = comments.items.find(
823 (comment) => comment.id === input.threadId && comment.threadId === input.threadId,
824 );
825 if (root === undefined || root.version === undefined || !isId(root.id))
826 return yield* failure("setThreadResolution", "GitCafe did not return the thread root.");
827 if (input.resolved === (root.resolvedAt !== null)) return;
828 const path = yield* pullPath("setThreadResolution", input);
829 yield* read(
830 "setThreadResolution",
831 input,
832 {
833 method: "POST",
834 path: `${path}/comments/${root.id}/${input.resolved ? "resolve" : "unresolve"}`,
835 body: { expectedVersion: root.version },
836 },
837 Written,
838 );
839 },
840 ),
841 };
842 return provider;
843});