import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { afterEach, assert, expect, it, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import * as Redacted from "effect/Redacted";
import { HttpClient, HttpClientResponse } from "effect/http";
import * as GitHubRest from "./GitHubRest.ts";
import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
import * as GitHubCredentials from "./GitHubCredentials.ts";
import * as GitHubQuota from "./GitHubQuota.ts";
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
import { KnownWorkflowRuns } from "./gitHubConditionalChecks.ts";
import * as GitHubAppAccess from "./GitHubAppAccess.ts";
import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
enabled: false,
token: () => Effect.succeedNone,
invalidate: () => Effect.void,
});
const mockedAppToken = vi.fn<(host: string) => Effect.Effect<Option.Option<string>>>(
() => Effect.succeedNone,
);
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
// GitHub's field-level reviewer refusal; the surrounding response data is synthetic.
const refusedReviewer = {
type: "FORBIDDEN",
message: "Resource not accessible by integration",
path: ["repository", "pullRequest", "reviewRequests", "nodes", 0, "requestedReviewer"],
};
const pullRequestInput = { cwd: "/w", repository: "acme/web", host: "github.com", number: 7 };
type PullRequestRead = (
input: typeof pullRequestInput,
) => Effect.Effect<unknown, GitHubPullRequestApi.GitHubPullRequestApiError>;
const refusedReviewerResponse = () =>
Effect.succeed(output(encodeJson({ ...coreResponse(), errors: [refusedReviewer] })));
const coreResponse = (pullRequest: Readonly<Record<string, unknown>> = {}) => ({
data: {
repository: {
mergeCommitAllowed: true,
squashMergeAllowed: false,
rebaseMergeAllowed: true,
autoMergeAllowed: true,
viewerPermission: "WRITE",
pullRequest: {
number: 7,
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
body: "",
isDraft: false,
mergeable: "MERGEABLE",
mergeStateStatus: "BLOCKED",
reviewDecision: null,
additions: 0,
deletions: 0,
changedFiles: 0,
mergedAt: null,
closedAt: null,
isCrossRepository: false,
maintainerCanModify: true,
headRepositoryOwner: null,
headRepository: null,
headRef: null,
author: null,
autoMergeRequest: null,
headRefName: "feature",
baseRefName: "main",
headRefOid: "abc123",
state: "OPEN",
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
viewerCanUpdate: true,
viewerDidAuthor: false,
viewerCanUpdateBranch: true,
baseRef: { compare: { behindBy: 2 } },
reviewRequests: { nodes: [] },
labels: { nodes: [] },
commits: { nodes: [] },
...pullRequest,
},
},
},
});
type ApiCall =
| {
readonly kind: "graphql";
readonly authorization: string | undefined;
readonly partial?: boolean;
readonly operationName?: string;
readonly host: string;
readonly operation: string;
readonly query: string;
readonly variables?: Readonly<Record<string, unknown>>;
}
| ({ readonly kind: "rest" } & GitHubRest.GitHubRestInput);
type ApiAnswer = Effect.Effect<GitHubRest.GitHubRestResponse, GitHubRequestPolicy.GitHubApiError>;
const mockedExecute = vi.fn<(call: ApiCall) => ApiAnswer>();
const defaultCredential = (host: string) =>
Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:token` });
const mockedCredential =
vi.fn<
(
host: string,
) => Effect.Effect<GitHubRequestPolicy.GitHubHeldCredential, GitHubRequestPolicy.GitHubApiError>
>(defaultCredential);
const mockedStackMemberships = vi.fn<(call: ApiCall) => ApiAnswer>(() =>
Effect.succeed(output('{"data":{}}')),
);
const mockApi = Layer.succeed(
GitHubRest.GitHubRest,
GitHubRest.GitHubRest.of({
rest: (input) => mockedExecute({ kind: "rest", ...input }),
credential: (host) => mockedCredential(host),
appCredential: () => Effect.succeedNone,
}),
);
const mockHttp = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Effect.gen(function* () {
const host = new URL(request.url).hostname.replace(/^api\./, "");
const sent =
request.body._tag === "Uint8Array"
? (JSON.parse(new TextDecoder().decode(request.body.body)) as {
readonly query: string;
readonly operationName: string;
readonly variables: Readonly<Record<string, unknown>>;
})
: { query: "", operationName: "", variables: {} };
const call: ApiCall = {
kind: "graphql",
authorization: request.headers["authorization"],
host,
operation: "batch",
operationName: sent.operationName,
query: sent.query,
variables: sent.variables,
partial: true,
};
const answer = yield* (
sent.query.startsWith("query PullRequestStackMembership(")
? mockedStackMemberships
: mockedExecute
)(call).pipe(
Effect.catchTags({
GitHubApiResponseError: (error) =>
Effect.succeed(output('{"message":"Bad gateway"}', false, false, {}, error.status)),
}),
Effect.orDie,
);
// Empty mutation mocks still need the selected GraphQL root field.
const body =
answer.body === "{}" && sent.query.startsWith("mutation ")
? encodeJson(mutationAnswer(sent.query))
: answer.body;
return HttpClientResponse.fromWeb(
request,
new Response(body, {
status: answer.status,
headers: { "content-type": "application/json", ...answer.headers },
}),
);
}),
),
);
const layer = it.layer(
GitHubPullRequestApi.layer.pipe(
Layer.provideMerge(GitHubAppAccess.layer),
Layer.provideMerge(mockApi),
Layer.provideMerge(GitHubRequestPolicy.layer),
Layer.provideMerge(
Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
enabled: false,
token: (host) => mockedAppToken(host),
invalidate: () => Effect.void,
}),
),
Layer.provideMerge(GitHubQuota.layer),
Layer.provideMerge(SourceControlRateLimit.layer),
Layer.provideMerge(mockHttp),
Layer.provideMerge(
Layer.succeed(GitHubCredentials.GitHubCredentials, {
get: (host) =>
mockedCredential(host).pipe(
Effect.map((held) => ({ source: "gh" as const, ...held, host })),
Effect.mapError(() => new GitHubCredentials.GitHubCliMissingError({ host })),
),
saved: () => Effect.succeedNone,
fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
invalidate: () => Effect.void,
}),
),
Layer.provide(NodeCrypto.layer),
Layer.provide(TestSourceControlHost.layer()),
Layer.provide(NodeServices.layer),
),
);
function output(
body: string,
truncated = false,
invalidUtf8 = false,
headers: Readonly<Record<string, string>> = {},
status = 200,
): GitHubRest.GitHubRestResponse {
return { status, headers, body, truncated, invalidUtf8 };
}
function graphqlQuota(remaining: number, resetAt = "2099-08-13T14:00:00Z") {
return {
"x-ratelimit-resource": "graphql",
"x-ratelimit-limit": "5000",
"x-ratelimit-remaining": String(remaining),
"x-ratelimit-reset": String(Date.parse(resetAt) / 1000),
};
}
const rowDefaults = {
author: null,
state: "OPEN",
isDraft: false,
mergeable: "UNKNOWN",
reviewDecision: null,
latestReviews: { nodes: [] },
mergedAt: null,
reviewRequests: { nodes: [] },
labels: { nodes: [] },
commits: { nodes: [] },
};
const lastPage = { hasNextPage: false, endCursor: null };
function rows(
count: number,
firstNumber: number,
overrides: (number: number) => Readonly<Record<string, unknown>> = () => ({}),
): ReadonlyArray<Record<string, unknown>> {
return Array.from({ length: count }, (_, index) => {
const number = firstNumber + index;
const { reviewRequests, checks, ...rest } = overrides(number) as {
reviewRequests?: ReadonlyArray<Record<string, string>>;
checks?: string;
} & Record<string, unknown>;
return {
...rowDefaults,
number,
title: `Pull request ${number}`,
url: `https://github.com/acme/web/pull/${number}`,
headRefName: "feat/page",
baseRefName: "main",
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
repository: { nameWithOwner: "acme/web" },
...(reviewRequests === undefined
? {}
: {
reviewRequests: {
nodes: reviewRequests.map((requestedReviewer) => ({
requestedReviewer: {
__typename: "slug" in requestedReviewer ? "Team" : "User",
...requestedReviewer,
},
})),
},
}),
...(checks === undefined
? {}
: { commits: { nodes: [{ commit: { statusCheckRollup: { state: checks } } }] } }),
...rest,
};
});
}
function pullRequests(
count: number,
firstNumber: number,
overrides?: (number: number) => Readonly<Record<string, unknown>>,
): string {
return encodeJson({
data: {
search: { pageInfo: lastPage, nodes: rows(count, firstNumber, overrides) },
},
});
}
function listedPullRequests(
count: number,
firstNumber: number,
overrides?: (number: number) => Readonly<Record<string, unknown>>,
): string {
return encodeJson({
data: {
repository: {
pullRequests: {
pageInfo: lastPage,
nodes: rows(count, firstNumber, overrides),
},
},
},
});
}
const emptySearch = () => output(pullRequests(0, 1));
const emptyList = () => output(listedPullRequests(0, 1));
function pullRequestFiles(count: number, firstIndex: number): string {
return encodeJson(
Array.from({ length: count }, (_, index) => ({
filename: `src/file${firstIndex + index}.ts`,
status: "modified",
patch: "@@ -1 +1 @@\n-old\n+new",
})),
);
}
function threadComments(
ids: ReadonlyArray<string>,
endCursor: string | null,
totalCount = ids.length,
author: Readonly<Record<string, unknown>> | null = null,
) {
return {
totalCount,
pageInfo: { hasNextPage: endCursor !== null, endCursor },
nodes: ids.map((id) => ({
id,
author,
body: id,
createdAt: "2026-07-01T00:00:00Z",
lastEditedAt: null,
url: `https://github.com/acme/web/pull/7#discussion_${id}`,
reactionGroups: [],
})),
};
}
function thread(id: string, ...commentIds: ReadonlyArray<string>) {
return {
id,
path: "src/a.ts",
line: 1,
diffSide: "RIGHT",
isResolved: false,
isOutdated: false,
comments: threadComments(commentIds, null),
};
}
function reviewThreadsPage(
nodes: ReadonlyArray<Record<string, unknown>>,
endCursor: string | null,
requestedReviewers: ReadonlyArray<Record<string, unknown>> = [],
): string {
return encodeJson({
data: {
viewer: { login: "viewer" },
repository: {
pullRequest: {
reviewThreads: {
totalCount: nodes.length,
pageInfo: { hasNextPage: endCursor !== null, endCursor },
nodes,
},
viewerCanUpdate: true,
viewerDidAuthor: false,
author: null,
reactionGroups: [],
comments: { nodes: [] },
reviews: { nodes: [] },
reviewRequests: {
nodes: requestedReviewers.map((requestedReviewer) => ({ requestedReviewer })),
},
latestReviews: { nodes: [] },
reviewDismissals: { pageInfo: lastPage, nodes: [] },
commits: { nodes: [] },
},
},
},
});
}
function threadCommentsPage(
ids: ReadonlyArray<string>,
endCursor: string | null,
totalCount: number,
pullRequestId = "PR_7",
): string {
return encodeJson({
data: {
viewer: { login: "viewer" },
repository: { pullRequest: { id: "PR_7" } },
node: {
__typename: "PullRequestReviewThread",
pullRequest: { id: pullRequestId },
comments: threadComments(ids, endCursor, totalCount),
},
},
});
}
const diffRefused = new GitHubRequestPolicy.GitHubApiResponseError({
host: "github.com",
operation: "getPullRequestDiff",
status: 406,
});
function callAt(index: number): ApiCall {
const call = mockedExecute.mock.calls[index];
assert.isDefined(call);
return call[0];
}
function varsAt(index: number): Readonly<Record<string, unknown>> {
const call = callAt(index);
assert.strictEqual(call.kind, "graphql");
return call.kind === "graphql" ? (call.variables ?? {}) : {};
}
function queryAt(index: number): string {
const call = callAt(index);
return call.kind === "graphql" ? call.query : "";
}
function pathAt(index: number): string {
const call = callAt(index);
return call.kind === "rest" ? call.path : "";
}
function searchOfCall(index: number): string | undefined {
const q = callAt(index).kind === "graphql" ? varsAt(index)["q"] : undefined;
return typeof q === "string" ? q : undefined;
}
function searchItem(number: number, repository: string, updatedAt: string) {
return {
...rowDefaults,
number,
title: `Pull request ${number}`,
url: `https://github.com/${repository}/pull/${number}`,
author: {
__typename: "User",
login: "octocat",
avatarUrl: "https://avatars/octocat",
name: null,
},
headRefName: "feat/page",
baseRefName: "main",
state: "OPEN",
isDraft: false,
mergeable: "MERGEABLE",
createdAt: "2026-07-01T00:00:00Z",
updatedAt,
repository: { nameWithOwner: repository },
reviewRequests: { nodes: [{ requestedReviewer: { __typename: "User", login: "hubot" } }] },
labels: { nodes: [{ name: "bug", color: "ff0000" }] },
};
}
function searchPage(nodes: ReadonlyArray<unknown>, hasNextPage = false) {
return output(
encodeJson({
data: {
search: { pageInfo: { hasNextPage, endCursor: hasNextPage ? "next" : null }, nodes },
},
}),
);
}
const searchQueryOfCall = searchOfCall;
function matches(call: ApiCall, needle: string): boolean {
return call.kind === "graphql"
? call.operationName === needle || call.query.includes(needle)
: call.path.includes(needle);
}
function route(...routes: ReadonlyArray<readonly [needle: string, body: unknown]>): void {
mockedExecute.mockImplementation((call) => {
const match = routes.find(([needle]) => matches(call, needle));
return Effect.succeed(
output(
match !== undefined
? encodeJson(match[1])
: call.kind === "graphql" && call.query.startsWith("mutation ")
? encodeJson(mutationAnswer(call.query))
: "{}",
),
);
});
}
function mutationAnswer(query: string) {
const root = /\)\{(\w+)(?:\(|\{|@)/.exec(query)?.[1];
return { data: root === undefined ? {} : { [root]: null } };
}
function variablesOf(needle: string): ReadonlyArray<Readonly<Record<string, unknown>>> {
return mockedExecute.mock.calls.flatMap(([call]) =>
call.kind === "graphql" && matches(call, needle) ? [call.variables ?? {}] : [],
);
}
function restCallsTo(needle: string): ReadonlyArray<GitHubRest.GitHubRestInput> {
return mockedExecute.mock.calls.flatMap(([call]) =>
call.kind === "rest" && call.path.includes(needle) ? [call] : [],
);
}
/** Route before the node-ID lookup, whose document is contained in this scope query. */
const SUBJECT_SCOPE_QUERY = "PullRequestSubject";
const subjectScope = (subjectId: string, pullRequestId: string) => ({
data: {
repository: { pullRequest: { id: pullRequestId } },
node: { __typename: "IssueComment", id: subjectId, pullRequest: { id: pullRequestId } },
},
});
const checkRun = (fields: Record<string, unknown>) => ({
__typename: "CheckRun",
name: "",
status: "COMPLETED",
conclusion: null,
startedAt: null,
completedAt: null,
detailsUrl: null,
checkSuite: { workflowRun: null },
...fields,
});
const checkContextsPage = (
nodes: ReadonlyArray<Record<string, unknown>>,
endCursor: string | null,
headRefOid = "abc123",
) =>
encodeJson({
data: {
repository: {
pullRequest: {
headRefOid,
commits: {
nodes: [
{
commit: {
statusCheckRollup: {
contexts: { nodes, pageInfo: { hasNextPage: endCursor !== null, endCursor } },
},
},
},
],
},
},
},
},
});
const pullRequestRefs = encodeJson({ base: { sha: "a1b2c3d" }, head: { sha: "b1c2d3e" } });
const pullRequestMergeBase = encodeJson({ merge_base_commit: { sha: "c1d2e3f" } });
const crossRepositoryDetail = (headRefOid = "abc123") =>
coreResponse({
headRefName: "feat/page",
headRefOid,
isCrossRepository: true,
headRepositoryOwner: { __typename: "User", login: "octocat" },
});
const heads = (numbers: ReadonlyArray<number>) => ({
data: {
repository: {
pullRequests: {
pageInfo: { hasNextPage: false, endCursor: null },
nodes: numbers.map((number) => ({
number,
headRefOid: "abc123",
isCrossRepository: true,
headRepositoryOwner: { __typename: "User", login: "octocat" },
})),
},
},
},
});
const workflowRuns = (ids: ReadonlyArray<number>) => ({
workflow_runs: ids.map((id) => ({
id,
name: id === 10 ? "build" : `run ${id}`,
html_url: `https://example.com/${id}`,
})),
});
function workflowApprovalRoutes(
detail: () => unknown,
headsAnswer: unknown,
runsAnswer: unknown,
): void {
mockedExecute.mockImplementation((call) =>
Effect.sync(() =>
output(
call.kind === "rest"
? call.path.endsWith("/approve")
? ""
: encodeJson(runsAnswer)
: call.operationName === "PullRequestHeads"
? encodeJson(headsAnswer)
: encodeJson(detail()),
),
),
);
}
/** Node IDs stay cached after the first test. */
const NODE_ID_QUERY = "PullRequestNodeId";
const nodeIdAnswer = (id: string) => ({ data: { repository: { pullRequest: { id } } } });
afterEach(() => {
mockedExecute.mockReset();
mockedStackMemberships.mockReset();
mockedCredential.mockReset();
mockedAppToken.mockReset();
mockedCredential.mockImplementation(defaultCredential);
});
it.effect(
"keeps a verified credential through an auth switch and separates token fingerprints",
() =>
Effect.gen(function* () {
let activeToken = "broad-credential";
const requests: Array<{ readonly url: string; readonly authorization: string | undefined }> =
[];
const credentials = Layer.succeed(
GitHubCredentials.GitHubCredentials,
GitHubCredentials.GitHubCredentials.of({
get: (host) =>
Effect.sync(() => ({
host,
token: Redacted.make(activeToken),
source: "gh" as const,
fingerprint: `${host}:${activeToken.length}${activeToken.at(-1)}`,
})),
saved: () => Effect.succeedNone,
fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
invalidate: () => Effect.void,
}),
);
const http = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Effect.sync(() => {
requests.push({ url: request.url, authorization: request.headers["authorization"] });
const body = request.url.endsWith("/user")
? { id: 123, login: "same-account" }
: {
data: {
repository: { pullRequest: { id: "PR_1" } },
addComment: { clientMutationId: null },
},
};
return HttpClientResponse.fromWeb(
request,
new Response(encodeJson(body), { headers: { "content-type": "application/json" } }),
);
}),
),
);
const cli = yield* GitHubPullRequestApi.make.pipe(
Effect.provide(
GitHubAppAccess.layer.pipe(
Layer.provideMerge(GitHubRest.layer),
Layer.provideMerge(Layer.mergeAll(credentials, http, appSignedOut)),
Layer.provideMerge(GitHubQuota.layer),
Layer.provideMerge(SourceControlRateLimit.layer),
Layer.merge(TestSourceControlHost.layer()),
Layer.provideMerge(NodeServices.layer),
),
),
);
const input = { cwd: "/repo", host: "github.com" };
const first = yield* cli.withVerifiedCredential(input, (identity) =>
Effect.gen(function* () {
activeToken = "restricted-credential";
expect(yield* cli.getViewerLogin(input)).toBe("same-account");
yield* cli.commentOnPullRequest({
...input,
repository: "owner/repo",
number: 1,
body: "comment",
});
return identity;
}),
);
const second = yield* cli.withVerifiedCredential(input, Effect.succeed);
expect(first.accountId).toBe(second.accountId);
expect(first.credentialFingerprint).not.toBe(second.credentialFingerprint);
expect(encodeJson([first, second])).not.toContain("broad-credential");
expect(encodeJson([first, second])).not.toContain("restricted-credential");
expect(
requests
.filter((request) => request.url.endsWith("/graphql"))
.map((request) => request.authorization),
).toEqual(["Bearer broad-credential", "Bearer broad-credential"]);
expect(
requests
.filter((request) => request.url.endsWith("/user"))
.map((request) => request.authorization),
).toEqual(["Bearer broad-credential", "Bearer restricted-credential"]);
expect(yield* cli.getRoutingIdentity(input)).toEqual({
accountId: "123",
viewer: "same-account",
});
}),
);
layer("GitHubPullRequestApi.layer", (it) => {
it.effect("keeps recent references when the typed number does not exist", () =>
Effect.gen(function* () {
const search = {
pageInfo: { hasNextPage: false },
nodes: [{ __typename: "Issue", number: 7, title: "Seven", issueState: "OPEN" }],
};
mockedExecute.mockImplementation((call) =>
Effect.succeed(
output(
encodeJson(
call.kind === "graphql" && call.variables?.["exact"] === true
? {
data: { search, repository: { issueOrPullRequest: null } },
errors: [
{
type: "NOT_FOUND",
path: ["repository", "issueOrPullRequest"],
message: "Could not resolve to an issue or pull request.",
},
],
}
: { data: { search } },
),
),
),
);
const api = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const result = yield* api.searchRepositoryReferences({
cwd: "/w",
repository: "acme/web",
host: "github.com",
query: "99",
});
expect(result.items.map((item) => item.reference)).toEqual(["#7"]);
}),
);
it.effect("turns maintainer edits off without rewriting the pull request's text", () =>
Effect.gen(function* () {
mockedExecute.mockImplementation((call) =>
Effect.succeed(
output(
encodeJson(
call.kind === "graphql" && matches(call, NODE_ID_QUERY) ? nodeIdAnswer("PR_7") : {},
),
),
),
);
const api = yield* GitHubPullRequestApi.GitHubPullRequestApi;
yield* api.updatePullRequest({ ...pullRequestInput, maintainerCanModify: false });
expect(variablesOf("mutation UpdatePullRequest")).toEqual([
{ pullRequestId: "PR_7", maintainerCanModify: false },
]);
}),
);
it.effect.each(["mixed", "merges", "unavailable"] as const)(
"reads stats only for displayed non-merge commits (%s)",
(kind) =>
Effect.gen(function* () {
const oids = kind === "merges" ? ["merge"] : ["regular", "merge"];
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
encodeJson({
data: {
repository: {
pullRequest: {
author: null,
comments: { nodes: [], pageInfo: lastPage },
reviews: { nodes: [], pageInfo: lastPage },
commits: {
nodes: oids.map((oid) => ({
commit: {
id: "node-" + oid,
oid,
messageHeadline: oid,
committedDate: "2026-07-05T00:00:00Z",
parents: { totalCount: oid === "merge" ? 2 : 1 },
authors: { nodes: [] },
},
})),
},
},
},
},
}),
),
),
);
if (kind === "unavailable") {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}", false, false, {}, 503)));
} else if (kind !== "merges") {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
encodeJson({
data: {
nodes: [{ __typename: "Commit", oid: "regular", additions: 18, deletions: 7 }],
},
}),
),
),
);
}
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const activity = yield* cli.getPullRequestActivity(pullRequestInput);
expect(activity.commits.map((commit) => commit.oid)).toEqual(oids);
expect(activity.commits.find((commit) => commit.oid === "merge")).not.toHaveProperty(
"additions",
);
expect(activity.commits.find((commit) => commit.oid === "merge")).not.toHaveProperty(
"deletions",
);
if (kind === "mixed") {
expect(activity.commits[0]).toMatchObject({ additions: 18, deletions: 7 });
} else if (kind === "unavailable") {
expect(activity.commits[0]).not.toHaveProperty("additions");
}
expect(variablesOf("PullRequestCommitStats")).toEqual(
kind === "merges" ? [] : [{ ids: ["node-regular"] }],
);
expect(mockedExecute).toHaveBeenCalledTimes(kind === "merges" ? 1 : 2);
}),
);
it.effect("reads commit stats alongside later activity pages", () =>
Effect.gen(function* () {
const laterPageStarted = yield* Deferred.make<void>();
const statsStarted = yield* Deferred.make<void>();
const activityPage = (head: boolean) => ({
data: {
repository: {
pullRequest: {
...(head
? {
author: null,
commits: {
nodes: [
{
commit: {
id: "node-regular",
oid: "regular",
messageHeadline: "regular",
committedDate: "2026-07-05T00:00:00Z",
parents: { totalCount: 1 },
authors: { nodes: [] },
},
},
],
},
}
: {}),
comments: {
nodes: [],
pageInfo: head ? { hasNextPage: true, endCursor: "c1" } : lastPage,
},
reviews: { nodes: [], pageInfo: lastPage },
},
},
},
});
mockedExecute.mockImplementation((call) => {
if (matches(call, "PullRequestCommitStats")) {
return Deferred.succeed(statsStarted, undefined).pipe(
Effect.andThen(Deferred.await(laterPageStarted)),
Effect.as(
output(
encodeJson({
data: {
nodes: [{ __typename: "Commit", oid: "regular", additions: 3, deletions: 1 }],
},
}),
),
),
);
}
const head = call.kind === "graphql" && call.variables?.["head"] === true;
return head
? Effect.succeed(output(encodeJson(activityPage(true))))
: Deferred.succeed(laterPageStarted, undefined).pipe(
Effect.andThen(Deferred.await(statsStarted)),
Effect.as(output(encodeJson(activityPage(false)))),
);
});
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const activity = yield* cli.getPullRequestActivity(pullRequestInput);
expect(activity.commits[0]).toMatchObject({ additions: 3, deletions: 1 });
expect(mockedExecute).toHaveBeenCalledTimes(3);
}),
);
it.effect("loads the complete hover card with one GraphQL request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
encodeJson({
data: {
repository: {
pullRequest: {
number: 7,
title: "Fast previews",
url: "https://github.example/acme/web/pull/7",
state: "MERGED",
isDraft: false,
createdAt: "2026-07-01T00:00:00Z",
author: {
__typename: "User",
login: "octocat",
name: "Octo Cat",
avatarUrl: "https://github.example/avatar.png",
},
},
},
},
}),
),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const preview = yield* cli.getPullRequestPreview({
cwd: "/w",
repository: "acme/web",
host: "github.example",
number: 7,
});
expect(preview).toEqual({
number: 7,
title: "Fast previews",
url: "https://github.example/acme/web/pull/7",
state: "merged",
isDraft: false,
createdAt: "2026-07-01T00:00:00Z",
author: {
login: "octocat",
name: "Octo Cat",
avatarUrl: "https://github.example/avatar.png",
},
});
expect(mockedExecute).toHaveBeenCalledTimes(1);
expect(callAt(0)).toMatchObject({ kind: "graphql", host: "github.example" });
}),
);
it.effect("coalesces concurrent identity verification for the same host and credential", () =>
Effect.gen(function* () {
mockedExecute.mockImplementation(() =>
Effect.yieldNow.pipe(Effect.as(output('{"id":123,"login":"viewer"}'))),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const results = yield* Effect.all(
Array.from({ length: 4 }, () =>
cli.getRoutingIdentity({ cwd: "/w", host: "github.identity-flight.test" }),
),
{ concurrency: 4 },
);
expect(results).toEqual(
Array.from({ length: 4 }, () => ({ accountId: "123", viewer: "viewer" })),
);
expect(mockedExecute).toHaveBeenCalledTimes(1);
expect(pathAt(0)).toBe("user");
}),
);
it.effect(
"lets another identity reader continue when the first verification is interrupted",
() =>
Effect.gen(function* () {
const firstStarted = yield* Deferred.make<void>();
let verifications = 0;
mockedExecute.mockImplementation(() =>
Effect.gen(function* () {
if (++verifications === 1) {
yield* Deferred.succeed(firstStarted, undefined);
return yield* Effect.never;
}
return output('{"id":123,"login":"viewer"}');
}),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const input = { cwd: "/w", host: "github.identity-cancel.test" };
const first = yield* cli.getRoutingIdentity(input).pipe(Effect.forkChild);
yield* Deferred.await(firstStarted);
const second = yield* cli.getRoutingIdentity(input).pipe(Effect.forkChild);
yield* Effect.yieldNow;
yield* Fiber.interrupt(first);
expect(yield* Fiber.join(second)).toEqual({ accountId: "123", viewer: "viewer" });
expect(verifications).toBe(2);
}),
);
it.effect("reads linked pull requests on one host together, filed back by position", () =>
Effect.gen(function* () {
const node = (number: number) => ({
number,
title: `Pull request ${number}`,
url: `https://github.com/acme/web/pull/${number}`,
author: {
__typename: "User",
login: "octocat",
name: "Octo Cat",
avatarUrl: "https://avatars.githubusercontent.com/u/1",
},
baseRefName: "main",
headRefName: `feat/${number}`,
state: "OPEN",
isDraft: false,
mergeable: "MERGEABLE",
reviewDecision: null,
latestReviews: {
nodes: [{ state: "APPROVED", author: { __typename: "User", login: "reviewer" } }],
},
additions: 12,
deletions: 3,
changedFiles: 2,
updatedAt: "2026-08-24T12:34:56.000Z",
mergedAt: null,
closedAt: null,
commits: { nodes: [{ commit: { statusCheckRollup: { state: "SUCCESS" } } }] },
});
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
encodeJson({
data: {
_0_repository: { pullRequest: node(7) },
_1_repository: { pullRequest: node(8) },
},
}),
),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const reads = yield* Effect.forEach(
[7, 8],
(number) =>
cli.getPullRequestSummary({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number,
}),
{ concurrency: "unbounded" },
).pipe(Effect.forkChild);
yield* TestClock.adjust("10 millis");
const [seven, eight] = yield* Fiber.join(reads);
assert.deepStrictEqual(
{
number: seven?.number,
state: seven?.state,
headBranch: seven?.headBranch,
author: seven?.author?.login,
changedFiles: seven?.changedFiles,
reviewDecision: seven?.reviewDecision,
checksState: seven?.checksState,
mergeability: seven?.mergeability,
},
{
number: 7,
state: "open",
headBranch: "feat/7",
author: "octocat",
changedFiles: 2,
reviewDecision: "approved",
checksState: "passing",
mergeability: "mergeable",
},
);
assert.strictEqual(eight?.headBranch, "feat/8");
expect(mockedExecute).toHaveBeenCalledOnce();
expect(queryAt(0)).toContain(
"_0_repository:repository(owner:$_0_owner name:$_0_name){pullRequest(number:$_0_number)",
);
expect(varsAt(0)).toMatchObject({
_0_owner: "acme",
_0_name: "web",
_0_number: 7,
_0_stacks: true,
_1_number: 8,
});
}),
);
it.effect(
"fails only the pull request GitHub cannot find, and answers the rest of its batch",
() =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
encodeJson({
data: {
_0_repository: { pullRequest: null },
_1_repository: {
pullRequest: {
number: 8,
title: "Still here",
url: "https://github.com/acme/web/pull/8",
author: null,
baseRefName: "main",
headRefName: "feat/eight",
state: "OPEN",
isDraft: false,
mergeable: "MERGEABLE",
reviewDecision: null,
latestReviews: { nodes: [] },
additions: 1,
deletions: 1,
changedFiles: 1,
updatedAt: "2026-08-24T12:34:56.000Z",
mergedAt: null,
closedAt: null,
commits: { nodes: [] },
stack: null,
stackEntry: null,
},
},
},
errors: [
{
type: "NOT_FOUND",
path: ["_0_repository", "pullRequest"],
message: "Could not resolve to a PullRequest with the number of 7.",
},
],
}),
),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const reads = yield* Effect.forEach(
[7, 8],
(number) =>
cli
.getPullRequestSummary({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number,
})
.pipe(Effect.result),
{ concurrency: "unbounded" },
).pipe(Effect.forkChild);
yield* TestClock.adjust("10 millis");
const [seven, eight] = yield* Fiber.join(reads);
expect(Result.isFailure(seven!) ? seven.failure._tag : null).toBe("GitHubApiNotFoundError");
expect(Result.isSuccess(eight!) ? eight.success.headBranch : null).toBe("feat/eight");
expect(mockedExecute).toHaveBeenCalledOnce();
expect(callAt(0)).toMatchObject({ kind: "graphql", partial: true });
}),
);
it.effect("reads the stack a pull request is in through the stacks preview, on its host", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
encodeJson([
{
id: 42,
number: 3,
url: "https://api.github.com/repos/acme/web/stacks/3",
base: { ref: "main" },
pull_requests: [
{
number: 6,
head: { ref: "feat/one" },
state: "closed",
merged_at: "2026-09-02",
},
{ number: 7, head: { ref: "feat/two" }, state: "open", merged_at: null },
],
},
]),
),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const stack = yield* cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "ghe.example.com",
number: 7,
});
assert.deepStrictEqual(stack, {
id: "42",
number: 3,
url: "https://api.github.com/repos/acme/web/stacks/3",
base: "main",
layers: [
{ number: 6, headBranch: "feat/one", state: "merged" },
{ number: 7, headBranch: "feat/two", state: "open" },
],
});
expect(callAt(0)).toMatchObject({
kind: "rest",
host: "ghe.example.com",
path: "repos/acme/web/stacks?pull_request=7",
});
}),
);
it.effect("revalidates a polled stack, per credential, so an unchanged one costs no quota", () =>
Effect.gen(function* () {
const listing = encodeJson([
{
number: 4,
url: "https://api.github.com/repos/acme/poll/stacks/4",
base: { ref: "main" },
pull_requests: [
{ number: 9, head: { ref: "feat/nine" }, state: "open", merged_at: null },
],
},
]);
const read = Effect.flatMap(GitHubPullRequestApi.GitHubPullRequestApi, (cli) =>
cli.getPullRequestStack({
cwd: "/w",
repository: "acme/poll",
host: "github.com",
number: 9,
}),
);
mockedExecute.mockReturnValueOnce(
Effect.succeed(output(listing, false, false, { etag: 'W/"v1"' })),
);
const first = yield* read;
mockedExecute.mockReturnValueOnce(Effect.succeed(output("", false, false, {}, 304)));
const second = yield* read;
mockedCredential.mockImplementationOnce(() =>
Effect.succeed({ token: Redacted.make("other"), fingerprint: "github.com:other" }),
);
mockedExecute.mockReturnValueOnce(Effect.succeed(output(listing)));
yield* read;
assert.deepStrictEqual(second, first);
expect(callAt(0)).not.toHaveProperty("ifNoneMatch");
expect(callAt(1)).toMatchObject({ ifNoneMatch: 'W/"v1"' });
// Another account never revalidates the first account's answer.
expect(callAt(2)).not.toHaveProperty("ifNoneMatch");
}),
);
it.effect("reads a host that refuses the stacks preview as not stacked", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.fail(
new GitHubRequestPolicy.GitHubApiNotFoundError({
host: "github.com",
operation: "getPullRequestStack",
}),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const stack = yield* cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
assert.isNull(stack);
}),
);
it.effect("does not read a refused credential as an unstacked pull request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.fail(
new GitHubRequestPolicy.GitHubApiAuthenticationError({
host: "github.com",
operation: "getPullRequestStack",
}),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const error = yield* Effect.flip(
cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
}),
);
assert.strictEqual(error._tag, "GitHubApiAuthenticationError");
}),
);
it.effect("preserves transient stack failures instead of reporting no stack", () =>
Effect.gen(function* () {
const failure = new GitHubRequestPolicy.GitHubApiResponseError({
host: "github.com",
operation: "getPullRequestStack",
status: 503,
});
mockedExecute.mockReturnValueOnce(Effect.fail(failure));
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const error = yield* Effect.flip(
cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
}),
);
assert.strictEqual(error, failure);
}),
);
it.effect("reports truncation from the extra row, counted before decoding", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(11, 1))));
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const batch = yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
});
assert.strictEqual(batch.items.length, 10);
assert.isTrue(batch.truncated);
}),
);
it.effect("reports truncation when GitHub repeats a cursor before the page is full", () =>
Effect.gen(function* () {
const repeating = output(
encodeJson({
data: {
search: {
pageInfo: { hasNextPage: true, endCursor: "same" },
nodes: rows(100, 1),
},
},
}),
);
mockedExecute.mockReturnValue(Effect.succeed(repeating));
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const batch = yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 250,
});
assert.strictEqual(mockedExecute.mock.calls.length, 2);
assert.isTrue(batch.truncated);
}),
);
/**
* Lists a repository GitHub will not return, answering credential lookups in turn (the last
* answer repeats; `undefined` is no credential), and returns the error with the tokens sent.
*/
const listUnreadableRepository = (
...lookups: ReadonlyArray<
| { readonly token: string; readonly source: GitHubCredentials.GitHubCredentialSource }
| undefined
>
) => {
mockedExecute.mockClear();
let lookup = 0;
mockedCredential.mockImplementation((host) =>
Effect.suspend(() => {
const held = lookups[Math.min(lookup++, lookups.length - 1)];
return held === undefined
? Effect.fail(
new GitHubRequestPolicy.GitHubApiAuthenticationError({
host,
operation: "credential",
}),
)
: Effect.succeed({
token: Redacted.make(held.token),
fingerprint: `${host}:${held.token}`,
source: held.source,
});
}),
);
route(
["PullRequestSearch", { data: { search: { pageInfo: lastPage, nodes: [] } } }],
[
"PullRequestList",
{
data: { repository: null },
errors: [
{
type: "NOT_FOUND",
path: ["repository"],
message: "Could not resolve to a Repository with the name 'acme/private'.",
},
],
},
],
);
return GitHubPullRequestProvider.make.pipe(
Effect.flatMap((provider) =>
Effect.flip(
provider.listChangeRequests({
cwd: "/w",
repository: "acme/private",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
}),
),
),
Effect.map((error) => ({
error,
sentWith: mockedExecute.mock.calls.map(([call]) =>
call.kind === "graphql" ? call.authorization : undefined,
),
})),
);
};
it.effect("names the credential GitHub would not return a repository to", () =>
Effect.gen(function* () {
// The saved token is replaced mid-read; every request still goes out with the one named.
const saved = yield* listUnreadableRepository(
{ token: "first", source: "settings" },
{ token: "replaced", source: "settings" },
);
expect(saved.error.accessHint).toContain("saved GitHub token");
assert.isAbove(saved.sentWith.length, 1);
for (const authorization of saved.sentWith) expect(authorization).toContain("first");
// The policy hands what the app cannot see to the gh login, which GitHub refuses too.
mockedAppToken.mockReturnValue(Effect.succeedSome("app"));
const app = { token: "app", source: "app" } as const;
const gh = { token: "personal", source: "gh" } as const;
const retried = yield* listUnreadableRepository(app, gh);
expect(retried.error.accessHint).toContain("gh login");
expect(retried.sentWith).toEqual(["Bearer app", "Bearer app", "Bearer personal"]);
// With no gh login when the app is refused, the app made the last request; a login that
// turns up afterwards is not named.
const appOnly = yield* listUnreadableRepository(app, undefined, gh);
assert.isUndefined(appOnly.error.accessHint);
expect(appOnly.sentWith).toEqual(["Bearer app", "Bearer app"]);
}),
);
it.effect("carries every repository and every qualifier into one search", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(searchPage([])));
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
yield* cli.searchPullRequests({
cwd: "/w",
host: "github.com",
repositories: ["acme/web", "pingdotgg/t3code"],
state: "closed",
involvement: "reviewing",
viewer: "bilal",
limit: 10,
query: "pull requests page",
cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 10 },
});
assert.strictEqual(mockedExecute.mock.calls.length, 1);
assert.strictEqual(
searchQueryOfCall(0),
'is:pr is:closed is:unmerged review-requested:bilal "pull requests page" ' +
"updated:<=2026-07-02T00:00:00Z sort:updated-desc repo:acme/web repo:pingdotgg/t3code",
);
}),
);
it.effect("keeps a searched-for qualifier inside the phrase", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(searchPage([])));
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
yield* cli.searchPullRequests({
cwd: "/w",
host: "github.com",
repositories: ["acme/web"],
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
query: 'x" is:merged repo:evil/repo',
});
assert.strictEqual(
searchQueryOfCall(0),
'is:pr is:open "x\\" is:merged repo:evil/repo" sort:updated-desc repo:acme/web',
);
}),
);
it.effect("refuses to search for a repository GitHub cannot address", () =>
Effect.gen(function* () {
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const failure = yield* Effect.flip(
cli.searchPullRequests({
cwd: "/w",
host: "github.com",
repositories: ["acme/web", "acme/web is:merged"],
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
}),
);
assert.strictEqual(failure._tag, "GitHubRepositorySelectorError");
assert.strictEqual(mockedExecute.mock.calls.length, 0);
}),
);
it.effect("files each searched row under the repository it came from", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(
Effect.succeed(
searchPage([
searchItem(7, "acme/web", "2026-07-03T00:00:00Z"),
searchItem(9, "pingdotgg/t3code", "2026-07-02T00:00:00Z"),
{},
]),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const batch = yield* cli.searchPullRequests({
cwd: "/w",
host: "github.com",
repositories: ["acme/web", "pingdotgg/t3code"],
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
});
assert.deepStrictEqual(
batch.items.map((item) => [item.repository, item.number, item.author?.avatarUrl]),
[
["acme/web", 7, "https://avatars/octocat"],
["pingdotgg/t3code", 9, "https://avatars/octocat"],
],
);
assert.deepStrictEqual(
batch.items.map((item) => [item.additions, item.deletions]),
[
[0, 0],
[0, 0],
],
);
assert.isFalse(batch.truncated);
}),
);
it.effect("reports truncation from the extra row, and from a page GitHub says has more", () =>
Effect.gen(function* () {
mockedExecute
.mockReturnValueOnce(
Effect.succeed(
searchPage([
searchItem(1, "acme/web", "2026-07-03T00:00:00Z"),
searchItem(2, "acme/web", "2026-07-02T00:00:00Z"),
searchItem(3, "acme/web", "2026-07-01T00:00:00Z"),
]),
),
)
.mockReturnValueOnce(
Effect.succeed(searchPage([searchItem(1, "acme/web", "2026-07-03T00:00:00Z")], true)),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const read = () =>
cli.searchPullRequests({
cwd: "/w",
host: "github.com",
repositories: ["acme/web"],
state: "open",
involvement: "all",
viewer: "bilal",
limit: 2,
});
const overflowing = yield* read();
const capped = yield* read();
assert.strictEqual(overflowing.items.length, 2);
assert.isTrue(overflowing.truncated);
assert.isTrue(capped.truncated);
}),
);
it.effect("enriches only the visible fallback rows after filtering and widening", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(emptySearch()));
mockedExecute.mockReturnValueOnce(
Effect.succeed(output(listedPullRequests(3, 1, () => ({ isDraft: true })))),
);
mockedExecute.mockReturnValueOnce(
Effect.succeed(output(listedPullRequests(6, 1, (number) => ({ isDraft: number < 4 })))),
);
mockedStackMemberships.mockReturnValueOnce(
Effect.succeed(
output(
encodeJson({
data: {
_0_repository: {
pullRequest: {
stack: { number: 3, size: 2, baseRefName: "main" },
stackEntry: { position: 1 },
},
},
_1_repository: { pullRequest: { stack: null, stackEntry: null } },
},
}),
),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const batch = yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 2,
filters: { draft: "hide" },
});
expect(batch.items.map((item) => item.number)).toEqual([4, 5]);
expect(batch.items[0]?.stack).toEqual({ number: 3, size: 2, base: "main", position: 1 });
expect(batch.items[1]?.stack).toBeUndefined();
expect(batch.truncated).toBe(true);
expect(batch.continues).toBe(false);
expect(mockedStackMemberships).toHaveBeenCalledTimes(1);
const membership = mockedStackMemberships.mock.calls[0]?.[0];
const numbers = Object.entries(
membership?.kind === "graphql" ? (membership.variables ?? {}) : {},
)
.filter(([name]) => name.endsWith("_number"))
.map(([, number]) => number);
expect(numbers).toEqual([4, 5]);
}),
);
it.effect("batches membership reads and keeps successful rows when one chunk fails", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(27, 1))));
mockedStackMemberships.mockImplementation((input) =>
input.kind === "graphql" && Object.values(input.variables ?? {}).includes(26)
? Effect.fail(
new GitHubRequestPolicy.GitHubApiResponseError({
host: "github.com",
operation: "listPullRequestStackMemberships",
status: 502,
}),
)
: Effect.succeed(
output(
encodeJson({
data: Object.fromEntries(
Object.keys(input.kind === "graphql" ? (input.variables ?? {}) : {})
.filter((name) => name.endsWith("_number"))
.map((name, index) => [
name.replace(/number$/, "repository"),
{
pullRequest:
index === 0
? {
stack: { number: 3, size: 2, baseRefName: "main" },
stackEntry: { position: 1 },
}
: { stack: null, stackEntry: null },
},
]),
),
}),
),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const batch = yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 26,
});
expect(batch.items.map((item) => item.number)).toEqual(
Array.from({ length: 26 }, (_, i) => i + 1),
);
expect(batch.items[0]?.stack).toEqual({ number: 3, size: 2, base: "main", position: 1 });
expect(batch.items[25]?.stack).toBeUndefined();
expect(batch.truncated).toBe(true);
expect(batch.continues).toBe(true);
expect(mockedStackMemberships).toHaveBeenCalledTimes(2);
}),
);
it.effect("reads the line counts in chunks, and files them back by position", () =>
Effect.gen(function* () {
const changeRequests = Array.from({ length: 26 }, (_, index) => ({
repository: "acme/web",
number: index + 1,
}));
mockedExecute.mockImplementation((call) =>
Effect.succeed(
output(
encodeJson({
data: Object.fromEntries(
Object.keys(call.kind === "graphql" ? (call.variables ?? {}) : {})
.filter((name) => name.endsWith("_number"))
.map((name, index) => [
name.replace(/number$/, "repository"),
{ pullRequest: index === 0 ? { additions: 4, deletions: 1 } : null },
]),
),
}),
),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const stats = yield* cli.listPullRequestStats({
cwd: "/w",
host: "github.com",
changeRequests,
});
assert.strictEqual(mockedExecute.mock.calls.length, 2);
assert.deepStrictEqual(stats, [
{ repository: "acme/web", number: 1, additions: 4, deletions: 1 },
{ repository: "acme/web", number: 26, additions: 4, deletions: 1 },
]);
expect(queryAt(0)).toContain("_0_repository:repository(owner:$_0_owner name:$_0_name)");
expect(varsAt(0)).toMatchObject({ _0_owner: "acme", _0_name: "web", _24_number: 25 });
}),
);
it.effect("carries the further narrowings into the search as qualifiers", () =>
Effect.gen(function* () {
mockedExecute.mockImplementation((call) =>
Effect.succeed(
call.kind === "graphql" && call.operationName === "PullRequestList"
? emptyList()
: emptySearch(),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: {
draft: "hide",
review: "changes-requested",
checks: "failing",
labels: [["needs design"], ['quo"te']],
excludedLabels: ["wip"],
author: "octocat",
},
});
expect(searchOfCall(0)).toBe(
'is:pr is:open label:"needs design" label:"quote" -label:"wip" author:"octocat" ' +
"draft:false review:changes_requested status:failure sort:updated-desc repo:acme/web",
);
}),
);
it.effect('resolves an author filter of "me" to the viewer, not the literal word', () =>
Effect.gen(function* () {
mockedExecute.mockImplementation((call) =>
Effect.succeed(
call.kind === "graphql" && call.operationName === "PullRequestList"
? emptyList()
: emptySearch(),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { author: "me" },
});
expect(searchOfCall(0)).toBe('is:pr is:open author:"bilal" sort:updated-desc repo:acme/web');
}),
);
it.effect("sends one label qualifier per group, its names joined the way GitHub ors them", () =>
Effect.gen(function* () {
mockedExecute.mockImplementation((call) =>
Effect.succeed(
call.kind === "graphql" && call.operationName === "PullRequestList"
? emptyList()
: emptySearch(),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { labels: [["size:S", "size:XS"], ["bug"]] },
});
expect(searchOfCall(0)).toBe(
'is:pr is:open label:"size:S","size:XS" label:"bug" sort:updated-desc repo:acme/web',
);
}),
);
it.effect(
"falls back for a repository the index does not cover under a checks filter, keeping only the matching rows",
() =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(emptySearch()));
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
listedPullRequests(2, 1, (number) => ({
checks: number === 1 ? "SUCCESS" : "FAILURE",
})),
),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const batch = yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { checks: "passing" },
});
expect(searchOfCall(1)).toBeUndefined();
assert.deepStrictEqual(
batch.items.map((item) => item.number),
[1],
);
}),
);
it.effect("fails a checks filter for a row whose checks are still pending", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(emptySearch()));
mockedExecute.mockReturnValueOnce(
Effect.succeed(output(listedPullRequests(1, 1, () => ({ checks: "PENDING" })))),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const batch = yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { checks: "passing" },
});
assert.deepStrictEqual(batch.items, []);
}),
);
it.effect("escapes a backslash before the quote it would otherwise let out", () =>
Effect.gen(function* () {
mockedExecute.mockImplementation((call) =>
Effect.succeed(
call.kind === "graphql" && call.operationName === "PullRequestList"
? emptyList()
: emptySearch(),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
query: String.raw`a\" is:merged`,
});
expect(searchOfCall(0)).toBe(
String.raw`is:pr is:open "a\\\" is:merged" sort:updated-desc repo:acme/web`,
);
}),
);
it.effect("carries on from the instant the last slice ended on", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output(pullRequests(3, 1))));
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const batch = yield* cli.listPullRequests({