@devries-cameron20 / t3code-1 / commits / 20501a0221
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(issues): add issue tracking core with GitHub issues (#19259)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

Julius Marminge committed Nov 16, 2026 at 22:00 UTC 20501a0221312c225e505dd8f2aa88f0455cbda5
28 files changed +4799 -9
apps/server/src/auth/RpcAuthorization.test.ts
+53
@@ -8,6 +8,8 @@ import {
8 DEFAULT_SERVER_SETTINGS,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 + ProjectId,
12 + IssueTrackerKind,
13 SecretProviderId,
14 ThreadId,
15 AuthOrchestrationOperateScope,
@@ -144,6 +146,57 @@ describe("RPC scope middleware", () => {
146 );
147 });
148
149 +it.effect("allows issue reads but requires a source-control grant before commenting", () =>
150 + Effect.gen(function* () {
151 + const tested = [WS_METHODS.issuesList, WS_METHODS.issuesComment] as const;
152 + const group = WsRpcGroup.omit(
153 + ...[...WsRpcGroup.requests.keys()].filter(
154 + (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
155 + !(tested as ReadonlyArray<string>).includes(tag),
156 + ),
157 + );
158 + const comments: string[] = [];
159 + const handlers = Layer.mergeAll(
160 + group.toLayerHandler(WS_METHODS.issuesList, () =>
161 + Effect.succeed({ entries: [], trackers: [], errors: [], viewers: {}, nextCursors: {} }),
162 + ),
163 + group.toLayerHandler(WS_METHODS.issuesComment, ({ body }) =>
164 + Effect.sync(() => {
165 + comments.push(body);
166 + }),
167 + ),
168 + );
169 + const reader = yield* RpcTest.makeClient(group).pipe(
170 + Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))),
171 + );
172 + const comment = {
173 + projectId: ProjectId.make("web"),
174 + tracker: IssueTrackerKind.make("github"),
175 + scope: "acme/web",
176 + key: "42",
177 + body: "Repro attached.",
178 + };
179 +
180 + expect((yield* reader[WS_METHODS.issuesList]({ state: "open" })).entries).toEqual([]);
181 + expect(yield* reader[WS_METHODS.issuesComment](comment).pipe(Effect.flip)).toMatchObject({
182 + _tag: "EnvironmentAuthorizationError",
183 + requiredPermission: AuthSourceControlWriteScope,
184 + });
185 + expect(comments).toEqual([]);
186 +
187 + const writer = yield* RpcTest.makeClient(group).pipe(
188 + Effect.provide(
189 + Layer.merge(
190 + handlers,
191 + RpcAuthorization.layer([AuthOrchestrationReadScope, AuthSourceControlWriteScope]),
192 + ),
193 + ),
194 + );
195 + yield* writer[WS_METHODS.issuesComment](comment);
196 + expect(comments).toEqual(["Repro attached."]);
197 + }).pipe(Effect.scoped),
198 +);
199 +
200 it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)(
201 "enforces read permission on stream %s",
202 (method) =>
apps/server/src/auth/RpcAuthorization.ts
+5
@@ -132,6 +132,11 @@ export const RPC_REQUIRED_SCOPES = {
132 [WS_METHODS.pullRequestsStack]: AuthOrchestrationReadScope,
133 [WS_METHODS.pullRequestsLinkedThreads]: AuthOrchestrationReadScope,
134 [WS_METHODS.pullRequestsDetail]: AuthOrchestrationReadScope,
135 + [WS_METHODS.issuesList]: AuthOrchestrationReadScope,
136 + [WS_METHODS.issuesDetail]: AuthOrchestrationReadScope,
137 + [WS_METHODS.issuesComments]: AuthOrchestrationReadScope,
138 + [WS_METHODS.issuesTemplates]: AuthOrchestrationReadScope,
139 + [WS_METHODS.issuesCandidates]: AuthOrchestrationReadScope,
140 [WS_METHODS.pullRequestsPreview]: AuthOrchestrationReadScope,
141 [WS_METHODS.pullRequestsChecks]: AuthOrchestrationReadScope,
142 [WS_METHODS.pullRequestsActivity]: AuthOrchestrationReadScope,
apps/server/src/issue/IssueService.test.ts new
+346
@@ -0,0 +1,346 @@
1 +import { describe, expect, it } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Option from "effect/Option";
5 +import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
6 +import {
7 + IssueTrackerKind,
8 + SourceControlProviderKind,
9 + type OrchestrationProjectShell,
10 + type ProjectId,
11 +} from "@t3tools/contracts";
12 +import {
13 + IssueTrackerError,
14 + type IssueTrackerApi,
15 + type TrackerIssueDetail,
16 +} from "@t3tools/source-control-core/server/IssueTracker";
17 +
18 +import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
19 +
20 +import * as ProjectService from "../project/ProjectService.ts";
21 +import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
22 +import * as IssueService from "./IssueService.ts";
23 +import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
24 +
25 +const GITHUB = IssueTrackerKind.make("github");
26 +
27 +function project(input: {
28 + readonly id: string;
29 + readonly repository?: string;
30 + readonly provider?: string;
31 + readonly host?: string;
32 +}): OrchestrationProjectShell {
33 + const host = input.host ?? "github.com";
34 + return {
35 + id: input.id as ProjectId,
36 + title: input.id,
37 + workspaceRoot: `/w/${input.id}`,
38 + ...(input.repository
39 + ? {
40 + repositoryIdentity: {
41 + canonicalKey: normalizeGitRemoteUrl(`https://${host}/${input.repository}.git`),
42 + locator: {
43 + source: "git-remote" as const,
44 + remoteName: "origin",
45 + remoteUrl: `https://${host}/${input.repository}.git`,
46 + },
47 + provider: SourceControlProviderKind.make(input.provider ?? "github"),
48 + displayName: input.repository,
49 + },
50 + }
51 + : {}),
52 + defaultModelSelection: null,
53 + scripts: [],
54 + createdAt: "2026-07-01T00:00:00Z",
55 + updatedAt: "2026-07-01T00:00:00Z",
56 + };
57 +}
58 +
59 +function issue(key: string, updatedAt = "2026-07-02T00:00:00Z"): TrackerIssueDetail {
60 + return {
61 + key,
62 + displayKey: `#${key}`,
63 + title: `Issue ${key}`,
64 + url: `https://github.com/acme/web/issues/${key}`,
65 + author: null,
66 + state: { category: "open", name: "open" },
67 + createdAt: "2026-07-01T00:00:00Z",
68 + updatedAt,
69 + closedAt: null,
70 + assignees: [],
71 + labels: [],
72 + commentCount: 0,
73 + body: "",
74 + viewer: "julius",
75 + viewerPermissions: { setState: true, comment: true, edit: true, labels: true, assignees: true },
76 + comments: [],
77 + commentsCursor: null,
78 + events: [],
79 + linkedPullRequests: [],
80 + };
81 +}
82 +
83 +function fakeTracker(overrides: Partial<IssueTrackerApi> = {}): IssueTrackerApi {
84 + return {
85 + kind: GITHUB,
86 + capabilities: {
87 + create: true,
88 + edit: true,
89 + comment: true,
90 + labels: true,
91 + assignees: true,
92 + reactions: false,
93 + templates: false,
94 + linkedPullRequests: true,
95 + events: true,
96 + search: true,
97 + states: [
98 + { category: "open", name: "open" },
99 + { category: "closed", name: "closed" },
100 + ],
101 + closeReasons: ["completed"],
102 + },
103 + getViewer: () => Effect.succeed("julius"),
104 + listIssues: () => Effect.succeed({ items: [], nextCursor: null }),
105 + getIssue: (input) => Effect.succeed(issue(input.key)),
106 + getComments: () => Effect.succeed({ comments: [], nextCursor: null }),
107 + comment: () => Effect.void,
108 + update: () => Effect.void,
109 + setState: () => Effect.void,
110 + ...overrides,
111 + };
112 +}
113 +
114 +function makeService(input: {
115 + readonly projects: ReadonlyArray<OrchestrationProjectShell>;
116 + readonly trackers: ReadonlyArray<IssueTrackerApi>;
117 +}) {
118 + return IssueService.IssueService.pipe(
119 + Effect.provide(
120 + IssueService.layer.pipe(
121 + Layer.provide(
122 + Layer.mergeAll(
123 + Layer.succeed(
124 + IssueTrackerRegistry.IssueTrackerRegistry,
125 + IssueTrackerRegistry.fromTrackers(input.trackers),
126 + ),
127 + Layer.mock(ProjectService.ProjectService)({
128 + listShells: () => Effect.succeed(input.projects),
129 + getShell: (projectId) =>
130 + Effect.succeed(
131 + Option.fromNullishOr(input.projects.find((p) => p.id === projectId)),
132 + ),
133 + }),
134 + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
135 + resolve: () => Effect.succeed(null),
136 + }),
137 + ),
138 + ),
139 + ),
140 + ),
141 + );
142 +}
143 +
144 +describe("IssueService", () => {
145 + it.effect("reads another repository on the same host but refuses to write to it", () =>
146 + Effect.gen(function* () {
147 + const writes: string[] = [];
148 + const service = yield* makeService({
149 + projects: [project({ id: "web", repository: "acme/web" })],
150 + trackers: [
151 + fakeTracker({
152 + comment: (input) =>
153 + Effect.sync(() => {
154 + writes.push(`${input.scope}#${input.key}`);
155 + }),
156 + }),
157 + ],
158 + });
159 + const own = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
160 + const external = { ...own, scope: "other/backend", key: "7" };
161 +
162 + expect((yield* service.detail(own)).writable).toBe(true);
163 + // The external issue is served by the project's checkout and credentials, read-only.
164 + const detail = yield* service.detail(external);
165 + expect(detail).toMatchObject({ writable: false, scope: "other/backend", key: "7" });
166 +
167 + yield* service.comment({ ...own, body: "ok" });
168 + const refused = yield* service.comment({ ...external, body: "no" }).pipe(Effect.result);
169 + expect(refused).toMatchObject({
170 + _tag: "Failure",
171 + failure: { _tag: "IssueOperationError", reason: "read-only" },
172 + });
173 + expect(writes).toEqual(["acme/web#1"]);
174 +
175 + // Another host is not reachable through this project's credentials at all.
176 + const elsewhere = yield* Effect.flip(service.detail({ ...own, host: "ghe.example.test" }));
177 + expect(elsewhere).toMatchObject({
178 + _tag: "IssueUnavailableError",
179 + reason: "tracker-unsupported",
180 + });
181 + }),
182 + );
183 +
184 + it.effect("sends writes as interactive requests and reads as background ones", () =>
185 + Effect.gen(function* () {
186 + const interactive: Array<readonly [string, boolean]> = [];
187 + const record = (operation: string) =>
188 + Effect.gen(function* () {
189 + interactive.push([operation, yield* SourceControlRateLimit.Interactive]);
190 + });
191 + const service = yield* makeService({
192 + projects: [project({ id: "web", repository: "acme/web" })],
193 + trackers: [
194 + fakeTracker({
195 + getComments: () =>
196 + record("comments").pipe(Effect.as({ comments: [], nextCursor: null })),
197 + comment: () => record("comment"),
198 + }),
199 + ],
200 + });
201 + const ref = {
202 + projectId: "web" as ProjectId,
203 + tracker: GITHUB,
204 + scope: "acme/web",
205 + key: "42",
206 + };
207 + yield* service.comments({ ...ref, cursor: "next" });
208 + yield* service.comment({ ...ref, body: "Repro attached." });
209 + expect(interactive).toEqual([
210 + ["comments", false],
211 + ["comment", true],
212 + ]);
213 + }),
214 + );
215 +
216 + it.effect("refuses what the tracker did not declare before calling it", () =>
217 + Effect.gen(function* () {
218 + let calls = 0;
219 + const service = yield* makeService({
220 + projects: [project({ id: "web", repository: "acme/web" })],
221 + trackers: [
222 + fakeTracker({
223 + setState: () =>
224 + Effect.sync(() => {
225 + calls += 1;
226 + }),
227 + setReaction: () =>
228 + Effect.sync(() => {
229 + calls += 1;
230 + }),
231 + }),
232 + ],
233 + });
234 + const ref = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
235 +
236 + yield* service.setState({ ...ref, state: "closed", closeReason: "completed" });
237 + const unknownState = yield* Effect.flip(service.setState({ ...ref, state: "In Review" }));
238 + expect(unknownState._tag).toBe("IssueOperationError");
239 + const unknownReason = yield* Effect.flip(
240 + service.setState({ ...ref, state: "closed", closeReason: "not-planned" }),
241 + );
242 + expect(unknownReason._tag).toBe("IssueOperationError");
243 + const reaction = yield* Effect.flip(
244 + service.react({ ...ref, content: "heart", reacted: true }),
245 + );
246 + expect(reaction._tag).toBe("IssueOperationError");
247 + expect(calls).toBe(1);
248 + }),
249 + );
250 +
251 + it.effect("deduplicates and pages repositories despite partial failures", () =>
252 + Effect.gen(function* () {
253 + const listed: string[] = [];
254 + let failContinuation = true;
255 + const service = yield* makeService({
256 + projects: [
257 + project({ id: "web", repository: "Acme/Web" }),
258 + project({ id: "web-worktree", repository: "acme/web" }),
259 + project({ id: "api", repository: "acme/api" }),
260 + project({ id: "docs", repository: "acme/docs" }),
261 + project({
262 + id: "gitlab",
263 + repository: "acme/gl",
264 + provider: "gitlab",
265 + host: "gitlab.com",
266 + }),
267 + project({ id: "plain" }),
268 + ],
269 + trackers: [
270 + fakeTracker({
271 + listIssues: (input) =>
272 + Effect.gen(function* () {
273 + listed.push(input.scope);
274 + if (input.scope === "acme/api")
275 + return yield* new IssueTrackerError({
276 + tracker: GITHUB,
277 + operation: "listIssues",
278 + reason: "failed",
279 + // A tracker may fail without a detail; the wire error still needs one.
280 + detail: " ",
281 + });
282 + if (input.scope === "acme/docs")
283 + return { items: [issue("3", "2026-07-04T00:00:00Z")], nextCursor: null };
284 + if (input.cursor === "next" && failContinuation) {
285 + failContinuation = false;
286 + return yield* new IssueTrackerError({
287 + tracker: GITHUB,
288 + operation: "listIssues",
289 + reason: "failed",
290 + detail: "try again",
291 + });
292 + }
293 + if (input.cursor === "next")
294 + return { items: [issue("4", "2026-07-01T00:00:00Z")], nextCursor: null };
295 + return {
296 + items: [issue("1"), issue("2", "2026-07-05T00:00:00Z")],
297 + nextCursor: "next",
298 + };
299 + }),
300 + }),
301 + ],
302 + });
303 + const result = yield* service.list({ state: "open" });
304 + expect(listed.sort()).toEqual(["Acme/Web", "acme/api", "acme/docs"]);
305 + expect(result.entries.map((entry) => [entry.projectId, entry.key])).toEqual([
306 + ["web", "2"],
307 + ["docs", "3"],
308 + ["web", "1"],
309 + ]);
310 + expect(
311 + result.entries.filter((entry) => entry.projectId === "web").map((entry) => entry.scope),
312 + ).toEqual(["Acme/Web", "Acme/Web"]);
313 + expect(result.nextCursors).toEqual({ "github.com Acme/Web": "next" });
314 + expect(result.errors).toEqual([
315 + { projectId: "api", projectTitle: "api", message: "The issue tracker request failed." },
316 + ]);
317 + expect(result.viewers).toEqual({ "github.com": "julius" });
318 + expect(result.trackers).toEqual([
319 + expect.objectContaining({ host: "github.com", projectCount: 4, configured: true }),
320 + expect.objectContaining({
321 + host: "gitlab.com",
322 + tracker: "gitlab",
323 + projectCount: 1,
324 + configured: false,
325 + capabilities: null,
326 + }),
327 + ]);
328 +
329 + // A continuation only reads the scopes it names.
330 + listed.length = 0;
331 + const failed = yield* service.list({
332 + state: "open",
333 + cursors: result.nextCursors,
334 + });
335 + expect(listed).toEqual(["Acme/Web"]);
336 + expect(failed.nextCursors).toEqual(result.nextCursors);
337 + expect(failed.errors).toEqual([
338 + { projectId: "web", projectTitle: "web", message: "try again" },
339 + ]);
340 + const next = yield* service.list({ state: "open", cursors: failed.nextCursors });
341 + expect(next.entries.map((entry) => [entry.projectId, entry.key])).toEqual([["web", "4"]]);
342 + expect(next.nextCursors).toEqual({});
343 + expect(next.errors).toEqual([]);
344 + }),
345 + );
346 +});
apps/server/src/issue/IssueService.ts new
+569
@@ -0,0 +1,569 @@
1 +// References outside the project's canonical repository may be read on the same host,
2 +// but every write must pass through requireWritable.
3 +import * as Context from "effect/Context";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7 +import {
8 + IssueOperationError,
9 + IssueTrackerKind,
10 + IssueUnavailableError,
11 + type IssueCandidates,
12 + type IssueCommentInput,
13 + type IssueCommentsPage,
14 + type IssueCommentsPageInput,
15 + type IssueCreateInput,
16 + type IssueCreateResult,
17 + type IssueDetail,
18 + type IssueError,
19 + type IssueListEntry,
20 + type IssueListInput,
21 + type IssueListProjectError,
22 + type IssueListResult,
23 + type IssueReactionInput,
24 + type IssueRef,
25 + type IssueScopeRef,
26 + type IssueSetStateInput,
27 + type IssueTemplateList,
28 + type IssueTrackerSummary,
29 + type IssueUpdateInput,
30 + type OrchestrationProjectShell,
31 +} from "@t3tools/contracts";
32 +import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
33 +import {
34 + IssueTrackerError,
35 + type IssueTrackerApi,
36 +} from "@t3tools/source-control-core/server/IssueTracker";
37 +
38 +import * as ProjectService from "../project/ProjectService.ts";
39 +import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
40 +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
41 +import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
42 +
43 +const DEFAULT_LIST_LIMIT = 50;
44 +const SCOPE_CONCURRENCY = 4;
45 +
46 +const interactive =
47 + <I, A>(call: (input: I) => Effect.Effect<A, IssueError>) =>
48 + (input: I) =>
49 + call(input).pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
50 +
51 +const traced =
52 + <I, A>(operation: string, call: (input: I) => Effect.Effect<A, IssueError>) =>
53 + (input: I) =>
54 + call(input).pipe(Effect.withSpan(`IssueService.${operation}`));
55 +
56 +/** A tracker may fail with no detail; the wire errors carry a non-empty one. */
57 +function trackerDetail(error: IssueTrackerError): string {
58 + return error.detail.trim() || "The issue tracker request failed.";
59 +}
60 +
61 +/** One project's resolved tracker: which driver, where it is served from, and its container. */
62 +interface ProjectTrackerBinding {
63 + readonly canonicalKey: string;
64 + readonly tracker: IssueTrackerKind;
65 + readonly host: string;
66 + readonly scope: string;
67 +}
68 +
69 +/** A project the registry has a tracker for, ready to serve reads and writes. */
70 +interface SupportedProject extends ProjectTrackerBinding {
71 + readonly project: OrchestrationProjectShell;
72 + readonly api: IssueTrackerApi;
73 +}
74 +
75 +/**
76 + * The git-host path of resolution: the tracker is the host's own, named like the remote's
77 + * provider kind. Null for a project with no remote or a kind no tracker claims.
78 + */
79 +function resolveGitHostBinding(project: OrchestrationProjectShell): ProjectTrackerBinding | null {
80 + const identity = project.repositoryIdentity;
81 + const scope = sourceControlDefinitions.issueScope(identity);
82 + const kind = identity?.provider;
83 + if (!identity || kind === undefined || kind === "unknown" || scope === null) return null;
84 + return {
85 + canonicalKey: identity.canonicalKey,
86 + tracker: IssueTrackerKind.make(kind),
87 + host: sourceControlDefinitions.changeRequestHost(identity, kind),
88 + scope,
89 + };
90 +}
91 +
92 +function listCursorKey(host: string, scope: string): string {
93 + return `${host} ${scope}`;
94 +}
95 +
96 +function isTrackerUnusable(error: IssueTrackerError): boolean {
97 + return error.reason === "missing-tool" || error.reason === "unauthenticated";
98 +}
99 +
100 +function toIssueError(operation: string): (error: IssueTrackerError) => IssueError {
101 + return (error) =>
102 + isTrackerUnusable(error)
103 + ? new IssueUnavailableError({
104 + reason: error.reason === "missing-tool" ? "tool-missing" : "unauthenticated",
105 + tracker: error.tracker,
106 + cause: error,
107 + })
108 + : new IssueOperationError({
109 + operation,
110 + detail: trackerDetail(error),
111 + ...(error.reason === "not-found" || error.reason === "rate-limited"
112 + ? { reason: error.reason }
113 + : {}),
114 + ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
115 + cause: error,
116 + });
117 +}
118 +
119 +const readOnly = (operation: string) =>
120 + new IssueOperationError({
121 + operation,
122 + reason: "read-only",
123 + detail:
124 + "This issue belongs to a repository outside the selected project and cannot be changed from here.",
125 + });
126 +
127 +const unsupported = (operation: string, what: string) =>
128 + new IssueOperationError({ operation, detail: `This tracker does not support ${what}.` });
129 +
130 +export class IssueService extends Context.Service<
131 + IssueService,
132 + {
133 + readonly list: (input: IssueListInput) => Effect.Effect<IssueListResult, IssueError>;
134 + readonly detail: (input: IssueRef) => Effect.Effect<IssueDetail, IssueError>;
135 + readonly comments: (
136 + input: IssueCommentsPageInput,
137 + ) => Effect.Effect<IssueCommentsPage, IssueError>;
138 + readonly templates: (input: IssueScopeRef) => Effect.Effect<IssueTemplateList, IssueError>;
139 + readonly candidates: (input: IssueScopeRef) => Effect.Effect<IssueCandidates, IssueError>;
140 + readonly create: (input: IssueCreateInput) => Effect.Effect<IssueCreateResult, IssueError>;
141 + readonly comment: (input: IssueCommentInput) => Effect.Effect<void, IssueError>;
142 + readonly update: (input: IssueUpdateInput) => Effect.Effect<void, IssueError>;
143 + readonly setState: (input: IssueSetStateInput) => Effect.Effect<void, IssueError>;
144 + readonly react: (input: IssueReactionInput) => Effect.Effect<void, IssueError>;
145 + }
146 +>()("t3/issue/IssueService") {}
147 +
148 +const make = Effect.gen(function* () {
149 + const registry = yield* IssueTrackerRegistry.IssueTrackerRegistry;
150 + const projects = yield* ProjectService.ProjectService;
151 + const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
152 +
153 + const resolveProjectTracker = (
154 + project: OrchestrationProjectShell,
155 + ): Effect.Effect<ProjectTrackerBinding | null> =>
156 + (project.repositoryIdentity != null
157 + ? Effect.succeed(project.repositoryIdentity)
158 + : repositoryIdentities.resolve(project.workspaceRoot)
159 + ).pipe(
160 + Effect.map((repositoryIdentity) => resolveGitHostBinding({ ...project, repositoryIdentity })),
161 + );
162 +
163 + const listProjects = (filter: {
164 + readonly projectId?: IssueListInput["projectId"];
165 + readonly host?: string | undefined;
166 + }) =>
167 + (filter.projectId === undefined
168 + ? projects.listShells()
169 + : projects.getShell(filter.projectId).pipe(Effect.map(Option.toArray))
170 + ).pipe(
171 + Effect.mapError(
172 + (cause) =>
173 + new IssueOperationError({
174 + operation: "listProjects",
175 + detail: "The project list could not be read.",
176 + cause,
177 + }),
178 + ),
179 + Effect.flatMap((shells) =>
180 + Effect.forEach(
181 + shells,
182 + (project) =>
183 + resolveProjectTracker(project).pipe(
184 + Effect.map((binding) => (binding === null ? [] : [{ project, ...binding }])),
185 + ),
186 + { concurrency: SCOPE_CONCURRENCY },
187 + ),
188 + ),
189 + Effect.map((bound) => {
190 + const host = filter.host?.trim().toLowerCase();
191 + const supported: SupportedProject[] = [];
192 + const unimplemented = new Map<
193 + string,
194 + { tracker: IssueTrackerKind; projectCount: number }
195 + >();
196 + for (const candidate of bound.flat()) {
197 + if (host !== undefined && candidate.host !== host) continue;
198 + const api = registry.get(candidate.tracker);
199 + if (api === null) {
200 + const counted = unimplemented.get(candidate.host);
201 + if (counted === undefined)
202 + unimplemented.set(candidate.host, { tracker: candidate.tracker, projectCount: 1 });
203 + else counted.projectCount += 1;
204 + continue;
205 + }
206 + supported.push({ ...candidate, api });
207 + }
208 + return { supported, unimplemented };
209 + }),
210 + );
211 +
212 + /**
213 + * The project whose checkout and credentials serve a reference, and whether the reference is
214 + * the project's own scope. A reference naming another scope on the same tracker and host is
215 + * served by the project but marked read-only.
216 + */
217 + const requireProject = (
218 + ref: IssueScopeRef,
219 + ): Effect.Effect<SupportedProject & { readonly writable: boolean }, IssueError> =>
220 + listProjects({ projectId: ref.projectId }).pipe(
221 + Effect.flatMap(({ supported }) => {
222 + const own = supported[0];
223 + if (own === undefined || own.tracker !== ref.tracker) {
224 + return Effect.fail(new IssueUnavailableError({ reason: "tracker-unsupported" }));
225 + }
226 + const host = ref.host?.trim().toLowerCase() ?? own.host;
227 + if (host !== own.host) {
228 + return Effect.fail(new IssueUnavailableError({ reason: "tracker-unsupported" }));
229 + }
230 + const scope = ref.scope.trim();
231 + const writable = scope.toLowerCase() === own.scope.toLowerCase();
232 + return Effect.succeed({ ...own, scope, writable });
233 + }),
234 + );
235 +
236 + const requireWritable = (ref: IssueScopeRef, operation: string) =>
237 + requireProject(ref).pipe(
238 + Effect.filterOrFail(
239 + (project) => project.writable,
240 + () => readOnly(operation),
241 + ),
242 + );
243 +
244 + const list: IssueService["Service"]["list"] = Effect.fn("IssueService.list")(function* (input) {
245 + const { supported, unimplemented } = yield* listProjects(input);
246 + const limit = input.limit ?? DEFAULT_LIST_LIMIT;
247 + // Worktrees of one repository are separate projects; read each scope once.
248 + const scopes = new Map<string, SupportedProject>();
249 + for (const project of supported) {
250 + if (!scopes.has(project.canonicalKey)) scopes.set(project.canonicalKey, project);
251 + }
252 + const continuing = input.cursors;
253 + const viewers = new Map<string, string>();
254 + const trackers = new Map<string, IssueTrackerSummary>();
255 + const entries: IssueListEntry[] = [];
256 + const errors: IssueListProjectError[] = [];
257 + const nextCursors: Record<string, string> = {};
258 +
259 + const viewerRequests = new Map<string, Effect.Effect<string, IssueTrackerError>>();
260 + for (const project of scopes.values()) {
261 + if (viewerRequests.has(project.host)) continue;
262 + const request = yield* Effect.cached(
263 + project.api
264 + .getViewer({ cwd: project.project.workspaceRoot, host: project.host })
265 + .pipe(Effect.tap((viewer) => Effect.sync(() => viewers.set(project.host, viewer)))),
266 + );
267 + viewerRequests.set(project.host, request);
268 + }
269 +
270 + // Every project counts, including worktrees of a scope read once below.
271 + for (const project of supported) {
272 + const existing = trackers.get(project.host);
273 + trackers.set(
274 + project.host,
275 + existing === undefined
276 + ? {
277 + tracker: project.tracker,
278 + host: project.host,
279 + projectCount: 1,
280 + capabilities: project.api.capabilities,
281 + configured: true,
282 + detail: null,
283 + }
284 + : { ...existing, projectCount: existing.projectCount + 1 },
285 + );
286 + }
287 + const recordFailure = (project: SupportedProject, failure: IssueTrackerError) => {
288 + const existing = trackers.get(project.host);
289 + if (existing !== undefined && isTrackerUnusable(failure))
290 + trackers.set(project.host, {
291 + ...existing,
292 + configured: false,
293 + detail: trackerDetail(failure),
294 + });
295 + };
296 +
297 + yield* Effect.forEach(
298 + scopes.values(),
299 + (project) =>
300 + Effect.gen(function* () {
301 + const key = listCursorKey(project.host, project.scope);
302 + // A continuation names the scopes it wants; one not named has nothing to add.
303 + if (continuing !== undefined && continuing[key] === undefined) return;
304 + const cursor = continuing?.[key];
305 + const page = yield* viewerRequests.get(project.host)!.pipe(
306 + Effect.flatMap((viewer) =>
307 + project.api.listIssues({
308 + cwd: project.project.workspaceRoot,
309 + host: project.host,
310 + scope: project.scope,
311 + state: input.state,
312 + involvement: input.involvement ?? "all",
313 + viewer,
314 + limit,
315 + query: input.query,
316 + cursor,
317 + }),
318 + ),
319 + Effect.result,
320 + );
321 + if (page._tag === "Failure") {
322 + if (cursor !== undefined) nextCursors[key] = cursor;
323 + recordFailure(project, page.failure);
324 + errors.push({
325 + projectId: project.project.id,
326 + projectTitle: project.project.title,
327 + message: trackerDetail(page.failure),
328 + });
329 + return;
330 + }
331 + for (const item of page.success.items) {
332 + entries.push({
333 + ...item,
334 + tracker: project.tracker,
335 + host: project.host,
336 + scope: project.scope,
337 + projectId: project.project.id,
338 + projectTitle: project.project.title,
339 + });
340 + }
341 + if (page.success.nextCursor !== null) nextCursors[key] = page.success.nextCursor;
342 + }),
343 + { concurrency: SCOPE_CONCURRENCY, discard: true },
344 + );
345 +
346 + for (const [host, { tracker, projectCount }] of unimplemented) {
347 + trackers.set(host, {
348 + tracker,
349 + host,
350 + projectCount,
351 + capabilities: null,
352 + configured: false,
353 + detail: "Issues cannot be browsed for this host yet.",
354 + });
355 + }
356 + entries.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
357 + return {
358 + viewers: Object.fromEntries(viewers),
359 + trackers: [...trackers.values()],
360 + entries,
361 + errors,
362 + nextCursors,
363 + };
364 + });
365 +
366 + const detail: IssueService["Service"]["detail"] = (input) =>
367 + requireProject(input).pipe(
368 + Effect.flatMap((project) =>
369 + project.api
370 + .getIssue({
371 + cwd: project.project.workspaceRoot,
372 + host: project.host,
373 + scope: project.scope,
374 + key: input.key,
375 + })
376 + .pipe(
377 + Effect.mapError(toIssueError("detail")),
378 + Effect.map((issue): IssueDetail => ({
379 + ...issue,
380 + tracker: project.tracker,
381 + host: project.host,
382 + scope: project.scope,
383 + projectId: project.project.id,
384 + projectTitle: project.project.title,
385 + writable: project.writable,
386 + capabilities: project.api.capabilities,
387 + })),
388 + ),
389 + ),
390 + );
391 +
392 + const comments: IssueService["Service"]["comments"] = (input) =>
393 + requireProject(input).pipe(
394 + Effect.flatMap((project) =>
395 + project.api
396 + .getComments({
397 + cwd: project.project.workspaceRoot,
398 + host: project.host,
399 + scope: project.scope,
400 + key: input.key,
401 + cursor: input.cursor,
402 + })
403 + .pipe(Effect.mapError(toIssueError("comments"))),
404 + ),
405 + );
406 +
407 + const templates: IssueService["Service"]["templates"] = (input) =>
408 + requireProject(input).pipe(
409 + Effect.flatMap((project) =>
410 + project.api.listTemplates === undefined || !project.api.capabilities.templates
411 + ? Effect.fail(unsupported("templates", "issue templates"))
412 + : project.api
413 + .listTemplates({
414 + cwd: project.project.workspaceRoot,
415 + host: project.host,
416 + scope: project.scope,
417 + })
418 + .pipe(Effect.mapError(toIssueError("templates"))),
419 + ),
420 + );
421 +
422 + const candidates: IssueService["Service"]["candidates"] = (input) =>
423 + requireProject(input).pipe(
424 + Effect.flatMap((project) =>
425 + project.api.listCandidates === undefined ||
426 + !(project.api.capabilities.labels || project.api.capabilities.assignees)
427 + ? Effect.fail(unsupported("candidates", "labels or assignees"))
428 + : project.api
429 + .listCandidates({
430 + cwd: project.project.workspaceRoot,
431 + host: project.host,
432 + scope: project.scope,
433 + })
434 + .pipe(Effect.mapError(toIssueError("candidates"))),
435 + ),
436 + );
437 +
438 + const create: IssueService["Service"]["create"] = (input) =>
439 + requireWritable(input, "create").pipe(
440 + Effect.flatMap((project) =>
441 + project.api.create === undefined || !project.api.capabilities.create
442 + ? Effect.fail(unsupported("create", "filing issues"))
443 + : project.api
444 + .create({
445 + cwd: project.project.workspaceRoot,
446 + host: project.host,
447 + scope: project.scope,
448 + title: input.title,
449 + body: input.body,
450 + labels: input.labels,
451 + assignees: input.assignees,
452 + })
453 + .pipe(Effect.mapError(toIssueError("create"))),
454 + ),
455 + );
456 +
457 + const comment: IssueService["Service"]["comment"] = (input) =>
458 + requireWritable(input, "comment").pipe(
459 + Effect.flatMap((project) => {
460 + if (input.body.trim().length === 0) {
461 + return Effect.fail(
462 + new IssueOperationError({ operation: "comment", detail: "A comment needs some text." }),
463 + );
464 + }
465 + return project.api.comment === undefined || !project.api.capabilities.comment
466 + ? Effect.fail(unsupported("comment", "comments"))
467 + : project.api
468 + .comment({
469 + cwd: project.project.workspaceRoot,
470 + host: project.host,
471 + scope: project.scope,
472 + key: input.key,
473 + body: input.body,
474 + })
475 + .pipe(Effect.mapError(toIssueError("comment")));
476 + }),
477 + );
478 +
479 + const update: IssueService["Service"]["update"] = (input) =>
480 + requireWritable(input, "update").pipe(
481 + Effect.flatMap((project) => {
482 + const { capabilities } = project.api;
483 + const wantsWords = input.title !== undefined || input.body !== undefined;
484 + if (!wantsWords && input.labels === undefined && input.assignees === undefined) {
485 + return Effect.fail(
486 + new IssueOperationError({ operation: "update", detail: "Nothing to change." }),
487 + );
488 + }
489 + if (project.api.update === undefined) return Effect.fail(unsupported("update", "edits"));
490 + if (wantsWords && !capabilities.edit)
491 + return Effect.fail(unsupported("update", "editing the title or body"));
492 + if (input.labels !== undefined && !capabilities.labels)
493 + return Effect.fail(unsupported("update", "labels"));
494 + if (input.assignees !== undefined && !capabilities.assignees)
495 + return Effect.fail(unsupported("update", "assignees"));
496 + return project.api
497 + .update({
498 + cwd: project.project.workspaceRoot,
499 + host: project.host,
500 + scope: project.scope,
501 + key: input.key,
502 + title: input.title,
503 + body: input.body,
504 + labels: input.labels,
505 + assignees: input.assignees,
506 + })
507 + .pipe(Effect.mapError(toIssueError("update")));
508 + }),
509 + );
510 +
511 + const setState: IssueService["Service"]["setState"] = (input) =>
512 + requireWritable(input, "setState").pipe(
513 + Effect.flatMap((project) => {
514 + const { capabilities } = project.api;
515 + const target = capabilities.states.find((state) => state.name === input.state);
516 + if (project.api.setState === undefined || target === undefined)
517 + return Effect.fail(unsupported("setState", `the state "${input.state}"`));
518 + if (
519 + input.closeReason !== undefined &&
520 + (target.category !== "closed" || !capabilities.closeReasons.includes(input.closeReason))
521 + )
522 + return Effect.fail(unsupported("setState", `the close reason "${input.closeReason}"`));
523 + return project.api
524 + .setState({
525 + cwd: project.project.workspaceRoot,
526 + host: project.host,
527 + scope: project.scope,
528 + key: input.key,
529 + state: input.state,
530 + closeReason: input.closeReason,
531 + })
532 + .pipe(Effect.mapError(toIssueError("setState")));
533 + }),
534 + );
535 +
536 + const react: IssueService["Service"]["react"] = (input) =>
537 + requireWritable(input, "react").pipe(
538 + Effect.flatMap((project) =>
539 + project.api.setReaction === undefined || !project.api.capabilities.reactions
540 + ? Effect.fail(unsupported("react", "reactions"))
541 + : project.api
542 + .setReaction({
543 + cwd: project.project.workspaceRoot,
544 + host: project.host,
545 + scope: project.scope,
546 + key: input.key,
547 + subjectId: input.subjectId,
548 + content: input.content,
549 + reacted: input.reacted,
550 + })
551 + .pipe(Effect.mapError(toIssueError("react"))),
552 + ),
553 + );
554 +
555 + return IssueService.of({
556 + list,
557 + detail: traced("detail", detail),
558 + comments: traced("comments", comments),
559 + templates: traced("templates", templates),
560 + candidates: interactive(traced("candidates", candidates)),
561 + create: interactive(traced("create", create)),
562 + comment: interactive(traced("comment", comment)),
563 + update: interactive(traced("update", update)),
564 + setState: interactive(traced("setState", setState)),
565 + react: interactive(traced("react", react)),
566 + });
567 +});
568 +
569 +export const layer = Layer.effect(IssueService, make);
apps/server/src/issue/IssueTrackerRegistry.ts new
+36
@@ -0,0 +1,36 @@
1 +import * as Context from "effect/Context";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import type { IssueTrackerKind } from "@t3tools/contracts";
5 +import type { IssueTrackerApi } from "@t3tools/source-control-core/server/IssueTracker";
6 +
7 +import * as BuiltInDrivers from "../sourceControl/builtInDrivers.ts";
8 +
9 +export class IssueTrackerRegistry extends Context.Service<
10 + IssueTrackerRegistry,
11 + {
12 + /** Null for a kind with no implementation, which the service reports as unsupported. */
13 + readonly get: (kind: IssueTrackerKind) => IssueTrackerApi | null;
14 + readonly kinds: ReadonlyArray<IssueTrackerKind>;
15 + }
16 +>()("t3/issue/IssueTrackerRegistry") {}
17 +
18 +/** Exported for tests, which stand a registry up from trackers they supply themselves. */
19 +export function fromTrackers(
20 + trackers: ReadonlyArray<IssueTrackerApi>,
21 +): IssueTrackerRegistry["Service"] {
22 + const byKind = new Map(trackers.map((tracker) => [tracker.kind, tracker]));
23 + return {
24 + get: (kind) => byKind.get(kind) ?? null,
25 + kinds: trackers.map((tracker) => tracker.kind),
26 + };
27 +}
28 +
29 +const make = Effect.gen(function* () {
30 + const drivers = yield* BuiltInDrivers.SourceControlDrivers;
31 + return fromTrackers(drivers.flatMap(({ instance }) => instance.issues ?? []));
32 +});
33 +
34 +export const layer = Layer.effect(IssueTrackerRegistry, make).pipe(
35 + Layer.provide(BuiltInDrivers.layer),
36 +);
apps/server/src/observability/RpcInstrumentation.ts
+10
@@ -144,6 +144,16 @@ const RPC_AGGREGATES = {
144 [WS_METHODS.pullRequestsRequestReviewers]: "pull-requests",
145 [WS_METHODS.pullRequestsLabelCandidates]: "pull-requests",
146 [WS_METHODS.pullRequestsSetLabels]: "pull-requests",
147 + [WS_METHODS.issuesList]: "issues",
148 + [WS_METHODS.issuesDetail]: "issues",
149 + [WS_METHODS.issuesComments]: "issues",
150 + [WS_METHODS.issuesTemplates]: "issues",
151 + [WS_METHODS.issuesCandidates]: "issues",
152 + [WS_METHODS.issuesCreate]: "issues",
153 + [WS_METHODS.issuesComment]: "issues",
154 + [WS_METHODS.issuesUpdate]: "issues",
155 + [WS_METHODS.issuesSetState]: "issues",
156 + [WS_METHODS.issuesReact]: "issues",
157 [WS_METHODS.sourceControlLookupRepository]: "source-control",
158 [WS_METHODS.sourceControlCloneRepository]: "source-control",
159 [WS_METHODS.sourceControlPublishRepository]: "source-control",
apps/server/src/server.ts
+5
@@ -54,6 +54,8 @@ import { speechHttpApiLayer } from "./speech/http.ts";
54 import { speechStreamRouteLayer } from "./speech/stream.ts";
55 import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderRegistry.ts";
56 import * as PullRequestService from "./pullRequest/PullRequestService.ts";
57 +import * as IssueService from "./issue/IssueService.ts";
58 +import * as IssueTrackerRegistry from "./issue/IssueTrackerRegistry.ts";
59 import * as SqlitePersistence from "./persistence/Sqlite.ts";
60 import * as PullRequestFilesViewed from "./persistence/PullRequestFilesViewed.ts";
61 import * as PullRequestReviewGuides from "./persistence/PullRequestReviewGuides.ts";
@@ -438,6 +440,8 @@ const layerPullRequestService = PullRequestService.layer.pipe(
440 Layer.provide(SourceControlRateLimit.layer),
441 );
442
443 +const layerIssueService = IssueService.layer.pipe(Layer.provide(IssueTrackerRegistry.layer));
444 +
445 const layerGitManager = GitManager.layer.pipe(
446 Layer.provide(Layer.merge(ProjectionStoreV2.layer, ProjectStore.layer)),
447 Layer.provideMerge(RuntimeLayer.layerProjectSetupScriptRunner),
@@ -862,6 +866,7 @@ const layerMakeRoutes = Layer.mergeAll(
866 Layer.provide(PeerLinkRequests.layer),
867 // Share the service so HTTP/WS clients single-flight reads and invalidate each other's cached patches.
868 Layer.provide(layerPullRequestService),
869 + Layer.provide(layerIssueService),
870 // The same activity instance RunExecutionService reports to, by layer memoization.
871 Layer.provide(
872 ServerBrowser.layer.pipe(
apps/server/src/ws.test.ts
+2
@@ -114,6 +114,7 @@ import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner
114 import * as ProviderRegistry from "./provider/ProviderRegistry.ts";
115 import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
116 import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts";
117 +import * as IssueService from "./issue/IssueService.ts";
118 import * as PullRequestService from "./pullRequest/PullRequestService.ts";
119 import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts";
120 import * as RelayClient from "@t3tools/shared/relayClient";
@@ -858,6 +859,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
859 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
860 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}),
861 Layer.mock(PullRequestService.PullRequestService)({}),
862 + Layer.mock(IssueService.IssueService)({}),
863 Layer.mock(PullRequestSyncReactor.PullRequestSyncReactor)({}),
864 Layer.mock(RelayClient.RelayClient)({}),
865 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}),
apps/server/src/ws.ts
+21 -1
@@ -249,6 +249,7 @@ import * as UsageService from "./usage/UsageService.ts";
249 import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
250 import * as TriageService from "./triage/TriageService.ts";
251 import * as PullRequestService from "./pullRequest/PullRequestService.ts";
252 +import * as IssueService from "./issue/IssueService.ts";
253 import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts";
254 import { listLinkedPullRequestThreads } from "./pullRequest/linkedThreads.ts";
255 import { pullRequestSyncKey } from "./pullRequest/pullRequestSyncKey.ts";
@@ -716,7 +717,13 @@ const ServerWsRpcGroup = WsRpcGroup.middleware(RpcInstrumentation);
717 // crosses TypeScript's instantiation limit and the layer's requirements degrade to
718 // `any`, so the handlers are registered as two disjoint, smaller groups.
719 type ServerWsRpc = RpcGroup.Rpcs<typeof ServerWsRpcGroup>;
719 -const SPLIT_WS_RPC_PREFIXES = ["server", "pullRequests", "provider", "orchestration"] as const;
720 +const SPLIT_WS_RPC_PREFIXES = [
721 + "server",
722 + "pullRequests",
723 + "issues",
724 + "provider",
725 + "orchestration",
726 +] as const;
727 type SplitWsRpc = Extract<
728 ServerWsRpc,
729 { readonly _tag: `${(typeof SPLIT_WS_RPC_PREFIXES)[number]}.${string}` }
@@ -1474,6 +1481,7 @@ export const layerWsRpc = (
1481 const secretRequests = yield* SecretRequests.SecretRequests;
1482 const guestShares = yield* GuestShareService.GuestShareService;
1483 const pullRequests = yield* PullRequestService.PullRequestService;
1484 + const issues = yield* IssueService.IssueService;
1485 const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
1486 const pullRequestSync = yield* PullRequestSyncReactor.PullRequestSyncReactor;
1487 const deviceService = yield* DeviceService.DeviceService;
@@ -1962,6 +1970,16 @@ export const layerWsRpc = (
1970 });
1971
1972 const handlers = ServerWsRpcGroup.of({
1973 + [WS_METHODS.issuesList]: (input) => issues.list(input),
1974 + [WS_METHODS.issuesDetail]: (input) => issues.detail(input),
1975 + [WS_METHODS.issuesComments]: (input) => issues.comments(input),
1976 + [WS_METHODS.issuesTemplates]: (input) => issues.templates(input),
1977 + [WS_METHODS.issuesCandidates]: (input) => issues.candidates(input),
1978 + [WS_METHODS.issuesCreate]: (input) => issues.create(input),
1979 + [WS_METHODS.issuesComment]: (input) => issues.comment(input),
1980 + [WS_METHODS.issuesUpdate]: (input) => issues.update(input),
1981 + [WS_METHODS.issuesSetState]: (input) => issues.setState(input),
1982 + [WS_METHODS.issuesReact]: (input) => issues.react(input),
1983 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) =>
1984 Effect.annotateCurrentSpan({
1985 "orchestration_v2.command_id": command.commandId,
@@ -3576,6 +3594,7 @@ export const layer = Layer.unwrap(
3594 const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
3595 const npmRelease = yield* NpmRelease.NpmRelease;
3596 const pullRequests = yield* PullRequestService.PullRequestService;
3597 + const issues = yield* IssueService.IssueService;
3598 const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
3599 const peerLinks = yield* PeerLinks.PeerLinks;
3600 const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests;
@@ -3665,6 +3684,7 @@ export const layer = Layer.unwrap(
3684 Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),
3685 // Share server-lifetime PR caches so WS mutations invalidate every client's HTTP diffs.
3686 Layer.provide(Layer.succeed(PullRequestService.PullRequestService, pullRequests)),
3687 + Layer.provide(Layer.succeed(IssueService.IssueService, issues)),
3688 Layer.provide(OtlpEndpointCheck.layer),
3689 Layer.provide(
3690 Layer.succeed(
packages/contracts/src/clientRpcPermissions.ts
+5
@@ -40,6 +40,11 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
40 [WS_METHODS.pullRequestsSetFilesViewed]: AuthSourceControlWriteScope,
41 [WS_METHODS.pullRequestsRequestReviewers]: AuthSourceControlWriteScope,
42 [WS_METHODS.pullRequestsSetLabels]: AuthSourceControlWriteScope,
43 + [WS_METHODS.issuesCreate]: AuthSourceControlWriteScope,
44 + [WS_METHODS.issuesComment]: AuthSourceControlWriteScope,
45 + [WS_METHODS.issuesUpdate]: AuthSourceControlWriteScope,
46 + [WS_METHODS.issuesSetState]: AuthSourceControlWriteScope,
47 + [WS_METHODS.issuesReact]: AuthSourceControlWriteScope,
48 // Writing a guide runs a model on this environment's providers, which reading one does not.
49 [WS_METHODS.pullRequestsGenerateReviewGuide]: AuthOrchestrationOperateScope,
50 [WS_METHODS.projectsCreateFromThread]: AuthOrchestrationOperateScope,
packages/contracts/src/index.ts
+1
@@ -36,6 +36,7 @@ export * from "./projectClone.ts";
36 export * from "./speech.ts";
37 export * from "./pullRequest.ts";
38 export * from "./pullRequestReviewGuide.ts";
39 +export * from "./issue.ts";
40 export * from "./orchestrationDispatch.ts";
41 export * from "./orchestrationProject.ts";
42 export * from "./orchestrationV2.ts";
packages/contracts/src/issue.ts new
+471
@@ -0,0 +1,471 @@
1 +import * as Schema from "effect/Schema";
2 +import * as HttpServerRespondable from "effect/http/HttpServerRespondable";
3 +import * as HttpServerResponse from "effect/http/HttpServerResponse";
4 +
5 +import {
6 + IsoDateTime,
7 + NonNegativeInt,
8 + PositiveInt,
9 + ProjectId,
10 + TrimmedNonEmptyString,
11 +} from "./baseSchemas.ts";
12 +import { PullRequestActor, PullRequestLabel, PullRequestState } from "./pullRequest.ts";
13 +
14 +/**
15 + * Which tracker an issue lives in. Git hosts reuse their `SourceControlProviderKind` spelling
16 + * (`github`, `gitlab`); standalone trackers get their own (`linear`, `jira`). Branded apart from
17 + * the source control kind because the two sets are not the same: Bitbucket is a git host with no
18 + * tracker, and Linear is a tracker with no git host.
19 + */
20 +export const IssueTrackerKind = TrimmedNonEmptyString.check(
21 + Schema.isMaxLength(64),
22 + Schema.isPattern(/^[a-z][a-z0-9-]*$/),
23 +).pipe(Schema.brand("IssueTrackerKind"));
24 +export type IssueTrackerKind = typeof IssueTrackerKind.Type;
25 +
26 +export const IssueActor = PullRequestActor;
27 +export type IssueActor = typeof IssueActor.Type;
28 +
29 +export const IssueLabel = PullRequestLabel;
30 +export type IssueLabel = typeof IssueLabel.Type;
31 +
32 +/**
33 + * Where an issue stands, in two parts: the category every tracker has, and the name this tracker
34 + * gives it. GitHub only has the two; Linear and Jira have a workflow of their own ("In Review",
35 + * "Backlog"), which `name` carries verbatim so the page can show the tracker's word while every
36 + * filter and badge keys off `category`.
37 + */
38 +export const IssueStateCategory = Schema.Literals(["open", "closed"]);
39 +export type IssueStateCategory = typeof IssueStateCategory.Type;
40 +
41 +export const IssueState = Schema.Struct({
42 + category: IssueStateCategory,
43 + name: TrimmedNonEmptyString,
44 + /** Why it was closed, where the tracker records one (GitHub: `completed` / `not-planned`). */
45 + closeReason: Schema.optional(TrimmedNonEmptyString),
46 +});
47 +export type IssueState = typeof IssueState.Type;
48 +
49 +/** What a listing asks for: either category, or both. */
50 +export const IssueListState = Schema.Literals(["all", "open", "closed"]);
51 +export type IssueListState = typeof IssueListState.Type;
52 +
53 +export const IssueInvolvement = Schema.Literals(["all", "assigned", "authored", "mentioned"]);
54 +export type IssueInvolvement = typeof IssueInvolvement.Type;
55 +
56 +export const IssueReactionContent = Schema.Literals([
57 + "thumbs-up",
58 + "thumbs-down",
59 + "laugh",
60 + "hooray",
61 + "confused",
62 + "heart",
63 + "rocket",
64 + "eyes",
65 +]);
66 +export type IssueReactionContent = typeof IssueReactionContent.Type;
67 +
68 +export const IssueReaction = Schema.Struct({
69 + content: IssueReactionContent,
70 + count: PositiveInt,
71 + /** Who reacted, as far as the tracker named them; the viewer is left out and shown as "You". */
72 + actors: Schema.Array(TrimmedNonEmptyString),
73 + viewerHasReacted: Schema.Boolean,
74 +});
75 +export type IssueReaction = typeof IssueReaction.Type;
76 +
77 +/**
78 + * Addresses one issue: `scope` is the tracker's own container (`owner/repo`, a team key) and
79 + * `key` the issue's native id in it. `host` is absent for the kind's public host. `projectId`
80 + * names the project whose credentials serve the read, which need not own the issue.
81 + */
82 +export const IssueRef = Schema.Struct({
83 + projectId: ProjectId,
84 + tracker: IssueTrackerKind,
85 + host: Schema.optional(TrimmedNonEmptyString),
86 + scope: TrimmedNonEmptyString,
87 + key: TrimmedNonEmptyString,
88 +});
89 +export type IssueRef = typeof IssueRef.Type;
90 +
91 +/** A scope with no issue in it, for reads about the container itself: templates, candidates. */
92 +export const IssueScopeRef = Schema.Struct({
93 + projectId: ProjectId,
94 + tracker: IssueTrackerKind,
95 + host: Schema.optional(TrimmedNonEmptyString),
96 + scope: TrimmedNonEmptyString,
97 +});
98 +export type IssueScopeRef = typeof IssueScopeRef.Type;
99 +
100 +/** One row of a listing. Carries everything a list needs and nothing a detail needs. */
101 +export const IssueSummary = Schema.Struct({
102 + tracker: IssueTrackerKind,
103 + host: TrimmedNonEmptyString,
104 + scope: TrimmedNonEmptyString,
105 + key: TrimmedNonEmptyString,
106 + /** How the tracker writes the key for people: `#123` on a git host, `ENG-123` on Linear. */
107 + displayKey: TrimmedNonEmptyString,
108 + title: TrimmedNonEmptyString,
109 + url: TrimmedNonEmptyString,
110 + author: Schema.NullOr(IssueActor),
111 + state: IssueState,
112 + createdAt: IsoDateTime,
113 + updatedAt: IsoDateTime,
114 + closedAt: Schema.NullOr(IsoDateTime),
115 + assignees: Schema.Array(IssueActor),
116 + labels: Schema.Array(IssueLabel),
117 + commentCount: NonNegativeInt,
118 +});
119 +export type IssueSummary = typeof IssueSummary.Type;
120 +
121 +export const IssueListEntry = Schema.Struct({
122 + ...IssueSummary.fields,
123 + projectId: ProjectId,
124 + projectTitle: TrimmedNonEmptyString,
125 +});
126 +export type IssueListEntry = typeof IssueListEntry.Type;
127 +
128 +export const IssueComment = Schema.Struct({
129 + id: TrimmedNonEmptyString,
130 + author: Schema.NullOr(IssueActor),
131 + body: Schema.String,
132 + createdAt: IsoDateTime,
133 + url: Schema.NullOr(Schema.String),
134 + /** Absent from a tracker with no reactions, which differs from none on this comment. */
135 + reactions: Schema.optional(Schema.Array(IssueReaction)),
136 +});
137 +export type IssueComment = typeof IssueComment.Type;
138 +
139 +/**
140 + * Something that happened to an issue that nobody wrote words for: it was closed, labelled,
141 + * assigned, renamed. Kinds are the common vocabulary; a tracker drops what it cannot map rather
142 + * than guessing.
143 + */
144 +export const IssueEventKind = Schema.Literals([
145 + "closed",
146 + "reopened",
147 + "labeled",
148 + "unlabeled",
149 + "assigned",
150 + "unassigned",
151 + "renamed",
152 + "referenced",
153 + "state-changed",
154 +]);
155 +export type IssueEventKind = typeof IssueEventKind.Type;
156 +
157 +export const IssueEvent = Schema.Struct({
158 + id: TrimmedNonEmptyString,
159 + kind: IssueEventKind,
160 + actor: Schema.NullOr(IssueActor),
161 + createdAt: IsoDateTime,
162 + /** What the event was about, where it has a subject: a label name, a login, a new title. */
163 + detail: Schema.NullOr(TrimmedNonEmptyString),
164 +});
165 +export type IssueEvent = typeof IssueEvent.Type;
166 +
167 +/** A change request the tracker says closes or mentions this issue. */
168 +export const IssueLinkedPullRequest = Schema.Struct({
169 + repository: TrimmedNonEmptyString,
170 + number: PositiveInt,
171 + title: TrimmedNonEmptyString,
172 + url: TrimmedNonEmptyString,
173 + state: PullRequestState,
174 + isDraft: Schema.Boolean,
175 + /** Merging it closes this issue, rather than only citing it. */
176 + closesIssue: Schema.Boolean,
177 +});
178 +export type IssueLinkedPullRequest = typeof IssueLinkedPullRequest.Type;
179 +
180 +/**
181 + * What a tracker can do at all, so a surface never offers an action that would fail. The
182 + * service refuses a call outside these before it reaches the driver.
183 + */
184 +export const IssueCapabilities = Schema.Struct({
185 + create: Schema.Boolean,
186 + /** Title and body can be rewritten after filing. */
187 + edit: Schema.Boolean,
188 + comment: Schema.Boolean,
189 + labels: Schema.Boolean,
190 + assignees: Schema.Boolean,
191 + /** Reactions can be read and written on the issue and its comments. */
192 + reactions: Schema.Boolean,
193 + /** The scope offers starting points for a new issue. */
194 + templates: Schema.Boolean,
195 + /** The tracker reports linked change requests of its own accord. */
196 + linkedPullRequests: Schema.Boolean,
197 + /** State changes arrive as events beside the comments, not only as comments. */
198 + events: Schema.Boolean,
199 + /** The tracker narrows a listing by free text itself. */
200 + search: Schema.Boolean,
201 + /**
202 + * The states this tracker can be asked to move an issue into, by name. A git host offers
203 + * `open` and `closed`; a workflow tracker offers its own columns. Empty means state cannot be
204 + * changed from here.
205 + */
206 + states: Schema.Array(IssueState),
207 + /** Reasons a close can carry. Empty means a close takes none. */
208 + closeReasons: Schema.Array(TrimmedNonEmptyString),
209 +});
210 +export type IssueCapabilities = typeof IssueCapabilities.Type;
211 +
212 +/**
213 + * What the signed-in account may do with this issue, which `capabilities` says nothing about.
214 + * A permission the tracker reports nothing about is granted, so a refusal comes from the
215 + * tracker, which says why, rather than from a missing control.
216 + */
217 +export const IssueViewerPermissions = Schema.Struct({
218 + setState: Schema.Boolean,
219 + comment: Schema.Boolean,
220 + edit: Schema.Boolean,
221 + labels: Schema.Boolean,
222 + assignees: Schema.Boolean,
223 +});
224 +export type IssueViewerPermissions = typeof IssueViewerPermissions.Type;
225 +
226 +export const IssueDetail = Schema.Struct({
227 + ...IssueSummary.fields,
228 + projectId: ProjectId,
229 + projectTitle: TrimmedNonEmptyString,
230 + /** False for an issue outside every project's scope, which is read-only through this server. */
231 + writable: Schema.Boolean,
232 + capabilities: IssueCapabilities,
233 + viewerPermissions: IssueViewerPermissions,
234 + /** The signed-in account, so a comment edit is offered only on the viewer's own remarks. */
235 + viewer: Schema.NullOr(TrimmedNonEmptyString),
236 + body: Schema.String,
237 + reactions: Schema.optional(Schema.Array(IssueReaction)),
238 + comments: Schema.Array(IssueComment),
239 + /** Where older comments carry on; null once the conversation is whole. */
240 + commentsCursor: Schema.NullOr(TrimmedNonEmptyString),
241 + events: Schema.Array(IssueEvent),
242 + linkedPullRequests: Schema.Array(IssueLinkedPullRequest),
243 +});
244 +export type IssueDetail = typeof IssueDetail.Type;
245 +
246 +/** Older comments, one page past a cursor the detail or a previous page handed over. */
247 +export const IssueCommentsPageInput = Schema.Struct({
248 + ...IssueRef.fields,
249 + cursor: TrimmedNonEmptyString.check(Schema.isMaxLength(4_096)),
250 +});
251 +export type IssueCommentsPageInput = typeof IssueCommentsPageInput.Type;
252 +
253 +export const IssueCommentsPage = Schema.Struct({
254 + comments: Schema.Array(IssueComment),
255 + nextCursor: Schema.NullOr(TrimmedNonEmptyString),
256 +});
257 +export type IssueCommentsPage = typeof IssueCommentsPage.Type;
258 +
259 +/** Where each scope a listing already reached carries on, keyed `"<host> <scope>"`. */
260 +export const IssueListCursors = Schema.Record(
261 + TrimmedNonEmptyString,
262 + TrimmedNonEmptyString.check(Schema.isMaxLength(4_096)),
263 +);
264 +export type IssueListCursors = typeof IssueListCursors.Type;
265 +
266 +export const IssueListInput = Schema.Struct({
267 + state: IssueListState,
268 + involvement: Schema.optional(IssueInvolvement),
269 + projectId: Schema.optional(ProjectId),
270 + /** Narrows to one host, named as the host itself. Absent means every host the workspace has. */
271 + host: Schema.optional(TrimmedNonEmptyString),
272 + /** Rows per scope, which with a continuation is rows per slice. */
273 + limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 200 }))),
274 + /** Carry on from an earlier answer: only the scopes named here are read, one slice each. */
275 + cursors: Schema.optional(IssueListCursors),
276 + /** Free text the trackers themselves are asked to match. */
277 + query: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(200))),
278 +});
279 +export type IssueListInput = typeof IssueListInput.Type;
280 +
281 +/** One tracker account the workspace has projects on, and whether it can be read right now. */
282 +export const IssueTrackerSummary = Schema.Struct({
283 + tracker: IssueTrackerKind,
284 + host: TrimmedNonEmptyString,
285 + projectCount: PositiveInt,
286 + capabilities: Schema.NullOr(IssueCapabilities),
287 + /** False when the tracker's tool or credentials are missing, with `detail` saying which. */
288 + configured: Schema.Boolean,
289 + detail: Schema.NullOr(TrimmedNonEmptyString),
290 +});
291 +export type IssueTrackerSummary = typeof IssueTrackerSummary.Type;
292 +
293 +export const IssueListProjectError = Schema.Struct({
294 + projectId: ProjectId,
295 + projectTitle: TrimmedNonEmptyString,
296 + message: TrimmedNonEmptyString,
297 +});
298 +export type IssueListProjectError = typeof IssueListProjectError.Type;
299 +
300 +export const IssueListResult = Schema.Struct({
301 + /** The signed-in account per host, which is what involvement compares against. */
302 + viewers: Schema.Record(TrimmedNonEmptyString, TrimmedNonEmptyString),
303 + trackers: Schema.Array(IssueTrackerSummary),
304 + /** By update, newest first, across every scope this answer covers. */
305 + entries: Schema.Array(IssueListEntry),
306 + errors: Schema.Array(IssueListProjectError),
307 + /** Where each scope carries on, sent straight back as `cursors`. Absent once a scope is done. */
308 + nextCursors: IssueListCursors,
309 +});
310 +export type IssueListResult = typeof IssueListResult.Type;
311 +
312 +const IssueTitle = TrimmedNonEmptyString.check(Schema.isMaxLength(1024));
313 +// Not trimmed: a body is markdown, where leading spaces open a code block. The bound keeps
314 +// oversized payloads off the wire; the service rejects a comment that is only whitespace.
315 +const IssueBody = Schema.String.check(Schema.isMaxLength(65_536));
316 +const CommentBody = Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536));
317 +
318 +export const IssueCreateInput = Schema.Struct({
319 + ...IssueScopeRef.fields,
320 + title: IssueTitle,
321 + /** May be empty: an issue with a title and nothing else is a legitimate one. */
322 + body: IssueBody,
323 + labels: Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(50)),
324 + assignees: Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(25)),
325 +});
326 +export type IssueCreateInput = typeof IssueCreateInput.Type;
327 +
328 +export const IssueCreateResult = Schema.Struct({
329 + key: TrimmedNonEmptyString,
330 + displayKey: TrimmedNonEmptyString,
331 + url: TrimmedNonEmptyString,
332 +});
333 +export type IssueCreateResult = typeof IssueCreateResult.Type;
334 +
335 +export const IssueCommentInput = Schema.Struct({
336 + ...IssueRef.fields,
337 + body: CommentBody,
338 +});
339 +export type IssueCommentInput = typeof IssueCommentInput.Type;
340 +
341 +/**
342 + * Rewrites the issue's own fields. Every field is optional and only the present ones are
343 + * written; `labels` and `assignees` are the whole set, which is how every tracker writes them.
344 + * The service refuses a request with nothing present.
345 + */
346 +export const IssueUpdateInput = Schema.Struct({
347 + ...IssueRef.fields,
348 + title: Schema.optional(IssueTitle),
349 + body: Schema.optional(IssueBody),
350 + labels: Schema.optional(Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(50))),
351 + assignees: Schema.optional(Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(25))),
352 +});
353 +export type IssueUpdateInput = typeof IssueUpdateInput.Type;
354 +
355 +/** Moves the issue to one of the states the tracker declared in `capabilities.states`. */
356 +export const IssueSetStateInput = Schema.Struct({
357 + ...IssueRef.fields,
358 + state: TrimmedNonEmptyString,
359 + /** Only meaningful for a closing state on a tracker that declared `closeReasons`. */
360 + closeReason: Schema.optional(TrimmedNonEmptyString),
361 +});
362 +export type IssueSetStateInput = typeof IssueSetStateInput.Type;
363 +
364 +export const IssueReactionInput = Schema.Struct({
365 + ...IssueRef.fields,
366 + /** Absent reacts to the issue itself; present names a comment id as the detail carried it. */
367 + subjectId: Schema.optional(TrimmedNonEmptyString),
368 + content: IssueReactionContent,
369 + reacted: Schema.Boolean,
370 +});
371 +export type IssueReactionInput = typeof IssueReactionInput.Type;
372 +
373 +/**
374 + * One starting point a scope offers for a new issue. Only the body-shaped kind travels here:
375 + * GitHub's typed issue forms are flattened to a body by the driver, so a composer on any
376 + * tracker is one text box with a draft in it.
377 + */
378 +export const IssueTemplate = Schema.Struct({
379 + key: TrimmedNonEmptyString,
380 + name: TrimmedNonEmptyString,
381 + about: Schema.String,
382 + title: Schema.String,
383 + body: Schema.String,
384 + labels: Schema.Array(TrimmedNonEmptyString),
385 + assignees: Schema.Array(TrimmedNonEmptyString),
386 +});
387 +export type IssueTemplate = typeof IssueTemplate.Type;
388 +
389 +export const IssueTemplateList = Schema.Struct({
390 + templates: Schema.Array(IssueTemplate),
391 + /** False where the scope's config forbids an issue filed from nothing. */
392 + blankIssuesEnabled: Schema.Boolean,
393 +});
394 +export type IssueTemplateList = typeof IssueTemplateList.Type;
395 +
396 +export const IssueLabelCandidate = Schema.Struct({
397 + ...IssueLabel.fields,
398 + description: Schema.NullOr(Schema.String),
399 +});
400 +export type IssueLabelCandidate = typeof IssueLabelCandidate.Type;
401 +
402 +export const IssueAssigneeCandidate = Schema.Struct({
403 + ...IssueActor.fields,
404 + /** How the tracker addresses this person on a write, which is not always the login. */
405 + id: TrimmedNonEmptyString,
406 +});
407 +export type IssueAssigneeCandidate = typeof IssueAssigneeCandidate.Type;
408 +
409 +/** The labels and people a scope offers, read when a picker opens rather than with every issue. */
410 +export const IssueCandidates = Schema.Struct({
411 + labels: Schema.Array(IssueLabelCandidate),
412 + assignees: Schema.Array(IssueAssigneeCandidate),
413 + /** The tracker has more than were read, so somebody missing is not necessarily ineligible. */
414 + truncated: Schema.Boolean,
415 +});
416 +export type IssueCandidates = typeof IssueCandidates.Type;
417 +
418 +export const IssueUnavailableReason = Schema.Literals([
419 + "tool-missing",
420 + "unauthenticated",
421 + "tracker-unsupported",
422 +]);
423 +export type IssueUnavailableReason = typeof IssueUnavailableReason.Type;
424 +
425 +/** The tracker cannot be read at all for this project, as opposed to one request failing. */
426 +export class IssueUnavailableError extends Schema.TaggedError<IssueUnavailableError>()(
427 + "IssueUnavailableError",
428 + {
429 + reason: IssueUnavailableReason,
430 + tracker: Schema.optional(IssueTrackerKind),
431 + cause: Schema.optional(Schema.Defect()),
432 + },
433 + { httpApiStatus: 503 },
434 +) {
435 + [HttpServerRespondable.symbol]() {
436 + return HttpServerResponse.schemaJson(IssueUnavailableError)(this, { status: 503 });
437 + }
438 +
439 + override get message(): string {
440 + switch (this.reason) {
441 + case "tool-missing":
442 + return "The tool this tracker is read through is not installed or set up.";
443 + case "unauthenticated":
444 + return "This tracker has no working credentials.";
445 + case "tracker-unsupported":
446 + return "Issues cannot be browsed for this project yet.";
447 + }
448 + }
449 +}
450 +
451 +export class IssueOperationError extends Schema.TaggedError<IssueOperationError>()(
452 + "IssueOperationError",
453 + {
454 + operation: Schema.String,
455 + detail: TrimmedNonEmptyString,
456 + reason: Schema.optional(Schema.Literals(["not-found", "read-only", "rate-limited"])),
457 + retryAt: Schema.optional(Schema.Number),
458 + cause: Schema.optional(Schema.Defect()),
459 + },
460 + { httpApiStatus: 502 },
461 +) {
462 + [HttpServerRespondable.symbol]() {
463 + return HttpServerResponse.schemaJson(IssueOperationError)(this, { status: 502 });
464 + }
465 +
466 + override get message(): string {
467 + return `Issue operation ${this.operation} failed: ${this.detail}`;
468 + }
469 +}
470 +
471 +export type IssueError = IssueUnavailableError | IssueOperationError;
packages/contracts/src/rpc.ts
+109
@@ -169,6 +169,25 @@ import {
169 ProviderUploadFeedbackResult,
170 } from "./provider.ts";
171 import { ProviderInstanceId, ProviderInstanceMutation } from "./providerInstance.ts";
172 +import {
173 + IssueCandidates,
174 + IssueCommentInput,
175 + IssueCommentsPage,
176 + IssueCommentsPageInput,
177 + IssueCreateInput,
178 + IssueCreateResult,
179 + IssueDetail,
180 + IssueListInput,
181 + IssueListResult,
182 + IssueOperationError,
183 + IssueReactionInput,
184 + IssueRef,
185 + IssueScopeRef,
186 + IssueSetStateInput,
187 + IssueTemplateList,
188 + IssueUnavailableError,
189 + IssueUpdateInput,
190 +} from "./issue.ts";
191 import {
192 GuestShareCreateError,
193 GuestShareCreateInput,
@@ -602,6 +621,18 @@ export const WS_METHODS = {
621 pullRequestsLabelCandidates: "pullRequests.labelCandidates",
622 pullRequestsSetLabels: "pullRequests.setLabels",
623
624 + // Issue tracking methods
625 + issuesList: "issues.list",
626 + issuesDetail: "issues.detail",
627 + issuesComments: "issues.comments",
628 + issuesTemplates: "issues.templates",
629 + issuesCandidates: "issues.candidates",
630 + issuesCreate: "issues.create",
631 + issuesComment: "issues.comment",
632 + issuesUpdate: "issues.update",
633 + issuesSetState: "issues.setState",
634 + issuesReact: "issues.react",
635 +
636 sourceControlLookupRepository: "sourceControl.lookupRepository",
637 sourceControlCloneRepository: "sourceControl.cloneRepository",
638 sourceControlPublishRepository: "sourceControl.publishRepository",
@@ -1283,6 +1314,74 @@ const WsPullRequestsSetLabelsRpc = Rpc.make(WS_METHODS.pullRequestsSetLabels, {
1314 error: PullRequestRpcError,
1315 });
1316
1317 +const IssueRpcError = Schema.Union([
1318 + IssueUnavailableError,
1319 + IssueOperationError,
1320 + EnvironmentAuthorizationError,
1321 +]);
1322 +
1323 +const WsIssuesListRpc = Rpc.make(WS_METHODS.issuesList, {
1324 + payload: IssueListInput,
1325 + success: IssueListResult,
1326 + error: IssueRpcError,
1327 +});
1328 +
1329 +const WsIssuesDetailRpc = Rpc.make(WS_METHODS.issuesDetail, {
1330 + payload: IssueRef,
1331 + success: IssueDetail,
1332 + error: IssueRpcError,
1333 +});
1334 +
1335 +/** Older comments, one page at a time, past the cursor the detail handed over. */
1336 +const WsIssuesCommentsRpc = Rpc.make(WS_METHODS.issuesComments, {
1337 + payload: IssueCommentsPageInput,
1338 + success: IssueCommentsPage,
1339 + error: IssueRpcError,
1340 +});
1341 +
1342 +const WsIssuesTemplatesRpc = Rpc.make(WS_METHODS.issuesTemplates, {
1343 + payload: IssueScopeRef,
1344 + success: IssueTemplateList,
1345 + error: IssueRpcError,
1346 +});
1347 +
1348 +/** Read when a label or assignee picker opens, not with every issue. */
1349 +const WsIssuesCandidatesRpc = Rpc.make(WS_METHODS.issuesCandidates, {
1350 + payload: IssueScopeRef,
1351 + success: IssueCandidates,
1352 + error: IssueRpcError,
1353 +});
1354 +
1355 +const WsIssuesCreateRpc = Rpc.make(WS_METHODS.issuesCreate, {
1356 + payload: IssueCreateInput,
1357 + success: IssueCreateResult,
1358 + error: IssueRpcError,
1359 +});
1360 +
1361 +const WsIssuesCommentRpc = Rpc.make(WS_METHODS.issuesComment, {
1362 + payload: IssueCommentInput,
1363 + success: Schema.Void,
1364 + error: IssueRpcError,
1365 +});
1366 +
1367 +const WsIssuesUpdateRpc = Rpc.make(WS_METHODS.issuesUpdate, {
1368 + payload: IssueUpdateInput,
1369 + success: Schema.Void,
1370 + error: IssueRpcError,
1371 +});
1372 +
1373 +const WsIssuesSetStateRpc = Rpc.make(WS_METHODS.issuesSetState, {
1374 + payload: IssueSetStateInput,
1375 + success: Schema.Void,
1376 + error: IssueRpcError,
1377 +});
1378 +
1379 +const WsIssuesReactRpc = Rpc.make(WS_METHODS.issuesReact, {
1380 + payload: IssueReactionInput,
1381 + success: Schema.Void,
1382 + error: IssueRpcError,
1383 +});
1384 +
1385 const WsSourceControlLookupRepositoryRpc = Rpc.make(WS_METHODS.sourceControlLookupRepository, {
1386 payload: SourceControlRepositoryLookupInput,
1387 success: SourceControlRepositoryInfo,
@@ -2111,6 +2210,16 @@ export class RpcScopeAuthorization extends RpcMiddleware.Service<RpcScopeAuthori
2210 ) {}
2211
2212 export const WsRpcGroup = RpcGroup.make(
2213 + WsIssuesListRpc,
2214 + WsIssuesDetailRpc,
2215 + WsIssuesCommentsRpc,
2216 + WsIssuesTemplatesRpc,
2217 + WsIssuesCandidatesRpc,
2218 + WsIssuesCreateRpc,
2219 + WsIssuesCommentRpc,
2220 + WsIssuesUpdateRpc,
2221 + WsIssuesSetStateRpc,
2222 + WsIssuesReactRpc,
2223 WsGuestShareCreateRpc,
2224 WsServerProbeRpc,
2225 WsServerGetConfigRpc,
packages/source-control-core/package.json
+4
@@ -35,6 +35,10 @@
35 "types": "./src/server/pullRequestChecks.ts",
36 "import": "./src/server/pullRequestChecks.ts"
37 },
38 + "./server/IssueTracker": {
39 + "types": "./src/server/IssueTracker.ts",
40 + "import": "./src/server/IssueTracker.ts"
41 + },
42 "./server/PullRequestProvider": {
43 "types": "./src/server/PullRequestProvider.ts",
44 "import": "./src/server/PullRequestProvider.ts"
packages/source-control-core/src/server/IssueTracker.ts new
+178
@@ -0,0 +1,178 @@
1 +/**
2 + * The port every issue tracker implements. A tracker hands back the neutral contract types and
3 + * declares what it cannot do in `capabilities`; the service refuses a call outside them.
4 + */
5 +import * as Schema from "effect/Schema";
6 +import type * as Effect from "effect/Effect";
7 +import type {
8 + IssueCandidates,
9 + IssueCapabilities,
10 + IssueComment,
11 + IssueCommentsPage,
12 + IssueCreateResult,
13 + IssueEvent,
14 + IssueInvolvement,
15 + IssueLinkedPullRequest,
16 + IssueListState,
17 + IssueReaction,
18 + IssueReactionContent,
19 + IssueSummary,
20 + IssueTemplateList,
21 + IssueTrackerKind,
22 + IssueViewerPermissions,
23 +} from "@t3tools/contracts";
24 +import { IssueTrackerKind as IssueTrackerKindSchema } from "@t3tools/contracts";
25 +
26 +/**
27 + * The one failure shape every tracker reports, so the service can decide what a failure means
28 + * without knowing which CLI or API produced it. A missing or unauthenticated tool disables the
29 + * tracker for the whole workspace; everything else is specific to the request.
30 + */
31 +export class IssueTrackerError extends Schema.TaggedError<IssueTrackerError>()(
32 + "IssueTrackerError",
33 + {
34 + tracker: IssueTrackerKindSchema,
35 + operation: Schema.String,
36 + reason: Schema.Literals([
37 + "missing-tool",
38 + "unauthenticated",
39 + "rate-limited",
40 + "not-found",
41 + "failed",
42 + ]),
43 + detail: Schema.String,
44 + retryAt: Schema.optional(Schema.Number),
45 + cause: Schema.optional(Schema.Defect()),
46 + },
47 +) {
48 + override get message(): string {
49 + return `${this.tracker} failed in ${this.operation}: ${this.detail}`;
50 + }
51 +}
52 +
53 +/**
54 + * Where a tracker's issues are addressed from. `cwd` is a checkout whose credentials serve the
55 + * read; `host` is where the tracker is served from (`github.com`, a GHE install, `linear.app`);
56 + * `scope` is the tracker's own container — a repository path, a team or project key.
57 + */
58 +export interface IssueScopeTarget {
59 + readonly cwd: string;
60 + readonly host: string;
61 + readonly scope: string;
62 +}
63 +
64 +export interface IssueTarget extends IssueScopeTarget {
65 + /** The issue's native id within the scope: `"123"` on GitHub, `"ENG-123"` on Linear. */
66 + readonly key: string;
67 +}
68 +
69 +/** An issue as the tracker sees it, before the service attaches project context. */
70 +export type TrackerIssueSummary = Omit<IssueSummary, "tracker" | "host" | "scope">;
71 +
72 +export interface TrackerIssuePage {
73 + readonly items: ReadonlyArray<TrackerIssueSummary>;
74 + /** Where the next slice starts, or null once the tracker has nothing more. Opaque. */
75 + readonly nextCursor: string | null;
76 +}
77 +
78 +export interface TrackerIssueDetail extends TrackerIssueSummary {
79 + readonly body: string;
80 + readonly viewer: string | null;
81 + readonly viewerPermissions: IssueViewerPermissions;
82 + readonly reactions?: ReadonlyArray<IssueReaction>;
83 + readonly comments: ReadonlyArray<IssueComment>;
84 + /** Where older comments carry on; null once the conversation is whole. */
85 + readonly commentsCursor: string | null;
86 + readonly events: ReadonlyArray<IssueEvent>;
87 + readonly linkedPullRequests: ReadonlyArray<IssueLinkedPullRequest>;
88 +}
89 +
90 +export interface IssueTrackerApi {
91 + readonly kind: IssueTrackerKind;
92 + readonly capabilities: IssueCapabilities;
93 +
94 + /** The signed-in account, which is what involvement filtering compares against. */
95 + readonly getViewer: (input: {
96 + readonly cwd: string;
97 + readonly host: string;
98 + }) => Effect.Effect<string, IssueTrackerError>;
99 +
100 + readonly listIssues: (
101 + input: IssueScopeTarget & {
102 + readonly state: IssueListState;
103 + readonly involvement: IssueInvolvement;
104 + readonly viewer: string;
105 + readonly limit: number;
106 + /** Free text as the tracker understands it; ignored by a tracker without `search`. */
107 + readonly query?: string | undefined;
108 + /** A cursor this tracker handed back from an earlier page. Absent asks for the first. */
109 + readonly cursor?: string | undefined;
110 + },
111 + ) => Effect.Effect<TrackerIssuePage, IssueTrackerError>;
112 +
113 + /** The issue with its first page of conversation, in one read where the tracker allows. */
114 + readonly getIssue: (input: IssueTarget) => Effect.Effect<TrackerIssueDetail, IssueTrackerError>;
115 +
116 + /** One page of older comments past a cursor `getIssue` or a previous page handed over. */
117 + readonly getComments: (
118 + input: IssueTarget & { readonly cursor: string },
119 + ) => Effect.Effect<IssueCommentsPage, IssueTrackerError>;
120 +
121 + /** Only called when `capabilities.create` is true. */
122 + readonly create?: (
123 + input: IssueScopeTarget & {
124 + readonly title: string;
125 + readonly body: string;
126 + readonly labels: ReadonlyArray<string>;
127 + readonly assignees: ReadonlyArray<string>;
128 + },
129 + ) => Effect.Effect<IssueCreateResult, IssueTrackerError>;
130 +
131 + /** Only called when `capabilities.comment` is true. */
132 + readonly comment?: (
133 + input: IssueTarget & { readonly body: string },
134 + ) => Effect.Effect<void, IssueTrackerError>;
135 +
136 + /**
137 + * Rewrites the present fields. Only called with a field the tracker declared it can write
138 + * (`edit` for title and body, `labels`, `assignees`), and never with all of them absent.
139 + */
140 + readonly update?: (
141 + input: IssueTarget & {
142 + readonly title?: string | undefined;
143 + readonly body?: string | undefined;
144 + readonly labels?: ReadonlyArray<string> | undefined;
145 + readonly assignees?: ReadonlyArray<string> | undefined;
146 + },
147 + ) => Effect.Effect<void, IssueTrackerError>;
148 +
149 + /** Only called with a state name from `capabilities.states`. */
150 + readonly setState?: (
151 + input: IssueTarget & {
152 + readonly state: string;
153 + readonly closeReason?: string | undefined;
154 + },
155 + ) => Effect.Effect<void, IssueTrackerError>;
156 +
157 + /**
158 + * Adds a reaction or takes it back. `subjectId` is a comment id as the detail carried it;
159 + * absent means the issue itself. Only called when `capabilities.reactions` is true.
160 + */
161 + readonly setReaction?: (
162 + input: IssueTarget & {
163 + readonly subjectId?: string | undefined;
164 + readonly content: IssueReactionContent;
165 + readonly reacted: boolean;
166 + },
167 + ) => Effect.Effect<void, IssueTrackerError>;
168 +
169 + /** Only called when `capabilities.templates` is true. */
170 + readonly listTemplates?: (
171 + input: IssueScopeTarget,
172 + ) => Effect.Effect<IssueTemplateList, IssueTrackerError>;
173 +
174 + /** Only called when `capabilities.labels` or `capabilities.assignees` is true. */
175 + readonly listCandidates?: (
176 + input: IssueScopeTarget,
177 + ) => Effect.Effect<IssueCandidates, IssueTrackerError>;
178 +}
packages/source-control-core/src/server/driver.ts
+3
@@ -15,6 +15,7 @@ import type * as Scope from "effect/Scope";
15 import type { SourceControlDefinition } from "../shared/definition.ts";
16
17 import type { SourceControlProviderDiscoverySpec } from "./discovery.ts";
18 +import type { IssueTrackerApi } from "./IssueTracker.ts";
19 import type { PullRequestProviderApi } from "./PullRequestProvider.ts";
20 import type * as SourceControlHost from "./SourceControlHost.ts";
21 import type * as SourceControlProvider from "./SourceControlProvider.ts";
@@ -53,6 +54,8 @@ export interface SourceControlDriverInstance {
54 readonly discovery: SourceControlProviderDiscoverySpec;
55 /** Null for a host whose pull requests this build cannot read. */
56 readonly pullRequests: PullRequestProviderApi | null;
57 + /** Absent for a host whose issues this build cannot read. */
58 + readonly issues?: IssueTrackerApi;
59 /**
60 * Fetches media the definition's `mediaUrl` claimed, with the credential the host serves it
61 * to. Null when the fetch went nowhere a response could come from, such as a redirect loop.
packages/source-control-core/src/shared/definition.ts
+19 -6
@@ -342,6 +342,11 @@ export interface SourceControlDefinition {
342 * path, `owner/name`.
343 */
344 readonly repositorySelector?: (identity: RepositorySelectorIdentity) => string | null;
345 + /**
346 + * The container the project's issues live in, where that is not its repository: Azure DevOps
347 + * keeps work items per project. Null when the repository cannot be placed.
348 + */
349 + readonly issueScope?: (identity: RepositorySelectorIdentity) => string | null;
350 /**
351 * The key of a remote's lower case `host/path`, `.git` suffix kept, for a host that spells it
352 * apart from `normalizeGitRemoteUrl`: over SSH and the web, or with `.git` as part of the name.
@@ -661,6 +666,8 @@ export interface SourceControlDefinitionRegistry {
666 readonly repositorySelector: (
667 identity: RepositorySelectorIdentity | null | undefined,
668 ) => string | null;
669 + /** Where the project's issues live: the host's `issueScope`, else its repository. */
670 + readonly issueScope: (identity: RepositorySelectorIdentity | null | undefined) => string | null;
671 readonly changeRequestHost: <const Kind extends string | undefined>(
672 identity: ChangeRequestHostIdentity,
673 kind: Kind,
@@ -726,6 +733,10 @@ export function makeSourceControlDefinitionRegistry(
733 };
734 const remoteOwner = (remote: GitRemoteHost) =>
735 recognitionOrder.find((definition) => definition.recognizeRemote(remote) !== null);
736 + const repositorySelector = (identity: RepositorySelectorIdentity | null | undefined) =>
737 + identity?.provider === undefined
738 + ? defaultRepositorySelector(identity)
739 + : (byKind.get(identity.provider)?.repositorySelector ?? defaultRepositorySelector)(identity);
740 const parseChangeRequestUrl = (value: string): ParsedChangeRequest | null => {
741 const url = httpUrl(value);
742 if (url === null) return null;
@@ -826,12 +837,14 @@ export function makeSourceControlDefinitionRegistry(
837 },
838 canonicalRepositoryKey: (key) => repositoryKeyOwner(key)?.canonical ?? canonicalKeyPath(key),
839 findByRepositoryKey: (key) => repositoryKeyOwner(key)?.definition,
829 - repositorySelector: (identity) =>
830 - identity?.provider === undefined
831 - ? defaultRepositorySelector(identity)
832 - : (byKind.get(identity.provider)?.repositorySelector ?? defaultRepositorySelector)(
833 - identity,
834 - ),
840 + repositorySelector,
841 + issueScope: (identity) => {
842 + const issueScope =
843 + identity?.provider === undefined ? undefined : byKind.get(identity.provider)?.issueScope;
844 + return issueScope === undefined || identity == null
845 + ? repositorySelector(identity)
846 + : issueScope(identity);
847 + },
848 changeRequestHost: (identity, kind) =>
849 (kind === undefined ? undefined : byKind.get(kind)?.changeRequestHost?.(identity)) ??
850 projectChangeRequestHost(identity, kind),
packages/source-control-github/package.json
+2 -1
@@ -23,7 +23,8 @@
23 "@t3tools/provider-core": "workspace:*",
24 "@t3tools/shared": "workspace:*",
25 "@t3tools/source-control-core": "workspace:*",
26 - "effect": "catalog:"
26 + "effect": "catalog:",
27 + "yaml": "catalog:"
28 },
29 "devDependencies": {
30 "@effect/graphql-generator": "catalog:",
packages/source-control-github/schema/github.graphql.ts
+29
@@ -95,6 +95,17 @@ export type FileViewedState = typeof FileViewedState.Type
95 export const IssueState = Schema.Literals(["CLOSED", "OPEN"])
96 export type IssueState = typeof IssueState.Type
97
98 +/**
99 + * The possible state reasons of an issue.
100 + *
101 + * - `COMPLETED`: An issue that has been closed as completed
102 + * - `DUPLICATE`: An issue that has been closed as a duplicate.
103 + * - `NOT_PLANNED`: An issue that has been closed as not planned
104 + * - `REOPENED`: An issue that has been reopened
105 + */
106 +export const IssueStateReason = Schema.Literals(["COMPLETED", "DUPLICATE", "NOT_PLANNED", "REOPENED"])
107 +export type IssueStateReason = typeof IssueStateReason.Type
108 +
109 /**
110 * Detailed status information about a pull request merge.
111 *
@@ -298,10 +309,26 @@ export interface UpdateRefsInput extends Schema.Struct.Type<typeof UpdateRefsInp
309 export declare namespace Typename {
310 /** Every possible `__typename` of interface `Actor`. */
311 export type Actor = "Bot" | "EnterpriseUserAccount" | "Mannequin" | "Organization" | "User"
312 + /** Every possible `__typename` of union `Assignee`. */
313 + export type Assignee = "Bot" | "Mannequin" | "Organization" | "User"
314 /** Every possible `__typename` of interface `GitObject`. */
315 export type GitObject = "Blob" | "Commit" | "Tag" | "Tree"
316 /** Every possible `__typename` of union `IssueOrPullRequest`. */
317 export type IssueOrPullRequest = "Issue" | "PullRequest"
318 + /** Every possible `__typename` of union `IssueTimelineItems`. */
319 + export type IssueTimelineItems =
320 + | "AddedToProjectEvent" | "AddedToProjectV2Event" | "AssignedEvent" | "BlockedByAddedEvent"
321 + | "BlockedByRemovedEvent" | "BlockingAddedEvent" | "BlockingRemovedEvent" | "ClosedEvent" | "CommentDeletedEvent"
322 + | "ConnectedEvent" | "ConvertedFromDraftEvent" | "ConvertedNoteToIssueEvent" | "ConvertedToDiscussionEvent"
323 + | "CrossReferencedEvent" | "DemilestonedEvent" | "DisconnectedEvent" | "IssueComment" | "IssueCommentPinnedEvent"
324 + | "IssueCommentUnpinnedEvent" | "IssueFieldAddedEvent" | "IssueFieldChangedEvent" | "IssueFieldRemovedEvent"
325 + | "IssueTypeAddedEvent" | "IssueTypeChangedEvent" | "IssueTypeRemovedEvent" | "LabeledEvent" | "LockedEvent"
326 + | "MarkedAsDuplicateEvent" | "MentionedEvent" | "MilestonedEvent" | "MovedColumnsInProjectEvent"
327 + | "ParentIssueAddedEvent" | "ParentIssueRemovedEvent" | "PinnedEvent" | "ProjectV2ItemStatusChangedEvent"
328 + | "ReferencedEvent" | "RemovedFromProjectEvent" | "RemovedFromProjectV2Event" | "RenamedTitleEvent"
329 + | "ReopenedEvent" | "SubIssueAddedEvent" | "SubIssueRemovedEvent" | "SubscribedEvent" | "TransferredEvent"
330 + | "UnassignedEvent" | "UnlabeledEvent" | "UnlockedEvent" | "UnmarkedAsDuplicateEvent" | "UnpinnedEvent"
331 + | "UnsubscribedEvent" | "UserBlockedEvent"
332 /** Every possible `__typename` of interface `Node`. */
333 export type Node =
334 | "AddedToMergeQueueEvent" | "AddedToProjectEvent" | "AddedToProjectV2Event" | "AddedToStackEvent" | "App"
@@ -403,6 +430,8 @@ export declare namespace Typename {
430 | "PullRequestReview" | "PullRequestReviewComment" | "Release"
431 /** Every possible `__typename` of union `Reactor`. */
432 export type Reactor = "Bot" | "Mannequin" | "Organization" | "User"
433 + /** Every possible `__typename` of union `ReferencedSubject`. */
434 + export type ReferencedSubject = "Issue" | "PullRequest"
435 /** Every possible `__typename` of interface `RepositoryOwner`. */
436 export type RepositoryOwner = "Organization" | "User"
437 /** Every possible `__typename` of union `RequestedReviewer`. */
packages/source-control-github/src/server/GitHubIssueTracker.test.ts new
+553
@@ -0,0 +1,553 @@
1 +import { describe, expect, it } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +
5 +import * as Redacted from "effect/Redacted";
6 +import * as Schema from "effect/Schema";
7 +import { HttpClient, HttpClientResponse } from "effect/http";
8 +import { IssueTemplateList } from "@t3tools/contracts";
9 +import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
10 +import * as GitHubCredentials from "./GitHubCredentials.ts";
11 +import * as GitHubRest from "./GitHubRest.ts";
12 +import * as GitHubQuota from "./GitHubQuota.ts";
13 +import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
14 +import * as GitHubIssueTracker from "./GitHubIssueTracker.ts";
15 +
16 +const DETAIL_RESPONSE = JSON.stringify({
17 + data: {
18 + viewer: { login: "julius" },
19 + repository: {
20 + viewerPermission: "TRIAGE",
21 + issue: {
22 + __typename: "Issue",
23 + number: 42,
24 + title: "Composer loses focus",
25 + url: "https://github.com/acme/web/issues/42",
26 + author: {
27 + __typename: "User",
28 + login: "octocat",
29 + avatarUrl: "https://avatars/octocat",
30 + name: "Octo Cat",
31 + },
32 + state: "CLOSED",
33 + stateReason: "DUPLICATE",
34 + createdAt: "2026-07-01T00:00:00Z",
35 + updatedAt: "2026-07-03T00:00:00Z",
36 + closedAt: "2026-07-03T00:00:00Z",
37 + comments: {
38 + totalCount: 3,
39 + pageInfo: { hasPreviousPage: true, startCursor: "Y3Vyc29y" },
40 + nodes: [
41 + {
42 + __typename: "IssueComment",
43 + id: "IC_1",
44 + author: { __typename: "User", login: "julius", avatarUrl: "https://avatars/julius" },
45 + body: "Repro attached.",
46 + createdAt: "2026-07-02T00:00:00Z",
47 + url: "https://github.com/acme/web/issues/42#issuecomment-1",
48 + reactionGroups: [
49 + {
50 + content: "THUMBS_UP",
51 + viewerHasReacted: true,
52 + reactors: {
53 + totalCount: 2,
54 + nodes: [
55 + { __typename: "User", login: "julius" },
56 + { __typename: "User", login: "theo" },
57 + ],
58 + },
59 + },
60 + {
61 + content: "EYES",
62 + viewerHasReacted: false,
63 + reactors: { totalCount: 0, nodes: [] },
64 + },
65 + ],
66 + },
67 + ],
68 + },
69 + assignees: {
70 + pageInfo: { hasNextPage: false, endCursor: null },
71 + nodes: [{ login: "theo", name: null, avatarUrl: "https://avatars/julius" }],
72 + },
73 + labels: {
74 + pageInfo: { hasNextPage: true, endCursor: "labels-next" },
75 + nodes: [{ name: "bug", color: "d73a4a" }, null],
76 + },
77 + body: "Typing in the composer drops focus after a paste.",
78 + viewerCanUpdate: false,
79 + viewerCanClose: false,
80 + viewerCanReopen: true,
81 + reactionGroups: [],
82 + closedByPullRequestsReferences: {
83 + nodes: [
84 + {
85 + number: 50,
86 + title: "fix(web): keep composer focus",
87 + url: "https://github.com/acme/web/pull/50",
88 + state: "MERGED",
89 + isDraft: false,
90 + repository: { nameWithOwner: "acme/web" },
91 + },
92 + ],
93 + },
94 + timelineItems: {
95 + nodes: [
96 + {
97 + __typename: "LabeledEvent",
98 + id: "LE_1",
99 + createdAt: "2026-07-01T01:00:00Z",
100 + actor: { __typename: "User", login: "theo", avatarUrl: "https://avatars/theo" },
101 + label: { name: "bug" },
102 + },
103 + {
104 + __typename: "CrossReferencedEvent",
105 + id: "CRE_1",
106 + createdAt: "2026-07-02T01:00:00Z",
107 + actor: { __typename: "User", login: "julius", avatarUrl: "https://avatars/julius" },
108 + source: {
109 + __typename: "PullRequest",
110 + number: 50,
111 + title: "fix(web): keep composer focus",
112 + url: "https://github.com/acme/web/pull/50",
113 + state: "MERGED",
114 + isDraft: false,
115 + repository: { nameWithOwner: "acme/web" },
116 + },
117 + },
118 + { __typename: "MentionedEvent", id: "ME_1", createdAt: "2026-07-02T02:00:00Z" },
119 + {
120 + __typename: "ClosedEvent",
121 + id: "CE_1",
122 + createdAt: "2026-07-03T00:00:00Z",
123 + actor: null,
124 + },
125 + ],
126 + },
127 + },
128 + },
129 + },
130 +});
131 +
132 +const decodeVariables = Schema.decodeUnknownSync(
133 + Schema.fromJsonString(
134 + Schema.Struct({
135 + query: Schema.String,
136 + variables: Schema.Record(Schema.String, Schema.Unknown),
137 + }),
138 + ),
139 +);
140 +
141 +function transport(httpClient: HttpClient.HttpClient) {
142 + return GitHubRest.layer.pipe(
143 + Layer.provideMerge(
144 + Layer.mergeAll(
145 + GitHubQuota.layer,
146 + SourceControlRateLimit.layer,
147 + Layer.mock(GitHubCredentials.GitHubCredentials)({
148 + saved: () => Effect.succeedNone,
149 + get: (host) =>
150 + Effect.succeed({
151 + host,
152 + token: Redacted.make("test-token"),
153 + source: "gh" as const,
154 + fingerprint: "test",
155 + }),
156 + }),
157 + Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
158 + enabled: false,
159 + token: () => Effect.succeedNone,
160 + invalidate: () => Effect.void,
161 + }),
162 + Layer.succeed(HttpClient.HttpClient, httpClient),
163 + ),
164 + ),
165 + );
166 +}
167 +
168 +function tracker(onRequest: (variables: unknown) => void, templateRepository?: unknown) {
169 + return GitHubIssueTracker.make.pipe(
170 + Effect.provide(
171 + transport(
172 + HttpClient.make((request) => {
173 + if (request.body._tag !== "Uint8Array")
174 + return Effect.die("Expected a GraphQL JSON request.");
175 + const { variables } = decodeVariables(new TextDecoder().decode(request.body.body));
176 + onRequest(variables);
177 + const body =
178 + templateRepository !== undefined
179 + ? JSON.stringify({ data: { repository: templateRepository } })
180 + : "labelsCursor" in variables
181 + ? JSON.stringify({
182 + data: {
183 + repository: {
184 + issue: {
185 + labels: {
186 + pageInfo: { hasNextPage: false, endCursor: null },
187 + nodes: [{ name: "needs repro", color: "ffffff" }],
188 + },
189 + assignees: {
190 + pageInfo: { hasNextPage: false, endCursor: null },
191 + nodes: [],
192 + },
193 + },
194 + },
195 + },
196 + })
197 + : DETAIL_RESPONSE;
198 + return Effect.succeed(
199 + HttpClientResponse.fromWeb(
200 + request,
201 + new Response(body, {
202 + headers: { "content-type": "application/json" },
203 + }),
204 + ),
205 + );
206 + }),
207 + ),
208 + ),
209 + );
210 +}
211 +
212 +const encodeTemplateList = Schema.encodeSync(IssueTemplateList);
213 +
214 +const decodeBody = Schema.decodeUnknownSync(
215 + Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
216 +);
217 +
218 +describe("GitHubIssueTracker", () => {
219 + it.effect("writes an issue lifecycle without mutating pull requests or foreign comments", () =>
220 + Effect.gen(function* () {
221 + const writes: unknown[] = [];
222 + let issueState: { state: string; stateReason: string | null } = {
223 + state: "OPEN",
224 + stateReason: null,
225 + };
226 + const http = HttpClient.make((request) => {
227 + if (request.body._tag !== "Uint8Array") return Effect.die("Expected a JSON request.");
228 + const text = new TextDecoder().decode(request.body.body);
229 + let response: unknown = {};
230 + if (request.url === "https://api.github.com/graphql") {
231 + const { query, variables } = decodeVariables(text);
232 + expect(request.method).toBe("POST");
233 + const operation = query.match(/(?:query|mutation)\s+(\w+)/)?.[1];
234 + if (operation === "IssueNodeId" || operation === "IssueCommentScope") {
235 + expect(variables).toMatchObject({ owner: "acme", name: "web" });
236 + response = {
237 + data: {
238 + repository: {
239 + issue: variables["number"] === 42 ? { id: "I_42", ...issueState } : null,
240 + },
241 + ...(operation === "IssueCommentScope"
242 + ? { node: { __typename: "IssueComment", issue: { id: "I_other" } } }
243 + : {}),
244 + },
245 + };
246 + } else {
247 + expect(["AddReaction", "RemoveReaction"]).toContain(operation);
248 + expect(variables).toEqual({ subjectId: "I_42", content: "THUMBS_UP" });
249 + writes.push(operation);
250 + response = {
251 + data: {
252 + [operation === "AddReaction" ? "addReaction" : "removeReaction"]: {
253 + reaction: { content: "THUMBS_UP" },
254 + },
255 + },
256 + };
257 + }
258 + } else {
259 + const body = decodeBody(text);
260 + writes.push([request.method, request.url, body]);
261 + if (typeof body["state"] === "string") {
262 + issueState = {
263 + state: body["state"].toUpperCase(),
264 + stateReason:
265 + typeof body["state_reason"] === "string"
266 + ? body["state_reason"].toUpperCase()
267 + : null,
268 + };
269 + }
270 + if (request.url.endsWith("/issues")) {
271 + response = { number: 42, html_url: "https://github.com/acme/web/issues/42" };
272 + }
273 + }
274 + return Effect.succeed(
275 + HttpClientResponse.fromWeb(
276 + request,
277 + new Response(JSON.stringify(response), {
278 + headers: { "content-type": "application/json" },
279 + }),
280 + ),
281 + );
282 + });
283 + const api = yield* GitHubIssueTracker.make.pipe(Effect.provide(transport(http)));
284 + const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" };
285 + expect(
286 + yield* api.create({
287 + ...target,
288 + title: "Fixture",
289 + body: "Body",
290 + labels: ["bug"],
291 + assignees: ["octocat"],
292 + }),
293 + ).toEqual({
294 + key: "42",
295 + displayKey: "#42",
296 + url: "https://github.com/acme/web/issues/42",
297 + });
298 + yield* api.comment({ ...target, body: "Comment" });
299 + yield* api.update({ ...target, title: "Updated", body: "Edited", labels: [], assignees: [] });
300 + yield* api.setState({ ...target, state: "closed", closeReason: "not-planned" });
301 + // GitHub ignores a new reason on a closed issue, so it is refused instead of sent.
302 + expect(
303 + yield* api
304 + .setState({ ...target, state: "closed", closeReason: "completed" })
305 + .pipe(Effect.result),
306 + ).toMatchObject({ _tag: "Failure", failure: { operation: "setState", reason: "failed" } });
307 + yield* api.setState({ ...target, state: "open" });
308 + yield* api.setReaction({ ...target, content: "thumbs-up", reacted: true });
309 + yield* api.setReaction({ ...target, content: "thumbs-up", reacted: false });
310 +
311 + const pullRequest = { ...target, key: "50" };
312 + expect(
313 + yield* api.update({ ...pullRequest, title: "Do not edit" }).pipe(Effect.result),
314 + ).toMatchObject({ _tag: "Failure", failure: { operation: "update", reason: "not-found" } });
315 + expect(
316 + yield* api.setState({ ...pullRequest, state: "closed" }).pipe(Effect.result),
317 + ).toMatchObject({
318 + _tag: "Failure",
319 + failure: { operation: "setState", reason: "not-found" },
320 + });
321 + expect(
322 + yield* api.comment({ ...pullRequest, body: "Do not comment" }).pipe(Effect.result),
323 + ).toMatchObject({ _tag: "Failure", failure: { operation: "comment", reason: "not-found" } });
324 + expect(
325 + yield* Effect.flip(
326 + api.setReaction({
327 + ...target,
328 + subjectId: "IC_other",
329 + content: "thumbs-up",
330 + reacted: true,
331 + }),
332 + ),
333 + ).toMatchObject({ operation: "setReaction", reason: "failed" });
334 +
335 + expect(writes).toEqual([
336 + [
337 + "POST",
338 + "https://api.github.com/repos/acme/web/issues",
339 + { title: "Fixture", body: "Body", labels: ["bug"], assignees: ["octocat"] },
340 + ],
341 + ["POST", "https://api.github.com/repos/acme/web/issues/42/comments", { body: "Comment" }],
342 + [
343 + "PATCH",
344 + "https://api.github.com/repos/acme/web/issues/42",
345 + { title: "Updated", body: "Edited", labels: [], assignees: [] },
346 + ],
347 + [
348 + "PATCH",
349 + "https://api.github.com/repos/acme/web/issues/42",
350 + { state: "closed", state_reason: "not_planned" },
351 + ],
352 + ["PATCH", "https://api.github.com/repos/acme/web/issues/42", { state: "open" }],
353 + "AddReaction",
354 + "RemoveReaction",
355 + ]);
356 + }),
357 + );
358 +
359 + it.effect("offers YAML issue forms when blank issues are disabled", () =>
360 + Effect.gen(function* () {
361 + const form = {
362 + __typename: "Blob",
363 + isTruncated: false,
364 + text: `name: Bug report
365 +description: Report broken behavior.
366 +title: "[Bug]: "
367 +labels: [bug, needs-triage]
368 +assignees: "octocat, theo"
369 +body:
370 + - type: markdown
371 + attributes:
372 + value: Search existing issues first.
373 + - type: checkboxes
374 + attributes:
375 + label: Before submitting
376 + options:
377 + - label: I searched existing issues.
378 + required: true
379 + - type: dropdown
380 + attributes:
381 + label: Area
382 + description: Which part is affected?
383 + options: [Web, Server]
384 + default: 1
385 + validations:
386 + required: true
387 + - type: textarea
388 + attributes:
389 + label: Steps to reproduce
390 + placeholder: Start the app.
391 + - type: input
392 + attributes:
393 + label: Version
394 + value: main
395 + - type: upload
396 + attributes:
397 + label: Supporting files
398 + description: Redact secrets before uploading.
399 +`,
400 + };
401 + const config = {
402 + __typename: "Blob",
403 + isTruncated: false,
404 + text: '"blank_issues_enabled": false # use a template',
405 + };
406 + const repository = {
407 + issueTemplates: [],
408 + templateDirectory: {
409 + __typename: "Tree",
410 + entries: [
411 + { name: "config.yml", object: config },
412 + { name: "bug_report.yml", object: form },
413 + {
414 + name: "empty_name.yml",
415 + object: { ...form, text: 'name: ""\ndescription: Empty name\nbody: []' },
416 + },
417 + {
418 + name: "blank_name.yml",
419 + object: { ...form, text: 'name: " "\ndescription: Blank name\nbody: []' },
420 + },
421 + {
422 + name: "invalid.yml",
423 + object: { ...form, text: "name: Missing required metadata\nbody: []" },
424 + },
425 + ],
426 + },
427 + };
428 + const api = yield* tracker(() => {}, repository);
429 + const input = { cwd: "/w", host: "github.com", scope: "acme/web" };
430 + const result = yield* api.listTemplates!(input);
431 + expect(encodeTemplateList(result)).toEqual(result);
432 + expect(result.blankIssuesEnabled).toBe(false);
433 + expect(result.templates).toHaveLength(1);
434 + expect(result.templates[0]).toMatchObject({
435 + key: "bug_report.yml",
436 + name: "Bug report",
437 + about: "Report broken behavior.",
438 + title: "[Bug]: ",
439 + labels: ["bug", "needs-triage"],
440 + assignees: ["octocat", "theo"],
441 + });
442 + expect(result.templates[0]?.body).toBe(`Search existing issues first.
443 +
444 +### Before submitting
445 +
446 +- [ ] I searched existing issues. (required)
447 +
448 +### Area
449 +
450 +Which part is affected?
451 +
452 +Required.
453 +
454 +Choose one:
455 +
456 +- Web
457 +- Server (default)
458 +
459 +### Steps to reproduce
460 +
461 +Example:
462 +> Start the app.
463 +
464 +### Version
465 +
466 +main
467 +
468 +### Supporting files
469 +
470 +Redact secrets before uploading.`);
471 + config.isTruncated = true;
472 + expect(yield* Effect.flip(api.listTemplates!(input))).toMatchObject({
473 + reason: "failed",
474 + detail: "GitHub returned incomplete issue template contents.",
475 + });
476 + }),
477 + );
478 +
479 + it.effect("maps a detail read to the neutral issue shape", () =>
480 + Effect.gen(function* () {
481 + const seen: unknown[] = [];
482 + const api = yield* tracker((variables) => {
483 + seen.push(variables);
484 + });
485 + const issue = yield* api.getIssue({
486 + cwd: "/w",
487 + host: "github.com",
488 + scope: "acme/web",
489 + key: "42",
490 + });
491 + expect(seen).toEqual([
492 + { owner: "acme", name: "web", number: 42 },
493 + {
494 + owner: "acme",
495 + name: "web",
496 + number: 42,
497 + labelsCursor: "labels-next",
498 + assigneesCursor: null,
499 + },
500 + ]);
501 + expect(issue).toMatchObject({
502 + key: "42",
503 + displayKey: "#42",
504 + title: "Composer loses focus",
505 + body: "Typing in the composer drops focus after a paste.",
506 + state: { category: "closed", name: "closed", closeReason: "duplicate" },
507 + author: {
508 + login: "octocat",
509 + name: "Octo Cat",
510 + avatarUrl: "https://avatars/octocat",
511 + },
512 + assignees: [{ login: "theo" }],
513 + labels: [
514 + { name: "bug", color: "d73a4a" },
515 + { name: "needs repro", color: "ffffff" },
516 + ],
517 + commentCount: 3,
518 + viewer: "julius",
519 + // Triage may label, assign, close and reopen; `viewerCanUpdate: false` withholds edits.
520 + viewerPermissions: {
521 + setState: true,
522 + edit: false,
523 + labels: true,
524 + assignees: true,
525 + comment: true,
526 + },
527 + commentsCursor: "Y3Vyc29y",
528 + });
529 + // The viewer is left out of `actors` and shown as "You"; an empty group is dropped.
530 + expect(issue.comments[0]?.reactions).toEqual([
531 + { content: "thumbs-up", count: 2, actors: ["theo"], viewerHasReacted: true },
532 + ]);
533 + // The closing reference wins over the cross-reference sighting of the same pull request.
534 + expect(issue.linkedPullRequests).toEqual([
535 + {
536 + repository: "acme/web",
537 + number: 50,
538 + title: "fix(web): keep composer focus",
539 + url: "https://github.com/acme/web/pull/50",
540 + state: "merged",
541 + isDraft: false,
542 + closesIssue: true,
543 + },
544 + ]);
545 + // An event kind this page has no vocabulary for is dropped rather than guessed at.
546 + expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
547 + ["labeled", "bug"],
548 + ["referenced", "acme/web#50"],
549 + ["closed", null],
550 + ]);
551 + }),
552 + );
553 +});
packages/source-control-github/src/server/GitHubIssueTracker.ts new
+442
@@ -0,0 +1,442 @@
1 +import * as Effect from "effect/Effect";
2 +import * as Result from "effect/Result";
3 +import { GraphQLClient, GraphQLClientError, GraphQLGroup } from "effect/graphql";
4 +import {
5 + IssueTrackerKind,
6 + type IssueCapabilities,
7 + type IssueInvolvement,
8 +} from "@t3tools/contracts";
9 +import {
10 + IssueTrackerError,
11 + type IssueTrackerApi,
12 +} from "@t3tools/source-control-core/server/IssueTracker";
13 +
14 +import * as GitHubRest from "./GitHubRest.ts";
15 +import { readIssueTemplates } from "./gitHubIssueTemplates.ts";
16 +import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
17 +import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
18 +import { IssuesGraphQLGroup } from "./issues.graphql.ts";
19 +import { AddReaction, RemoveReaction } from "./pullRequestMutations.graphql.ts";
20 +import { gitHubReactionContent } from "./gitHubPullRequestJson.ts";
21 +import {
22 + decodeCreatedIssueJson,
23 + toIssueCandidates,
24 + toIssueComments,
25 + toIssueDetail,
26 + toIssueSearch,
27 +} from "./gitHubIssueJson.ts";
28 +
29 +const KIND = IssueTrackerKind.make("github");
30 +
31 +const CAPABILITIES: IssueCapabilities = {
32 + create: true,
33 + edit: true,
34 + comment: true,
35 + labels: true,
36 + assignees: true,
37 + reactions: true,
38 + templates: true,
39 + linkedPullRequests: true,
40 + events: true,
41 + search: true,
42 + states: [
43 + { category: "open", name: "open" },
44 + { category: "closed", name: "closed" },
45 + ],
46 + closeReasons: ["completed", "not-planned"],
47 +};
48 +
49 +const REPOSITORY = /^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+$/;
50 +
51 +function searchTerms(query: string): ReadonlyArray<string> {
52 + return query
53 + .split(/\s+/)
54 + .filter((word) => word.length > 0)
55 + .map((word) => `"${word.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`);
56 +}
57 +
58 +const INVOLVEMENT_QUALIFIER: Record<IssueInvolvement, string | null> = {
59 + all: null,
60 + assigned: "assignee",
61 + authored: "author",
62 + mentioned: "mentions",
63 +};
64 +
65 +function searchQuery(input: {
66 + readonly scope: string;
67 + readonly state: "all" | "open" | "closed";
68 + readonly involvement: IssueInvolvement;
69 + readonly viewer: string;
70 + readonly query?: string | undefined;
71 +}): string {
72 + const qualifier = INVOLVEMENT_QUALIFIER[input.involvement];
73 + return [
74 + "is:issue",
75 + `repo:${input.scope.trim()}`,
76 + ...(input.state === "all" ? [] : [`is:${input.state}`]),
77 + ...(qualifier === null ? [] : [`${qualifier}:${input.viewer}`]),
78 + "sort:updated-desc",
79 + ...searchTerms(input.query ?? ""),
80 + ].join(" ");
81 +}
82 +
83 +const CLOSE_REASON: Record<string, "completed" | "not_planned"> = {
84 + completed: "completed",
85 + "not-planned": "not_planned",
86 +};
87 +
88 +function reasonFor(
89 + error: GitHubRequestPolicy.GitHubApiError | GraphQLClientError.GraphQLClientError,
90 +): IssueTrackerError["reason"] {
91 + switch (error._tag) {
92 + case "GitHubCliMissingError":
93 + return "missing-tool";
94 + case "GitHubNotSignedInError":
95 + case "GitHubHostDisabledError":
96 + case "GitHubApiAuthenticationError":
97 + return "unauthenticated";
98 + case "GitHubApiRateLimitError":
99 + case "SourceControlRateLimitPausedError":
100 + return "rate-limited";
101 + case "GitHubApiNotFoundError":
102 + return "not-found";
103 + default:
104 + return "failed";
105 + }
106 +}
107 +
108 +const FAILURE_DETAIL: Record<IssueTrackerError["reason"], string> = {
109 + "missing-tool": "GitHub CLI is not installed.",
110 + unauthenticated: "GitHub authentication is unavailable. Sign in and retry.",
111 + "rate-limited": "GitHub API rate limit exceeded.",
112 + "not-found": "GitHub could not find the requested issue.",
113 + failed: "The GitHub issue request failed.",
114 +};
115 +
116 +const group = GraphQLGroup.merge(
117 + IssuesGraphQLGroup,
118 + GraphQLGroup.make(AddReaction, RemoveReaction),
119 +).middleware(GitHubGraphQlClient.GitHubGraphQlAuth);
120 +
121 +export const make = Effect.gen(function* () {
122 + const api = yield* GitHubRest.GitHubRest;
123 + const client = yield* GraphQLClient.make(group).pipe(Effect.provide(GitHubGraphQlClient.layer));
124 +
125 + const fail =
126 + (operation: string) =>
127 + (error: GitHubRequestPolicy.GitHubApiError | GraphQLClientError.GraphQLClientError) =>
128 + new IssueTrackerError({
129 + tracker: KIND,
130 + operation,
131 + reason: reasonFor(error),
132 + detail: GraphQLClientError.isGraphQLClientError(error)
133 + ? `GitHub returned an unreadable ${operation} response.`
134 + : FAILURE_DETAIL[reasonFor(error)],
135 + ...("retryAt" in error && error.retryAt !== undefined ? { retryAt: error.retryAt } : {}),
136 + cause: error,
137 + });
138 +
139 + const invalid = (operation: string, detail: string, reason: "failed" | "not-found" = "failed") =>
140 + new IssueTrackerError({ tracker: KIND, operation, reason, detail });
141 +
142 + const notFound = (operation: string) =>
143 + invalid(operation, "GitHub could not find the requested issue.", "not-found");
144 +
145 + const repository = Effect.fn("GitHubIssueTracker.repository")(function* (
146 + scope: string,
147 + operation: string,
148 + ) {
149 + if (!REPOSITORY.test(scope) || scope.endsWith("/.") || scope.endsWith("/..")) {
150 + return yield* invalid(operation, "A repository was named that GitHub cannot address.");
151 + }
152 + const [owner = "", name = ""] = scope.split("/");
153 + return { owner, name };
154 + });
155 +
156 + const issue = Effect.fn("GitHubIssueTracker.issue")(function* (
157 + input: { readonly scope: string; readonly key: string },
158 + operation: string,
159 + ) {
160 + const repo = yield* repository(input.scope, operation);
161 + const number = Number(input.key);
162 + if (!/^[1-9]\d*$/.test(input.key) || !Number.isSafeInteger(number) || number > 2_147_483_647) {
163 + return yield* notFound(operation);
164 + }
165 + return { ...repo, number, path: `repos/${repo.owner}/${repo.name}/issues/${number}` };
166 + });
167 +
168 + const graphql =
169 + (host: string, operation: string) =>
170 + <A, E extends GitHubRequestPolicy.GitHubApiError | GraphQLClientError.GraphQLClientError, R>(
171 + effect: Effect.Effect<A, E, R>,
172 + ) =>
173 + effect.pipe(GitHubGraphQlClient.call({ host, operation }), Effect.mapError(fail(operation)));
174 +
175 + const verifiedIssue = Effect.fn("GitHubIssueTracker.verifiedIssue")(function* (
176 + input: { readonly host: string; readonly scope: string; readonly key: string },
177 + operation: string,
178 + ) {
179 + const target = yield* issue(input, operation);
180 + const { owner, name, number } = target;
181 + // REST issue endpoints also accept pull requests; resolve an Issue before writing.
182 + const result = yield* client
183 + .IssueNodeId({ owner, name, number })
184 + .pipe(graphql(input.host, operation));
185 + const found = result.repository?.issue;
186 + if (found == null) return yield* notFound(operation);
187 + return { ...target, id: found.id, state: found.state, stateReason: found.stateReason };
188 + });
189 +
190 + const patchIssue = (
191 + input: { readonly host: string; readonly scope: string; readonly key: string },
192 + operation: string,
193 + body: Record<string, unknown>,
194 + ) =>
195 + verifiedIssue(input, operation).pipe(
196 + Effect.flatMap(({ path }) =>
197 + api
198 + .rest({ host: input.host, operation, method: "PATCH", path, body })
199 + .pipe(Effect.asVoid, Effect.mapError(fail(operation))),
200 + ),
201 + );
202 +
203 + return {
204 + kind: KIND,
205 + capabilities: CAPABILITIES,
206 +
207 + getViewer: (input) =>
208 + client.IssueViewer({}).pipe(
209 + graphql(input.host, "getViewer"),
210 + Effect.map(({ viewer }) => viewer.login),
211 + ),
212 +
213 + listIssues: (input) =>
214 + repository(input.scope, "listIssues").pipe(
215 + Effect.flatMap(() =>
216 + client
217 + .IssueSearch({
218 + q: searchQuery(input),
219 + cursor: input.cursor,
220 + rows: Math.min(Math.max(Math.trunc(input.limit), 1), 100),
221 + })
222 + .pipe(graphql(input.host, "listIssues"), Effect.map(toIssueSearch)),
223 + ),
224 + ),
225 +
226 + getIssue: Effect.fn("GitHubIssueTracker.getIssue")(function* (input) {
227 + const { owner, name, number } = yield* issue(input, "getIssue");
228 + const result = yield* client
229 + .IssueDetail({ owner, name, number })
230 + .pipe(graphql(input.host, "getIssue"));
231 + const detail = toIssueDetail(result);
232 + const raw = result.repository?.issue;
233 + if (detail === null || raw == null) return yield* notFound("getIssue");
234 + // Editing replaces these sets. Finish their pages before handing them to a client.
235 + let labels = raw.labels;
236 + let assignees = raw.assignees;
237 + const seen = new Set<string>();
238 + const allLabels = [...detail.labels];
239 + const allAssignees = [...detail.assignees];
240 + while (labels?.pageInfo.hasNextPage === true || assignees.pageInfo.hasNextPage) {
241 + const labelsCursor = labels?.pageInfo.hasNextPage ? labels.pageInfo.endCursor : null;
242 + const assigneesCursor = assignees.pageInfo.hasNextPage
243 + ? assignees.pageInfo.endCursor
244 + : null;
245 + const key = `${labelsCursor ?? ""} ${assigneesCursor ?? ""}`;
246 + if (
247 + (labels?.pageInfo.hasNextPage && labelsCursor === null) ||
248 + (assignees.pageInfo.hasNextPage && assigneesCursor === null) ||
249 + seen.has(key)
250 + ) {
251 + return yield* invalid(
252 + "getIssue",
253 + "GitHub did not return complete issue labels or assignees.",
254 + );
255 + }
256 + seen.add(key);
257 + const page = yield* client
258 + .IssueCollections({ owner, name, number, labelsCursor, assigneesCursor })
259 + .pipe(graphql(input.host, "getIssue"));
260 + const next = page.repository?.issue;
261 + if (next == null) return yield* notFound("getIssue");
262 + if (labels?.pageInfo.hasNextPage) {
263 + labels = next.labels;
264 + if (next.labels === null) {
265 + return yield* invalid("getIssue", "GitHub did not return complete issue labels.");
266 + }
267 + allLabels.push(
268 + ...(next.labels.nodes ?? []).flatMap((node) =>
269 + node === null ? [] : [{ name: node.name, color: node.color }],
270 + ),
271 + );
272 + }
273 + if (assignees.pageInfo.hasNextPage) {
274 + assignees = next.assignees;
275 + allAssignees.push(
276 + ...(next.assignees.nodes ?? []).flatMap((node) =>
277 + node === null
278 + ? []
279 + : [{ login: node.login, name: node.name, avatarUrl: node.avatarUrl }],
280 + ),
281 + );
282 + }
283 + }
284 + return { ...detail, labels: allLabels, assignees: allAssignees };
285 + }),
286 +
287 + getComments: (input) =>
288 + issue(input, "getComments").pipe(
289 + Effect.flatMap(({ owner, name, number }) =>
290 + client
291 + .IssueComments({ owner, name, number, cursor: input.cursor })
292 + .pipe(graphql(input.host, "getComments")),
293 + ),
294 + Effect.flatMap((result) =>
295 + result.repository?.issue == null
296 + ? Effect.fail(notFound("getComments"))
297 + : Effect.succeed(toIssueComments(result)),
298 + ),
299 + ),
300 +
301 + create: (input) =>
302 + repository(input.scope, "create").pipe(
303 + Effect.flatMap(({ owner, name }) =>
304 + api
305 + .rest({
306 + host: input.host,
307 + operation: "create",
308 + method: "POST",
309 + path: `repos/${owner}/${name}/issues`,
310 + body: {
311 + title: input.title,
312 + body: input.body,
313 + labels: input.labels,
314 + assignees: input.assignees,
315 + },
316 + })
317 + .pipe(Effect.mapError(fail("create"))),
318 + ),
319 + Effect.flatMap((response) => {
320 + const decoded = decodeCreatedIssueJson(response.body);
321 + return Result.isSuccess(decoded)
322 + ? Effect.succeed({
323 + key: String(decoded.success.number),
324 + displayKey: `#${decoded.success.number}`,
325 + url: decoded.success.url,
326 + })
327 + : Effect.fail(
328 + new IssueTrackerError({
329 + tracker: KIND,
330 + operation: "create",
331 + reason: "failed",
332 + detail: "GitHub returned an unreadable create response.",
333 + cause: decoded.failure,
334 + }),
335 + );
336 + }),
337 + ),
338 +
339 + comment: (input) =>
340 + verifiedIssue(input, "comment").pipe(
341 + Effect.flatMap(({ path }) =>
342 + api
343 + .rest({
344 + host: input.host,
345 + operation: "comment",
346 + method: "POST",
347 + path: `${path}/comments`,
348 + body: { body: input.body },
349 + })
350 + .pipe(Effect.asVoid, Effect.mapError(fail("comment"))),
351 + ),
352 + ),
353 +
354 + update: (input) =>
355 + patchIssue(input, "update", {
356 + ...(input.title === undefined ? {} : { title: input.title }),
357 + ...(input.body === undefined ? {} : { body: input.body }),
358 + ...(input.labels === undefined ? {} : { labels: input.labels }),
359 + ...(input.assignees === undefined ? {} : { assignees: input.assignees }),
360 + }),
361 +
362 + setState: Effect.fn("GitHubIssueTracker.setState")(function* (input) {
363 + const { path, state, stateReason } = yield* verifiedIssue(input, "setState");
364 + const reason =
365 + input.state === "closed" && input.closeReason !== undefined
366 + ? CLOSE_REASON[input.closeReason]
367 + : undefined;
368 + // GitHub ignores `state_reason` unless the state changes, and would answer with success.
369 + if (reason !== undefined && state === "CLOSED" && stateReason?.toLowerCase() !== reason) {
370 + return yield* invalid(
371 + "setState",
372 + "GitHub cannot change why a closed issue was closed. Reopen it, then close it again.",
373 + );
374 + }
375 + yield* api
376 + .rest({
377 + host: input.host,
378 + operation: "setState",
379 + method: "PATCH",
380 + path,
381 + body: { state: input.state, ...(reason === undefined ? {} : { state_reason: reason }) },
382 + })
383 + .pipe(Effect.mapError(fail("setState")));
384 + }),
385 +
386 + setReaction: Effect.fn("GitHubIssueTracker.setReaction")(function* (input) {
387 + let subjectId: string;
388 + if (input.subjectId === undefined) {
389 + const target = yield* verifiedIssue(input, "setReaction");
390 + subjectId = target.id;
391 + } else {
392 + const { owner, name, number } = yield* issue(input, "setReaction");
393 + // Node ids are global: prove the comment belongs to this issue before writing.
394 + const result = yield* client
395 + .IssueCommentScope({ owner, name, number, commentId: input.subjectId })
396 + .pipe(graphql(input.host, "setReaction"));
397 + const expected = result.repository?.issue?.id;
398 + if (
399 + expected === undefined ||
400 + result.node?.__typename !== "IssueComment" ||
401 + result.node.issue.id !== expected
402 + ) {
403 + return yield* invalid(
404 + "setReaction",
405 + "The comment does not belong to the selected issue.",
406 + );
407 + }
408 + subjectId = input.subjectId;
409 + }
410 + const variables = { subjectId, content: gitHubReactionContent(input.content) };
411 + yield* (
412 + input.reacted
413 + ? client.AddReaction(variables).pipe(Effect.asVoid)
414 + : client.RemoveReaction(variables).pipe(Effect.asVoid)
415 + ).pipe(graphql(input.host, "setReaction"));
416 + }),
417 +
418 + listTemplates: (input) =>
419 + repository(input.scope, "listTemplates").pipe(
420 + Effect.flatMap(({ owner, name }) =>
421 + client.IssueTemplates({ owner, name }).pipe(graphql(input.host, "listTemplates")),
422 + ),
423 + Effect.flatMap(({ repository }) =>
424 + repository === null
425 + ? Effect.fail(notFound("listTemplates"))
426 + : readIssueTemplates(repository),
427 + ),
428 + ),
429 +
430 + listCandidates: (input) =>
431 + repository(input.scope, "listCandidates").pipe(
432 + Effect.flatMap(({ owner, name }) =>
433 + client.IssueCandidates({ owner, name }).pipe(graphql(input.host, "listCandidates")),
434 + ),
435 + Effect.flatMap(({ repository }) =>
436 + repository === null
437 + ? Effect.fail(notFound("listCandidates"))
438 + : Effect.succeed(toIssueCandidates(repository)),
439 + ),
440 + ),
441 + } satisfies IssueTrackerApi;
442 +});
packages/source-control-github/src/server/driver.ts
+2
@@ -17,6 +17,7 @@ import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
17 import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
18 import * as GitHubRest from "./GitHubRest.ts";
19 import * as GitHubHttpClient from "./GitHubHttpClient.ts";
20 +import * as GitHubIssueTracker from "./GitHubIssueTracker.ts";
21 import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
22
23 // `GitHubRest.layerWithDependencies` carries the quota reserve every GitHub reader shares, so it
@@ -104,6 +105,7 @@ const makeInstance = Effect.gen(function* () {
105 sourceControl: GitHubSourceControlProvider.make,
106 discovery: GitHubSourceControlProvider.makeDiscovery,
107 pullRequests: GitHubPullRequestProvider.make,
108 + issues: GitHubIssueTracker.make,
109 fetchMedia: GitHubMediaFetch.make.pipe(
110 Effect.provideService(HttpClient.HttpClient, mediaHttpClient),
111 ),
packages/source-control-github/src/server/gitHubIssueJson.ts new
+350
@@ -0,0 +1,350 @@
1 +import * as Result from "effect/Result";
2 +import * as Schema from "effect/Schema";
3 +import { TrimmedNonEmptyString } from "@t3tools/contracts";
4 +import type {
5 + IssueActor,
6 + IssueComment,
7 + IssueEvent,
8 + IssueEventKind,
9 + IssueLabel,
10 + IssueLinkedPullRequest,
11 + IssueState,
12 + IssueTemplate,
13 + IssueViewerPermissions,
14 + PullRequestState,
15 +} from "@t3tools/contracts";
16 +import { decodeJsonResult } from "@t3tools/shared/schemaJson";
17 +import type { TrackerIssueSummary } from "@t3tools/source-control-core/server/IssueTracker";
18 +
19 +import type * as Issues from "./issues.graphql.ts";
20 +import { toReactions } from "./gitHubPullRequestJson.ts";
21 +
22 +type DetailIssue = NonNullable<NonNullable<Issues.IssueDetail.Result["repository"]>["issue"]>;
23 +type Actor = {
24 + readonly login: string;
25 + readonly name?: string | null;
26 + readonly avatarUrl: string | null;
27 +};
28 +type Label = NonNullable<NonNullable<NonNullable<Issues.NodesIssue["labels"]>["nodes"]>[number]>;
29 +type TimelineItem = NonNullable<NonNullable<DetailIssue["timelineItems"]["nodes"]>[number]>;
30 +type Comments = Omit<DetailIssue["comments"], "totalCount">;
31 +type Reference = NonNullable<
32 + NonNullable<NonNullable<DetailIssue["closedByPullRequestsReferences"]>["nodes"]>[number]
33 +>;
34 +
35 +function trimmed(value: string | null | undefined): string | null {
36 + const text = value?.trim() ?? "";
37 + return text.length > 0 ? text : null;
38 +}
39 +
40 +function toActor(raw: Actor | null | undefined): IssueActor | null {
41 + const login = trimmed(raw?.login);
42 + return login === null
43 + ? null
44 + : {
45 + login,
46 + name: trimmed(raw != null && "name" in raw ? raw.name : null),
47 + avatarUrl: trimmed(raw?.avatarUrl),
48 + };
49 +}
50 +
51 +function toActors(raw: ReadonlyArray<Actor | null> | null | undefined): ReadonlyArray<IssueActor> {
52 + return (raw ?? []).flatMap((entry) => toActor(entry) ?? []);
53 +}
54 +
55 +function toLabels(raw: ReadonlyArray<Label | null> | null | undefined): ReadonlyArray<IssueLabel> {
56 + return (raw ?? []).flatMap((label) => {
57 + const name = trimmed(label?.name);
58 + return name === null ? [] : [{ name, color: trimmed(label?.color) }];
59 + });
60 +}
61 +
62 +/** GitHub uses uppercase close reasons; an open issue has `""` or `REOPENED`. */
63 +function toIssueState(
64 + state: string | null | undefined,
65 + stateReason: string | null | undefined,
66 +): IssueState {
67 + if (state?.trim().toUpperCase() !== "CLOSED") return { category: "open", name: "open" };
68 + const reason = stateReason?.trim().toUpperCase();
69 + return {
70 + category: "closed",
71 + name: "closed",
72 + ...(reason === "COMPLETED"
73 + ? { closeReason: "completed" }
74 + : reason === "NOT_PLANNED"
75 + ? { closeReason: "not-planned" }
76 + : reason === "DUPLICATE"
77 + ? { closeReason: "duplicate" }
78 + : {}),
79 + };
80 +}
81 +
82 +function toSummary(raw: Omit<Issues.NodesIssue, "__typename">): TrackerIssueSummary {
83 + return {
84 + key: String(raw.number),
85 + displayKey: `#${raw.number}`,
86 + title: raw.title,
87 + url: raw.url,
88 + author: toActor(raw.author),
89 + state: toIssueState(raw.state, raw.stateReason),
90 + createdAt: raw.createdAt,
91 + updatedAt: raw.updatedAt,
92 + closedAt: trimmed(raw.closedAt),
93 + assignees: toActors(raw.assignees?.nodes),
94 + labels: toLabels(raw.labels?.nodes),
95 + commentCount: Math.max(0, raw.comments?.totalCount ?? 0),
96 + };
97 +}
98 +
99 +function toPullRequestState(value: string | null | undefined): PullRequestState {
100 + switch (value?.trim().toUpperCase()) {
101 + case "MERGED":
102 + return "merged";
103 + case "CLOSED":
104 + return "closed";
105 + default:
106 + return "open";
107 + }
108 +}
109 +
110 +function toLinkedPullRequest(
111 + raw: Reference | null | undefined,
112 + closesIssue: boolean,
113 +): IssueLinkedPullRequest | null {
114 + if (raw == null) return null;
115 + const { title, url, number } = raw;
116 + const repository = raw.repository.nameWithOwner;
117 + return {
118 + repository,
119 + number,
120 + title,
121 + url,
122 + state: toPullRequestState(raw.state),
123 + isDraft: raw.isDraft ?? false,
124 + closesIssue,
125 + };
126 +}
127 +
128 +/** The change GitHub recorded, or null for a kind this page has no vocabulary for. */
129 +function toEventFields(
130 + raw: TimelineItem,
131 +): { readonly kind: IssueEventKind; readonly detail: string | null } | null {
132 + switch (raw.__typename) {
133 + case "ClosedEvent":
134 + return { kind: "closed", detail: null };
135 + case "ReopenedEvent":
136 + return { kind: "reopened", detail: null };
137 + case "LabeledEvent":
138 + return { kind: "labeled", detail: trimmed(raw.label?.name) };
139 + case "UnlabeledEvent":
140 + return { kind: "unlabeled", detail: trimmed(raw.label?.name) };
141 + case "AssignedEvent":
142 + return {
143 + kind: "assigned",
144 + detail: trimmed(
145 + raw.assignee != null && "login" in raw.assignee ? raw.assignee.login : null,
146 + ),
147 + };
148 + case "UnassignedEvent":
149 + return {
150 + kind: "unassigned",
151 + detail: trimmed(
152 + raw.assignee != null && "login" in raw.assignee ? raw.assignee.login : null,
153 + ),
154 + };
155 + case "RenamedTitleEvent":
156 + return { kind: "renamed", detail: trimmed(raw.currentTitle) };
157 + case "CrossReferencedEvent": {
158 + const repository = trimmed(
159 + raw.source != null && "repository" in raw.source
160 + ? raw.source.repository.nameWithOwner
161 + : null,
162 + );
163 + const number = raw.source != null && "number" in raw.source ? raw.source.number : 0;
164 + return {
165 + kind: "referenced",
166 + detail: repository === null || number <= 0 ? null : `${repository}#${number}`,
167 + };
168 + }
169 + default:
170 + return null;
171 + }
172 +}
173 +
174 +function toComments(
175 + raw: Comments | null | undefined,
176 + viewer: string | null,
177 +): ReadonlyArray<IssueComment> {
178 + return (raw?.nodes ?? []).flatMap((comment) => {
179 + const id = trimmed(comment?.id);
180 + if (comment == null || id === null) return [];
181 + return [
182 + {
183 + id,
184 + author: toActor(comment.author),
185 + body: comment.body ?? "",
186 + createdAt: comment.createdAt,
187 + url: trimmed(comment.url),
188 + reactions: toReactions(comment.reactionGroups, viewer),
189 + },
190 + ];
191 + });
192 +}
193 +
194 +function previousCursorOf(
195 + pageInfo: { readonly hasPreviousPage: boolean; readonly startCursor: string | null } | undefined,
196 +) {
197 + return pageInfo?.hasPreviousPage === true ? pageInfo.startCursor : null;
198 +}
199 +
200 +function toViewerPermissions(raw: {
201 + readonly viewerPermission?: string | null | undefined;
202 + readonly issue: {
203 + readonly state: string;
204 + readonly viewerCanUpdate: boolean;
205 + readonly viewerCanClose: boolean;
206 + readonly viewerCanReopen: boolean;
207 + } | null;
208 +}): IssueViewerPermissions {
209 + const canUpdate = raw.issue?.viewerCanUpdate !== false;
210 + const canTriage = ["ADMIN", "MAINTAIN", "WRITE", "TRIAGE"].includes(
211 + raw.viewerPermission?.trim().toUpperCase() ?? "",
212 + );
213 + return {
214 + // Triage may close and reopen an issue it may not edit, so this is not `viewerCanUpdate`.
215 + setState:
216 + raw.issue === null ||
217 + (raw.issue.state === "CLOSED" ? raw.issue.viewerCanReopen : raw.issue.viewerCanClose),
218 + comment: true,
219 + edit: canUpdate,
220 + labels: canTriage,
221 + assignees: canTriage,
222 + };
223 +}
224 +
225 +interface GitHubIssueDetail extends TrackerIssueSummary {
226 + readonly body: string;
227 + readonly viewer: string | null;
228 + readonly viewerPermissions: IssueViewerPermissions;
229 + readonly reactions: ReturnType<typeof toReactions>;
230 + readonly comments: ReadonlyArray<IssueComment>;
231 + readonly commentsCursor: string | null;
232 + readonly events: ReadonlyArray<IssueEvent>;
233 + readonly linkedPullRequests: ReadonlyArray<IssueLinkedPullRequest>;
234 +}
235 +
236 +/** Null for a number that names no issue the viewer can see. */
237 +export function toIssueDetail({
238 + viewer: rawViewer,
239 + repository,
240 +}: Issues.IssueDetail.Result): GitHubIssueDetail | null {
241 + const issue = repository?.issue;
242 + if (issue == null) return null;
243 + const viewer = trimmed(rawViewer?.login);
244 +
245 + // Closing references lead; a cross-reference seen twice is filed under the stronger relation.
246 + const links = new Map<string, IssueLinkedPullRequest>();
247 + for (const node of issue.closedByPullRequestsReferences?.nodes ?? []) {
248 + const link = toLinkedPullRequest(node, true);
249 + if (link !== null) links.set(`${link.repository.toLowerCase()}#${link.number}`, link);
250 + }
251 + const events: IssueEvent[] = [];
252 + for (const entry of issue.timelineItems?.nodes ?? []) {
253 + if (entry === null) continue;
254 + const item = entry;
255 + if (item.__typename === "CrossReferencedEvent") {
256 + const link =
257 + item.source.__typename === "PullRequest" ? toLinkedPullRequest(item.source, false) : null;
258 + const linkKey = link === null ? null : `${link.repository.toLowerCase()}#${link.number}`;
259 + if (link !== null && linkKey !== null && !links.has(linkKey)) links.set(linkKey, link);
260 + }
261 + const fields = toEventFields(item);
262 + const id = trimmed("id" in item ? item.id : null);
263 + const createdAt = trimmed("createdAt" in item ? item.createdAt : null);
264 + if (fields === null || id === null || createdAt === null) continue;
265 + events.push({ id, ...fields, actor: toActor("actor" in item ? item.actor : null), createdAt });
266 + }
267 + return {
268 + ...toSummary(issue),
269 + body: issue.body ?? "",
270 + viewer,
271 + viewerPermissions: toViewerPermissions({
272 + viewerPermission: repository?.viewerPermission,
273 + issue,
274 + }),
275 + reactions: toReactions(issue.reactionGroups, viewer),
276 + comments: toComments(issue.comments, viewer),
277 + commentsCursor: previousCursorOf(issue.comments?.pageInfo),
278 + events,
279 + linkedPullRequests: [...links.values()],
280 + };
281 +}
282 +
283 +export function toIssueSearch({ search }: Issues.IssueSearch.Result) {
284 + return {
285 + items: (search.nodes ?? []).flatMap((node) =>
286 + node !== null && node.__typename === "Issue" ? [toSummary(node)] : [],
287 + ),
288 + nextCursor: search.pageInfo.hasNextPage ? search.pageInfo.endCursor : null,
289 + };
290 +}
291 +
292 +export function toIssueComments({ viewer, repository }: Issues.IssueComments.Result) {
293 + const comments = repository?.issue?.comments;
294 + return {
295 + comments: toComments(comments, viewer.login),
296 + nextCursor: previousCursorOf(comments?.pageInfo),
297 + };
298 +}
299 +
300 +export function toIssueCandidates(
301 + repository: NonNullable<Issues.IssueCandidates.Result["repository"]>,
302 +) {
303 + const { labels, assignableUsers } = repository;
304 + return {
305 + labels: (labels?.nodes ?? []).flatMap((label) =>
306 + label === null
307 + ? []
308 + : [
309 + {
310 + name: label.name,
311 + color: label.color,
312 + description: label.description,
313 + },
314 + ],
315 + ),
316 + assignees: toActors(assignableUsers.nodes).map((actor) => ({ ...actor, id: actor.login })),
317 + truncated:
318 + labels?.pageInfo.hasNextPage === true || assignableUsers.pageInfo.hasNextPage === true,
319 + };
320 +}
321 +
322 +export function toIssueTemplates(
323 + repository: NonNullable<Issues.IssueTemplates.Result["repository"]>,
324 +): ReadonlyArray<IssueTemplate> {
325 + return (repository.issueTemplates ?? []).flatMap((template) => {
326 + if (template === null || template.filename.trim() === "") return [];
327 + return [
328 + {
329 + key: template.filename,
330 + name: template.name,
331 + about: template.about ?? "",
332 + title: template.title ?? "",
333 + body: template.body ?? "",
334 + labels: (template.labels?.nodes ?? []).flatMap((node) => node?.name ?? []),
335 + assignees: (template.assignees.nodes ?? []).flatMap((node) => node?.login ?? []),
336 + },
337 + ];
338 + });
339 +}
340 +
341 +const decodeCreatedIssue = decodeJsonResult(
342 + Schema.Struct({ number: Schema.Int, html_url: TrimmedNonEmptyString }),
343 +);
344 +
345 +export function decodeCreatedIssueJson(raw: string) {
346 + return Result.map(decodeCreatedIssue(raw), (issue) => ({
347 + number: issue.number,
348 + url: issue.html_url,
349 + }));
350 +}
packages/source-control-github/src/server/gitHubIssueTemplates.ts new
+159
@@ -0,0 +1,159 @@
1 +import * as Effect from "effect/Effect";
2 +import * as Result from "effect/Result";
3 +import * as Schema from "effect/Schema";
4 +import { parse as parseYaml } from "yaml";
5 +import { IssueTrackerKind, TrimmedNonEmptyString, type IssueTemplate } from "@t3tools/contracts";
6 +import { IssueTrackerError } from "@t3tools/source-control-core/server/IssueTracker";
7 +
8 +import type * as Issues from "./issues.graphql.ts";
9 +import { toIssueTemplates } from "./gitHubIssueJson.ts";
10 +
11 +const Names = Schema.Union([Schema.String, Schema.Array(Schema.String)]);
12 +const FormOption = Schema.Union([
13 + Schema.String,
14 + Schema.Struct({ label: Schema.String, required: Schema.optional(Schema.Boolean) }),
15 +]);
16 +const FormField = Schema.Struct({
17 + type: Schema.String,
18 + id: Schema.optional(Schema.String),
19 + attributes: Schema.optional(
20 + Schema.Struct({
21 + label: Schema.optional(Schema.String),
22 + description: Schema.optional(Schema.String),
23 + value: Schema.optional(Schema.String),
24 + placeholder: Schema.optional(Schema.String),
25 + render: Schema.optional(Schema.String),
26 + multiple: Schema.optional(Schema.Boolean),
27 + default: Schema.optional(Schema.Union([Schema.Int, Schema.Array(Schema.Int)])),
28 + options: Schema.optional(Schema.Array(FormOption)),
29 + }),
30 + ),
31 + validations: Schema.optional(
32 + Schema.Struct({
33 + required: Schema.optional(Schema.Boolean),
34 + accept: Schema.optional(Schema.String),
35 + }),
36 + ),
37 +});
38 +const decodeForm = Schema.decodeUnknownSync(
39 + Schema.Struct({
40 + name: TrimmedNonEmptyString,
41 + description: Schema.String,
42 + title: Schema.optional(Schema.String),
43 + labels: Schema.optional(Names),
44 + assignees: Schema.optional(Names),
45 + body: Schema.Array(FormField),
46 + }),
47 +);
48 +const decodeConfig = Schema.decodeUnknownSync(
49 + Schema.Struct({ blank_issues_enabled: Schema.optional(Schema.Boolean) }),
50 +);
51 +
52 +function names(value: string | ReadonlyArray<string> | undefined): ReadonlyArray<string> {
53 + return (typeof value === "string" ? value.split(",") : (value ?? []))
54 + .map((name) => name.trim())
55 + .filter((name) => name.length > 0);
56 +}
57 +
58 +function fieldMarkdown(field: typeof FormField.Type): string {
59 + const attributes = field.attributes;
60 + if (field.type === "markdown") return attributes?.value ?? "";
61 +
62 + const sections = [`### ${attributes?.label ?? field.id ?? field.type}`];
63 + if (attributes?.description) sections.push(attributes.description);
64 + if (field.validations?.required) sections.push("Required.");
65 + if (attributes?.placeholder)
66 + sections.push(`Example:\n> ${attributes.placeholder.trim().replaceAll("\n", "\n> ")}`);
67 + if (attributes?.render) sections.push(`Format: ${attributes.render}`);
68 + if (field.validations?.accept) sections.push(`Accepted files: ${field.validations.accept}`);
69 +
70 + const options = attributes?.options ?? [];
71 + if (field.type === "checkboxes") {
72 + sections.push(
73 + options
74 + .map((option) => {
75 + const label = typeof option === "string" ? option : option.label;
76 + const required = typeof option !== "string" && option.required;
77 + return `- [ ] ${label}${required ? " (required)" : ""}`;
78 + })
79 + .join("\n"),
80 + );
81 + } else if (field.type === "dropdown") {
82 + const defaults = attributes?.default;
83 + const defaultIndices = typeof defaults === "number" ? [defaults] : (defaults ?? []);
84 + sections.push(attributes?.multiple ? "Choose one or more:" : "Choose one:");
85 + sections.push(
86 + options
87 + .map((option, index) => {
88 + const label = typeof option === "string" ? option : option.label;
89 + return `- ${label}${defaultIndices.includes(index) ? " (default)" : ""}`;
90 + })
91 + .join("\n"),
92 + );
93 + }
94 + if (attributes?.value) sections.push(attributes.value);
95 + return sections.filter(Boolean).join("\n\n");
96 +}
97 +
98 +export const readIssueTemplates = Effect.fnUntraced(function* (
99 + repository: NonNullable<Issues.IssueTemplates.Result["repository"]>,
100 +) {
101 + const templates = new Map<string, IssueTemplate>(
102 + toIssueTemplates(repository).map((template) => [
103 + template.key.slice(template.key.lastIndexOf("/") + 1),
104 + template,
105 + ]),
106 + );
107 + let blankIssuesEnabled = true;
108 + const directory = repository.templateDirectory;
109 + for (const entry of directory?.__typename === "Tree" ? (directory.entries ?? []) : []) {
110 + if (!/\.ya?ml$/i.test(entry.name)) continue;
111 + const blob = entry.object;
112 + if (blob?.__typename !== "Blob" || blob.isTruncated || blob.text === null) {
113 + return yield* new IssueTrackerError({
114 + tracker: IssueTrackerKind.make("github"),
115 + operation: "listTemplates",
116 + reason: "failed",
117 + detail: "GitHub returned incomplete issue template contents.",
118 + });
119 + }
120 + const text = blob.text;
121 + const isConfig = /^config\.ya?ml$/i.test(entry.name);
122 + const parsed = yield* Effect.try({
123 + try: () => {
124 + const document: unknown = parseYaml(text);
125 + if (isConfig) {
126 + return { config: decodeConfig(document ?? {}) };
127 + }
128 + return { form: decodeForm(document) };
129 + },
130 + catch: (cause) =>
131 + new IssueTrackerError({
132 + tracker: IssueTrackerKind.make("github"),
133 + operation: "listTemplates",
134 + reason: "failed",
135 + detail: "The repository has an unreadable issue template or configuration.",
136 + cause,
137 + }),
138 + }).pipe(Effect.result);
139 + if (Result.isFailure(parsed)) {
140 + if (isConfig) return yield* parsed.failure;
141 + continue;
142 + }
143 + if (parsed.success.config !== undefined) {
144 + blankIssuesEnabled = parsed.success.config.blank_issues_enabled ?? true;
145 + } else if (parsed.success.form !== undefined) {
146 + const form = parsed.success.form;
147 + templates.set(entry.name, {
148 + key: entry.name,
149 + name: form.name,
150 + about: form.description,
151 + title: form.title ?? "",
152 + labels: names(form.labels),
153 + assignees: names(form.assignees),
154 + body: form.body.map(fieldMarkdown).filter(Boolean).join("\n\n"),
155 + });
156 + }
157 + }
158 + return { templates: [...templates.values()], blankIssuesEnabled };
159 +});
packages/source-control-github/src/server/gitHubPullRequestJson.ts
+1 -1
@@ -191,7 +191,7 @@ export function gitHubReactionContent(
191 }
192
193 /** Keep the viewer in counts, not actors, to avoid duplicating 'You'. */
194 -function toReactions(
194 +export function toReactions(
195 groups: ReadonlyArray<ReactionGroup> | null | undefined,
196 viewer: string | null,
197 ): ReadonlyArray<PullRequestReaction> {
packages/source-control-github/src/server/issues.graphql new
+392
@@ -0,0 +1,392 @@
1 +fragment IssueRow on Issue {
2 + number
3 + title
4 + url
5 + state
6 + stateReason
7 + createdAt
8 + updatedAt
9 + closedAt
10 + author {
11 + login
12 + avatarUrl
13 + ... on User {
14 + name
15 + }
16 + }
17 +}
18 +
19 +query IssueSearch($q: String!, $cursor: String, $rows: Int!) {
20 + search(query: $q, type: ISSUE, first: $rows, after: $cursor) {
21 + pageInfo {
22 + hasNextPage
23 + endCursor
24 + }
25 + nodes {
26 + ... on Issue {
27 + ...IssueRow
28 + assignees(first: 20) {
29 + nodes {
30 + login
31 + name
32 + avatarUrl
33 + }
34 + }
35 + labels(first: 20) {
36 + nodes {
37 + name
38 + color
39 + }
40 + }
41 + comments {
42 + totalCount
43 + }
44 + }
45 + }
46 + }
47 +}
48 +
49 +query IssueDetail($owner: String!, $name: String!, $number: Int!) {
50 + viewer {
51 + login
52 + }
53 + repository(owner: $owner, name: $name) {
54 + viewerPermission
55 + issue(number: $number) {
56 + ...IssueRow
57 + assignees(first: 100) {
58 + pageInfo {
59 + hasNextPage
60 + endCursor
61 + }
62 + nodes {
63 + login
64 + name
65 + avatarUrl
66 + }
67 + }
68 + labels(first: 100) {
69 + pageInfo {
70 + hasNextPage
71 + endCursor
72 + }
73 + nodes {
74 + name
75 + color
76 + }
77 + }
78 + body
79 + viewerCanUpdate
80 + viewerCanClose
81 + viewerCanReopen
82 + ...Reactions
83 + comments(last: 100) {
84 + totalCount
85 + pageInfo {
86 + hasPreviousPage
87 + startCursor
88 + }
89 + nodes {
90 + id
91 + author {
92 + login
93 + avatarUrl
94 + }
95 + body
96 + createdAt
97 + url
98 + ...Reactions
99 + }
100 + }
101 + closedByPullRequestsReferences(first: 20, includeClosedPrs: true) {
102 + nodes {
103 + number
104 + title
105 + url
106 + state
107 + isDraft
108 + repository {
109 + nameWithOwner
110 + }
111 + }
112 + }
113 + timelineItems(
114 + last: 100
115 + itemTypes: [
116 + CLOSED_EVENT
117 + REOPENED_EVENT
118 + LABELED_EVENT
119 + UNLABELED_EVENT
120 + ASSIGNED_EVENT
121 + UNASSIGNED_EVENT
122 + RENAMED_TITLE_EVENT
123 + CROSS_REFERENCED_EVENT
124 + ]
125 + ) {
126 + nodes {
127 + __typename
128 + ... on ClosedEvent {
129 + id
130 + createdAt
131 + actor {
132 + login
133 + avatarUrl
134 + }
135 + }
136 + ... on ReopenedEvent {
137 + id
138 + createdAt
139 + actor {
140 + login
141 + avatarUrl
142 + }
143 + }
144 + ... on LabeledEvent {
145 + id
146 + createdAt
147 + actor {
148 + login
149 + avatarUrl
150 + }
151 + label {
152 + name
153 + }
154 + }
155 + ... on UnlabeledEvent {
156 + id
157 + createdAt
158 + actor {
159 + login
160 + avatarUrl
161 + }
162 + label {
163 + name
164 + }
165 + }
166 + ... on AssignedEvent {
167 + id
168 + createdAt
169 + actor {
170 + login
171 + avatarUrl
172 + }
173 + assignee {
174 + ... on User {
175 + login
176 + name
177 + }
178 + ... on Bot {
179 + login
180 + }
181 + }
182 + }
183 + ... on UnassignedEvent {
184 + id
185 + createdAt
186 + actor {
187 + login
188 + avatarUrl
189 + }
190 + assignee {
191 + ... on User {
192 + login
193 + name
194 + }
195 + ... on Bot {
196 + login
197 + }
198 + }
199 + }
200 + ... on RenamedTitleEvent {
201 + id
202 + createdAt
203 + actor {
204 + login
205 + avatarUrl
206 + }
207 + currentTitle
208 + }
209 + ... on CrossReferencedEvent {
210 + id
211 + createdAt
212 + actor {
213 + login
214 + avatarUrl
215 + }
216 + source {
217 + __typename
218 + ... on PullRequest {
219 + number
220 + title
221 + url
222 + state
223 + isDraft
224 + repository {
225 + nameWithOwner
226 + }
227 + }
228 + ... on Issue {
229 + number
230 + repository {
231 + nameWithOwner
232 + }
233 + }
234 + }
235 + }
236 + }
237 + }
238 + }
239 + }
240 +}
241 +
242 +query IssueComments($owner: String!, $name: String!, $number: Int!, $cursor: String!) {
243 + viewer {
244 + login
245 + }
246 + repository(owner: $owner, name: $name) {
247 + issue(number: $number) {
248 + comments(last: 100, before: $cursor) {
249 + pageInfo {
250 + hasPreviousPage
251 + startCursor
252 + }
253 + nodes {
254 + id
255 + author {
256 + login
257 + avatarUrl
258 + }
259 + body
260 + createdAt
261 + url
262 + ...Reactions
263 + }
264 + }
265 + }
266 + }
267 +}
268 +
269 +query IssueNodeId($owner: String!, $name: String!, $number: Int!) {
270 + repository(owner: $owner, name: $name) {
271 + issue(number: $number) {
272 + id
273 + state
274 + stateReason
275 + }
276 + }
277 +}
278 +
279 +query IssueCommentScope($owner: String!, $name: String!, $number: Int!, $commentId: ID!) {
280 + repository(owner: $owner, name: $name) {
281 + issue(number: $number) {
282 + id
283 + }
284 + }
285 + node(id: $commentId) {
286 + ... on IssueComment {
287 + issue {
288 + id
289 + }
290 + }
291 + }
292 +}
293 +
294 +query IssueCandidates($owner: String!, $name: String!) {
295 + repository(owner: $owner, name: $name) {
296 + labels(first: 100) {
297 + pageInfo {
298 + hasNextPage
299 + }
300 + nodes {
301 + name
302 + color
303 + description
304 + }
305 + }
306 + assignableUsers(first: 100) {
307 + pageInfo {
308 + hasNextPage
309 + }
310 + nodes {
311 + login
312 + name
313 + avatarUrl
314 + }
315 + }
316 + }
317 +}
318 +
319 +query IssueTemplates($owner: String!, $name: String!) {
320 + repository(owner: $owner, name: $name) {
321 + templateDirectory: object(expression: "HEAD:.github/ISSUE_TEMPLATE") {
322 + ... on Tree {
323 + entries {
324 + name
325 + object {
326 + ... on Blob {
327 + text
328 + isTruncated
329 + }
330 + }
331 + }
332 + }
333 + }
334 + issueTemplates {
335 + filename
336 + name
337 + about
338 + title
339 + body
340 + assignees(first: 25) {
341 + nodes {
342 + login
343 + }
344 + }
345 + labels(first: 50) {
346 + nodes {
347 + name
348 + }
349 + }
350 + }
351 + }
352 +}
353 +
354 +query IssueViewer {
355 + viewer {
356 + login
357 + }
358 +}
359 +
360 +query IssueCollections(
361 + $owner: String!
362 + $name: String!
363 + $number: Int!
364 + $labelsCursor: String
365 + $assigneesCursor: String
366 +) {
367 + repository(owner: $owner, name: $name) {
368 + issue(number: $number) {
369 + labels(first: 100, after: $labelsCursor) {
370 + pageInfo {
371 + hasNextPage
372 + endCursor
373 + }
374 + nodes {
375 + name
376 + color
377 + }
378 + }
379 + assignees(first: 100, after: $assigneesCursor) {
380 + pageInfo {
381 + hasNextPage
382 + endCursor
383 + }
384 + nodes {
385 + login
386 + name
387 + avatarUrl
388 + }
389 + }
390 + }
391 + }
392 +}
packages/source-control-github/src/server/issues.graphql.ts new
+1029
@@ -0,0 +1,1029 @@
1 +// Generated by @effect/graphql-generator from issues.graphql. Do not edit.
2 +import { GraphQL, GraphQLGroup } from "effect/graphql"
3 +import * as Schema from "effect/Schema"
4 +import * as Shared from "../../schema/github.graphql.ts"
5 +
6 +/** A user is an individual's account on GitHub that owns repositories and can make new content. */
7 +export const AuthorUser = Schema.Struct({
8 + __typename: Schema.Literal("User"),
9 + /** The username used to login. */
10 + login: Schema.String,
11 + /** A URL pointing to the user's public avatar. */
12 + avatarUrl: Shared.URI,
13 + /** The user's public profile name. */
14 + name: Schema.NullOr(Schema.String)
15 +})
16 +export interface AuthorUser extends Schema.Struct.Type<typeof AuthorUser.fields> {}
17 +
18 +/** Represents an object which can take actions on GitHub. Typically a User or Bot. */
19 +export const ActorOther = Schema.Struct({
20 + __typename: GraphQL.otherTypename<Shared.Typename.Actor>()(["User"]),
21 + /** The username of the actor. */
22 + login: Schema.String,
23 + /** A URL pointing to the actor's public avatar. */
24 + avatarUrl: Shared.URI
25 +})
26 +export interface ActorOther extends Schema.Struct.Type<typeof ActorOther.fields> {}
27 +
28 +/**
29 + * `fragment IssueRow on Issue`
30 + *
31 + * An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project.
32 + */
33 +export const IssueRow = Schema.Struct({
34 + /** Identifies the issue number. */
35 + number: Shared.Int,
36 + /** Identifies the issue title. */
37 + title: Schema.String,
38 + /** The HTTP URL for this issue */
39 + url: Shared.URI,
40 + /** Identifies the state of the issue. */
41 + state: GraphQL.enumLiterals(Shared.IssueState.literals),
42 + /** Identifies the reason for the issue state. */
43 + stateReason: Schema.NullOr(GraphQL.enumLiterals(Shared.IssueStateReason.literals)),
44 + /** Identifies the date and time when the object was created. */
45 + createdAt: Shared.DateTime,
46 + /** Identifies the date and time when the object was last updated. */
47 + updatedAt: Shared.DateTime,
48 + /** Identifies the date and time when the object was closed. */
49 + closedAt: Schema.NullOr(Shared.DateTime),
50 + /** The actor who authored the comment. */
51 + author: Schema.NullOr(Schema.Union([
52 + AuthorUser,
53 + ActorOther
54 + ]))
55 +})
56 +export interface IssueRow extends Schema.Struct.Type<typeof IssueRow.fields> {}
57 +
58 +/** Information about pagination in a connection. */
59 +export const SearchPageInfoPageInfo = Schema.Struct({
60 + /** When paginating forwards, are there more items? */
61 + hasNextPage: Schema.Boolean,
62 + /** When paginating forwards, the cursor to continue. */
63 + endCursor: Schema.NullOr(Schema.String)
64 +})
65 +export interface SearchPageInfoPageInfo extends Schema.Struct.Type<typeof SearchPageInfoPageInfo.fields> {}
66 +
67 +/** A user is an individual's account on GitHub that owns repositories and can make new content. */
68 +export const AssigneesNodesUser = Schema.Struct({
69 + /** The username used to login. */
70 + login: Schema.String,
71 + /** The user's public profile name. */
72 + name: Schema.NullOr(Schema.String),
73 + /** A URL pointing to the user's public avatar. */
74 + avatarUrl: Shared.URI
75 +})
76 +export interface AssigneesNodesUser extends Schema.Struct.Type<typeof AssigneesNodesUser.fields> {}
77 +
78 +/** A list of users. */
79 +export const NodesAssigneesUserConnection = Schema.Struct({
80 + /** A list of nodes. */
81 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(AssigneesNodesUser)))
82 +})
83 +export interface NodesAssigneesUserConnection extends Schema.Struct.Type<typeof NodesAssigneesUserConnection.fields> {}
84 +
85 +/** A label for categorizing Issues, Pull Requests, Milestones, or Discussions with a given Repository. */
86 +export const NodesLabelsNodesLabel = Schema.Struct({
87 + /** Identifies the label name. */
88 + name: Schema.String,
89 + /** Identifies the label color. */
90 + color: Schema.String
91 +})
92 +export interface NodesLabelsNodesLabel extends Schema.Struct.Type<typeof NodesLabelsNodesLabel.fields> {}
93 +
94 +/** The connection type for Label. */
95 +export const NodesLabelsLabelConnection = Schema.Struct({
96 + /** A list of nodes. */
97 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(NodesLabelsNodesLabel)))
98 +})
99 +export interface NodesLabelsLabelConnection extends Schema.Struct.Type<typeof NodesLabelsLabelConnection.fields> {}
100 +
101 +/** The connection type for IssueComment. */
102 +export const NodesCommentsIssueCommentConnection = Schema.Struct({
103 + /** Identifies the total count of items in the connection. */
104 + totalCount: Shared.Int
105 +})
106 +export interface NodesCommentsIssueCommentConnection extends Schema.Struct.Type<typeof NodesCommentsIssueCommentConnection.fields> {}
107 +
108 +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */
109 +export const NodesIssue = Schema.Struct({
110 + __typename: Schema.Literal("Issue"),
111 + ...IssueRow.fields,
112 + /** A list of Users assigned to this object. */
113 + assignees: NodesAssigneesUserConnection,
114 + /** A list of labels associated with the object. */
115 + labels: Schema.NullOr(NodesLabelsLabelConnection),
116 + /** A list of comments associated with the Issue. */
117 + comments: NodesCommentsIssueCommentConnection
118 +})
119 +export interface NodesIssue extends Schema.Struct.Type<typeof NodesIssue.fields> {}
120 +
121 +/** The results of a search. */
122 +export const SearchResultItemOther = Schema.Struct({
123 + __typename: GraphQL.otherTypename<Shared.Typename.SearchResultItem>()(["Issue"])
124 +})
125 +export interface SearchResultItemOther extends Schema.Struct.Type<typeof SearchResultItemOther.fields> {}
126 +
127 +/**
128 + * A list of results that matched against a search query. Regardless of the number
129 + * of matches, a maximum of 1,000 results will be available across all types,
130 + * potentially split across many pages.
131 + */
132 +export const SearchResultItemConnection = Schema.Struct({
133 + /** Information to aid in pagination. */
134 + pageInfo: SearchPageInfoPageInfo,
135 + /** A list of nodes. */
136 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(Schema.Union([
137 + NodesIssue,
138 + SearchResultItemOther
139 + ]))))
140 +})
141 +export interface SearchResultItemConnection extends Schema.Struct.Type<typeof SearchResultItemConnection.fields> {}
142 +
143 +/** `query IssueSearch` */
144 +export const IssueSearch = GraphQL.query("IssueSearch", {
145 + document: {
146 + variables: [
147 + { name: "q", body: "String!" },
148 + { name: "cursor", body: "String" },
149 + { name: "rows", body: "Int!" }
150 + ],
151 + selections: [
152 + { name: "search", body: ["(query:$", "q", " type:ISSUE first:$", "rows", " after:$", "cursor", "){pageInfo{hasNextPage endCursor}nodes{__typename...on Issue{...IssueRow assignees(first:20){nodes{login name avatarUrl}}labels(first:20){nodes{name color}}comments{totalCount}}}}"] }
153 + ],
154 + fragments: [
155 + { name: "IssueRow", body: ["on Issue{number title url state stateReason createdAt updatedAt closedAt author{__typename login avatarUrl...on User{name}}}"] }
156 + ]
157 + },
158 + variables: {
159 + q: Schema.String,
160 + cursor: Schema.optional(Schema.NullOr(Schema.String)),
161 + rows: Shared.Int
162 + },
163 + result: Schema.Struct({
164 + /** Perform a search across resources, returning a maximum of 1,000 results. */
165 + search: SearchResultItemConnection
166 + })
167 +})
168 +export declare namespace IssueSearch {
169 + export type Variables = typeof IssueSearch.variables.Type
170 + export type Result = typeof IssueSearch.result.Type
171 +}
172 +
173 +/** A user is an individual's account on GitHub that owns repositories and can make new content. */
174 +export const ViewerUser = Schema.Struct({
175 + /** The username used to login. */
176 + login: Schema.String
177 +})
178 +export interface ViewerUser extends Schema.Struct.Type<typeof ViewerUser.fields> {}
179 +
180 +/** A list of users. */
181 +export const IssueAssigneesUserConnection = Schema.Struct({
182 + /** Information to aid in pagination. */
183 + pageInfo: SearchPageInfoPageInfo,
184 + /** A list of nodes. */
185 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(AssigneesNodesUser)))
186 +})
187 +export interface IssueAssigneesUserConnection extends Schema.Struct.Type<typeof IssueAssigneesUserConnection.fields> {}
188 +
189 +/** The connection type for Label. */
190 +export const IssueLabelsLabelConnection = Schema.Struct({
191 + /** Information to aid in pagination. */
192 + pageInfo: SearchPageInfoPageInfo,
193 + /** A list of nodes. */
194 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(NodesLabelsNodesLabel)))
195 +})
196 +export interface IssueLabelsLabelConnection extends Schema.Struct.Type<typeof IssueLabelsLabelConnection.fields> {}
197 +
198 +/** A user is an individual's account on GitHub that owns repositories and can make new content. */
199 +export const ReactorsNodesUser = Schema.Struct({
200 + __typename: Schema.Literal("User"),
201 + /** The username used to login. */
202 + login: Schema.String
203 +})
204 +export interface ReactorsNodesUser extends Schema.Struct.Type<typeof ReactorsNodesUser.fields> {}
205 +
206 +/** A special type of user which takes actions on behalf of GitHub Apps. */
207 +export const Bot = Schema.Struct({
208 + __typename: Schema.Literal("Bot"),
209 + /** The username of the actor. */
210 + login: Schema.String
211 +})
212 +export interface Bot extends Schema.Struct.Type<typeof Bot.fields> {}
213 +
214 +/** An account on GitHub, with one or more owners, that has repositories, members and teams. */
215 +export const Organization = Schema.Struct({
216 + __typename: Schema.Literal("Organization"),
217 + /** The organization's login name. */
218 + login: Schema.String
219 +})
220 +export interface Organization extends Schema.Struct.Type<typeof Organization.fields> {}
221 +
222 +/** A placeholder user for attribution of imported data on GitHub. */
223 +export const Mannequin = Schema.Struct({
224 + __typename: Schema.Literal("Mannequin"),
225 + /** The username of the actor. */
226 + login: Schema.String
227 +})
228 +export interface Mannequin extends Schema.Struct.Type<typeof Mannequin.fields> {}
229 +
230 +/** Types that can be assigned to reactions. */
231 +export const ReactorOther = Schema.Struct({
232 + __typename: GraphQL.otherTypename<Shared.Typename.Reactor>()(["User", "Bot", "Organization", "Mannequin"])
233 +})
234 +export interface ReactorOther extends Schema.Struct.Type<typeof ReactorOther.fields> {}
235 +
236 +/** The connection type for Reactor. */
237 +export const ReactorConnection = Schema.Struct({
238 + /** Identifies the total count of items in the connection. */
239 + totalCount: Shared.Int,
240 + /** A list of nodes. */
241 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(Schema.Union([
242 + ReactorsNodesUser,
243 + Bot,
244 + Organization,
245 + Mannequin,
246 + ReactorOther
247 + ]))))
248 +})
249 +export interface ReactorConnection extends Schema.Struct.Type<typeof ReactorConnection.fields> {}
250 +
251 +/** A group of emoji reactions to a particular piece of content. */
252 +export const ReactionGroup = Schema.Struct({
253 + /** Identifies the emoji reaction. */
254 + content: GraphQL.enumLiterals(Shared.ReactionContent.literals),
255 + /** Whether or not the authenticated user has left a reaction on the subject. */
256 + viewerHasReacted: Schema.Boolean,
257 + /** Reactors to the reaction subject with the emotion represented by this reaction group. */
258 + reactors: ReactorConnection
259 +})
260 +export interface ReactionGroup extends Schema.Struct.Type<typeof ReactionGroup.fields> {}
261 +
262 +/** Information about pagination in a connection. */
263 +export const CommentsPageInfoPageInfo = Schema.Struct({
264 + /** When paginating backwards, are there more items? */
265 + hasPreviousPage: Schema.Boolean,
266 + /** When paginating backwards, the cursor to continue. */
267 + startCursor: Schema.NullOr(Schema.String)
268 +})
269 +export interface CommentsPageInfoPageInfo extends Schema.Struct.Type<typeof CommentsPageInfoPageInfo.fields> {}
270 +
271 +/** Represents an object which can take actions on GitHub. Typically a User or Bot. */
272 +export const Actor = Schema.Struct({
273 + __typename: GraphQL.otherTypename<Shared.Typename.Actor>()([]),
274 + /** The username of the actor. */
275 + login: Schema.String,
276 + /** A URL pointing to the actor's public avatar. */
277 + avatarUrl: Shared.URI
278 +})
279 +export interface Actor extends Schema.Struct.Type<typeof Actor.fields> {}
280 +
281 +/** Represents a comment on an Issue. */
282 +export const NodesIssueComment = Schema.Struct({
283 + /** The Node ID of the IssueComment object */
284 + id: Shared.ID,
285 + /** The actor who authored the comment. */
286 + author: Schema.NullOr(Actor),
287 + /** The body as Markdown. */
288 + body: Schema.String,
289 + /** Identifies the date and time when the object was created. */
290 + createdAt: Shared.DateTime,
291 + /** The HTTP URL for this issue comment */
292 + url: Shared.URI,
293 + /** A list of reactions grouped by content left on the subject. */
294 + reactionGroups: Schema.NullOr(Schema.Array(ReactionGroup))
295 +})
296 +export interface NodesIssueComment extends Schema.Struct.Type<typeof NodesIssueComment.fields> {}
297 +
298 +/** The connection type for IssueComment. */
299 +export const IssueDetailRepositoryIssueCommentsIssueCommentConnection = Schema.Struct({
300 + /** Identifies the total count of items in the connection. */
301 + totalCount: Shared.Int,
302 + /** Information to aid in pagination. */
303 + pageInfo: CommentsPageInfoPageInfo,
304 + /** A list of nodes. */
305 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(NodesIssueComment)))
306 +})
307 +export interface IssueDetailRepositoryIssueCommentsIssueCommentConnection extends Schema.Struct.Type<typeof IssueDetailRepositoryIssueCommentsIssueCommentConnection.fields> {}
308 +
309 +/** A repository contains the content for a project. */
310 +export const NodesRepositoryRepository = Schema.Struct({
311 + /** The repository's name with owner. */
312 + nameWithOwner: Schema.String
313 +})
314 +export interface NodesRepositoryRepository extends Schema.Struct.Type<typeof NodesRepositoryRepository.fields> {}
315 +
316 +/** A repository pull request. */
317 +export const NodesPullRequest = Schema.Struct({
318 + /** Identifies the pull request number. */
319 + number: Shared.Int,
320 + /** Identifies the pull request title. */
321 + title: Schema.String,
322 + /** The HTTP URL for this pull request. */
323 + url: Shared.URI,
324 + /** Identifies the state of the pull request. */
325 + state: GraphQL.enumLiterals(Shared.PullRequestState.literals),
326 + /** Identifies if the pull request is a draft. */
327 + isDraft: Schema.Boolean,
328 + /** The repository associated with this node. */
329 + repository: NodesRepositoryRepository
330 +})
331 +export interface NodesPullRequest extends Schema.Struct.Type<typeof NodesPullRequest.fields> {}
332 +
333 +/** The connection type for PullRequest. */
334 +export const PullRequestConnection = Schema.Struct({
335 + /** A list of nodes. */
336 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(NodesPullRequest)))
337 +})
338 +export interface PullRequestConnection extends Schema.Struct.Type<typeof PullRequestConnection.fields> {}
339 +
340 +/** Represents a 'closed' event on any `Closable`. */
341 +export const ClosedEvent = Schema.Struct({
342 + __typename: Schema.Literal("ClosedEvent"),
343 + /** The Node ID of the ClosedEvent object */
344 + id: Shared.ID,
345 + /** Identifies the date and time when the object was created. */
346 + createdAt: Shared.DateTime,
347 + /** Identifies the actor who performed the event. */
348 + actor: Schema.NullOr(Actor)
349 +})
350 +export interface ClosedEvent extends Schema.Struct.Type<typeof ClosedEvent.fields> {}
351 +
352 +/** Represents a 'reopened' event on any `Closable`. */
353 +export const ReopenedEvent = Schema.Struct({
354 + __typename: Schema.Literal("ReopenedEvent"),
355 + /** The Node ID of the ReopenedEvent object */
356 + id: Shared.ID,
357 + /** Identifies the date and time when the object was created. */
358 + createdAt: Shared.DateTime,
359 + /** Identifies the actor who performed the event. */
360 + actor: Schema.NullOr(Actor)
361 +})
362 +export interface ReopenedEvent extends Schema.Struct.Type<typeof ReopenedEvent.fields> {}
363 +
364 +/** A label for categorizing Issues, Pull Requests, Milestones, or Discussions with a given Repository. */
365 +export const LabelLabel = Schema.Struct({
366 + /** Identifies the label name. */
367 + name: Schema.String
368 +})
369 +export interface LabelLabel extends Schema.Struct.Type<typeof LabelLabel.fields> {}
370 +
371 +/** Represents a 'labeled' event on a given issue or pull request. */
372 +export const LabeledEvent = Schema.Struct({
373 + __typename: Schema.Literal("LabeledEvent"),
374 + /** The Node ID of the LabeledEvent object */
375 + id: Shared.ID,
376 + /** Identifies the date and time when the object was created. */
377 + createdAt: Shared.DateTime,
378 + /** Identifies the actor who performed the event. */
379 + actor: Schema.NullOr(Actor),
380 + /** Identifies the label associated with the 'labeled' event. */
381 + label: LabelLabel
382 +})
383 +export interface LabeledEvent extends Schema.Struct.Type<typeof LabeledEvent.fields> {}
384 +
385 +/** Represents an 'unlabeled' event on a given issue or pull request. */
386 +export const UnlabeledEvent = Schema.Struct({
387 + __typename: Schema.Literal("UnlabeledEvent"),
388 + /** The Node ID of the UnlabeledEvent object */
389 + id: Shared.ID,
390 + /** Identifies the date and time when the object was created. */
391 + createdAt: Shared.DateTime,
392 + /** Identifies the actor who performed the event. */
393 + actor: Schema.NullOr(Actor),
394 + /** Identifies the label associated with the 'unlabeled' event. */
395 + label: LabelLabel
396 +})
397 +export interface UnlabeledEvent extends Schema.Struct.Type<typeof UnlabeledEvent.fields> {}
398 +
399 +/** A user is an individual's account on GitHub that owns repositories and can make new content. */
400 +export const AssigneeUser = Schema.Struct({
401 + __typename: Schema.Literal("User"),
402 + /** The username used to login. */
403 + login: Schema.String,
404 + /** The user's public profile name. */
405 + name: Schema.NullOr(Schema.String)
406 +})
407 +export interface AssigneeUser extends Schema.Struct.Type<typeof AssigneeUser.fields> {}
408 +
409 +/** Types that can be assigned to issues. */
410 +export const AssigneeOther = Schema.Struct({
411 + __typename: GraphQL.otherTypename<Shared.Typename.Assignee>()(["User", "Bot"])
412 +})
413 +export interface AssigneeOther extends Schema.Struct.Type<typeof AssigneeOther.fields> {}
414 +
415 +/** Represents an 'assigned' event on any assignable object. */
416 +export const AssignedEvent = Schema.Struct({
417 + __typename: Schema.Literal("AssignedEvent"),
418 + /** The Node ID of the AssignedEvent object */
419 + id: Shared.ID,
420 + /** Identifies the date and time when the object was created. */
421 + createdAt: Shared.DateTime,
422 + /** Identifies the actor who performed the event. */
423 + actor: Schema.NullOr(Actor),
424 + /** Identifies the user or mannequin that was assigned. */
425 + assignee: Schema.NullOr(Schema.Union([
426 + AssigneeUser,
427 + Bot,
428 + AssigneeOther
429 + ]))
430 +})
431 +export interface AssignedEvent extends Schema.Struct.Type<typeof AssignedEvent.fields> {}
432 +
433 +/** Represents an 'unassigned' event on any assignable object. */
434 +export const UnassignedEvent = Schema.Struct({
435 + __typename: Schema.Literal("UnassignedEvent"),
436 + /** The Node ID of the UnassignedEvent object */
437 + id: Shared.ID,
438 + /** Identifies the date and time when the object was created. */
439 + createdAt: Shared.DateTime,
440 + /** Identifies the actor who performed the event. */
441 + actor: Schema.NullOr(Actor),
442 + /** Identifies the user or mannequin that was unassigned. */
443 + assignee: Schema.NullOr(Schema.Union([
444 + AssigneeUser,
445 + Bot,
446 + AssigneeOther
447 + ]))
448 +})
449 +export interface UnassignedEvent extends Schema.Struct.Type<typeof UnassignedEvent.fields> {}
450 +
451 +/** Represents a 'renamed' event on a given issue or pull request */
452 +export const RenamedTitleEvent = Schema.Struct({
453 + __typename: Schema.Literal("RenamedTitleEvent"),
454 + /** The Node ID of the RenamedTitleEvent object */
455 + id: Shared.ID,
456 + /** Identifies the date and time when the object was created. */
457 + createdAt: Shared.DateTime,
458 + /** Identifies the actor who performed the event. */
459 + actor: Schema.NullOr(Actor),
460 + /** Identifies the current title of the issue or pull request. */
461 + currentTitle: Schema.String
462 +})
463 +export interface RenamedTitleEvent extends Schema.Struct.Type<typeof RenamedTitleEvent.fields> {}
464 +
465 +/** A repository pull request. */
466 +export const SourcePullRequest = Schema.Struct({
467 + __typename: Schema.Literal("PullRequest"),
468 + /** Identifies the pull request number. */
469 + number: Shared.Int,
470 + /** Identifies the pull request title. */
471 + title: Schema.String,
472 + /** The HTTP URL for this pull request. */
473 + url: Shared.URI,
474 + /** Identifies the state of the pull request. */
475 + state: GraphQL.enumLiterals(Shared.PullRequestState.literals),
476 + /** Identifies if the pull request is a draft. */
477 + isDraft: Schema.Boolean,
478 + /** The repository associated with this node. */
479 + repository: NodesRepositoryRepository
480 +})
481 +export interface SourcePullRequest extends Schema.Struct.Type<typeof SourcePullRequest.fields> {}
482 +
483 +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */
484 +export const SourceIssue = Schema.Struct({
485 + __typename: Schema.Literal("Issue"),
486 + /** Identifies the issue number. */
487 + number: Shared.Int,
488 + /** The repository associated with this node. */
489 + repository: NodesRepositoryRepository
490 +})
491 +export interface SourceIssue extends Schema.Struct.Type<typeof SourceIssue.fields> {}
492 +
493 +/** Any referencable object */
494 +export const ReferencedSubjectOther = Schema.Struct({
495 + __typename: GraphQL.otherTypename<Shared.Typename.ReferencedSubject>()(["PullRequest", "Issue"])
496 +})
497 +export interface ReferencedSubjectOther extends Schema.Struct.Type<typeof ReferencedSubjectOther.fields> {}
498 +
499 +/** Represents a mention made by one issue or pull request to another. */
500 +export const CrossReferencedEvent = Schema.Struct({
501 + __typename: Schema.Literal("CrossReferencedEvent"),
502 + /** The Node ID of the CrossReferencedEvent object */
503 + id: Shared.ID,
504 + /** Identifies the date and time when the object was created. */
505 + createdAt: Shared.DateTime,
506 + /** Identifies the actor who performed the event. */
507 + actor: Schema.NullOr(Actor),
508 + /** Issue or pull request that made the reference. */
509 + source: Schema.Union([
510 + SourcePullRequest,
511 + SourceIssue,
512 + ReferencedSubjectOther
513 + ])
514 +})
515 +export interface CrossReferencedEvent extends Schema.Struct.Type<typeof CrossReferencedEvent.fields> {}
516 +
517 +/** An item in an issue timeline */
518 +export const IssueTimelineItemsOther = Schema.Struct({
519 + __typename: GraphQL.otherTypename<Shared.Typename.IssueTimelineItems>()(["ClosedEvent", "ReopenedEvent", "LabeledEvent", "UnlabeledEvent", "AssignedEvent", "UnassignedEvent", "RenamedTitleEvent", "CrossReferencedEvent"])
520 +})
521 +export interface IssueTimelineItemsOther extends Schema.Struct.Type<typeof IssueTimelineItemsOther.fields> {}
522 +
523 +/** The connection type for IssueTimelineItems. */
524 +export const IssueTimelineItemsConnection = Schema.Struct({
525 + /** A list of nodes. */
526 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(Schema.Union([
527 + ClosedEvent,
528 + ReopenedEvent,
529 + LabeledEvent,
530 + UnlabeledEvent,
531 + AssignedEvent,
532 + UnassignedEvent,
533 + RenamedTitleEvent,
534 + CrossReferencedEvent,
535 + IssueTimelineItemsOther
536 + ]))))
537 +})
538 +export interface IssueTimelineItemsConnection extends Schema.Struct.Type<typeof IssueTimelineItemsConnection.fields> {}
539 +
540 +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */
541 +export const IssueDetailRepositoryIssueIssue = Schema.Struct({
542 + ...IssueRow.fields,
543 + /** A list of Users assigned to this object. */
544 + assignees: IssueAssigneesUserConnection,
545 + /** A list of labels associated with the object. */
546 + labels: Schema.NullOr(IssueLabelsLabelConnection),
547 + /** Identifies the body of the issue. */
548 + body: Schema.String,
549 + /** Check if the current viewer can update this object. */
550 + viewerCanUpdate: Schema.Boolean,
551 + /** Indicates if the object can be closed by the viewer. */
552 + viewerCanClose: Schema.Boolean,
553 + /** Indicates if the object can be reopened by the viewer. */
554 + viewerCanReopen: Schema.Boolean,
555 + /** A list of reactions grouped by content left on the subject. */
556 + reactionGroups: Schema.NullOr(Schema.Array(ReactionGroup)),
557 + /** A list of comments associated with the Issue. */
558 + comments: IssueDetailRepositoryIssueCommentsIssueCommentConnection,
559 + /** List of open pull requests referenced from this issue */
560 + closedByPullRequestsReferences: Schema.NullOr(PullRequestConnection),
561 + /** A list of events, comments, commits, etc. associated with the issue. */
562 + timelineItems: IssueTimelineItemsConnection
563 +})
564 +export interface IssueDetailRepositoryIssueIssue extends Schema.Struct.Type<typeof IssueDetailRepositoryIssueIssue.fields> {}
565 +
566 +/** A repository contains the content for a project. */
567 +export const IssueDetailRepositoryRepository = Schema.Struct({
568 + /** The users permission level on the repository. Will return null if authenticated as an GitHub App. */
569 + viewerPermission: Schema.NullOr(GraphQL.enumLiterals(Shared.RepositoryPermission.literals)),
570 + /** Returns a single issue from the current repository by number. */
571 + issue: Schema.NullOr(IssueDetailRepositoryIssueIssue)
572 +})
573 +export interface IssueDetailRepositoryRepository extends Schema.Struct.Type<typeof IssueDetailRepositoryRepository.fields> {}
574 +
575 +/** `query IssueDetail` */
576 +export const IssueDetail = GraphQL.query("IssueDetail", {
577 + document: {
578 + variables: [
579 + { name: "owner", body: "String!" },
580 + { name: "name", body: "String!" },
581 + { name: "number", body: "Int!" }
582 + ],
583 + selections: [
584 + { name: "viewer", body: ["{login}"] },
585 + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number repository{nameWithOwner}}}}}}}}"] }
586 + ],
587 + fragments: [
588 + { name: "IssueRow", body: ["on Issue{number title url state stateReason createdAt updatedAt closedAt author{__typename login avatarUrl...on User{name}}}"] },
589 + { name: "Reactions", body: ["on Reactable{__typename reactionGroups{content viewerHasReacted reactors(first:10){totalCount nodes{__typename...on User{login}...on Bot{login}...on Organization{login}...on Mannequin{login}}}}}"] }
590 + ]
591 + },
592 + variables: {
593 + owner: Schema.String,
594 + name: Schema.String,
595 + number: Shared.Int
596 + },
597 + result: Schema.Struct({
598 + /** The currently authenticated user. */
599 + viewer: ViewerUser,
600 + /** Lookup a given repository by the owner and repository name. */
601 + repository: Schema.NullOr(IssueDetailRepositoryRepository)
602 + })
603 +})
604 +export declare namespace IssueDetail {
605 + export type Variables = typeof IssueDetail.variables.Type
606 + export type Result = typeof IssueDetail.result.Type
607 +}
608 +
609 +/** The connection type for IssueComment. */
610 +export const IssueCommentsRepositoryIssueCommentsIssueCommentConnection = Schema.Struct({
611 + /** Information to aid in pagination. */
612 + pageInfo: CommentsPageInfoPageInfo,
613 + /** A list of nodes. */
614 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(NodesIssueComment)))
615 +})
616 +export interface IssueCommentsRepositoryIssueCommentsIssueCommentConnection extends Schema.Struct.Type<typeof IssueCommentsRepositoryIssueCommentsIssueCommentConnection.fields> {}
617 +
618 +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */
619 +export const IssueCommentsRepositoryIssueIssue = Schema.Struct({
620 + /** A list of comments associated with the Issue. */
621 + comments: IssueCommentsRepositoryIssueCommentsIssueCommentConnection
622 +})
623 +export interface IssueCommentsRepositoryIssueIssue extends Schema.Struct.Type<typeof IssueCommentsRepositoryIssueIssue.fields> {}
624 +
625 +/** A repository contains the content for a project. */
626 +export const IssueCommentsRepositoryRepository = Schema.Struct({
627 + /** Returns a single issue from the current repository by number. */
628 + issue: Schema.NullOr(IssueCommentsRepositoryIssueIssue)
629 +})
630 +export interface IssueCommentsRepositoryRepository extends Schema.Struct.Type<typeof IssueCommentsRepositoryRepository.fields> {}
631 +
632 +/** `query IssueComments` */
633 +export const IssueComments = GraphQL.query("IssueComments", {
634 + document: {
635 + variables: [
636 + { name: "owner", body: "String!" },
637 + { name: "name", body: "String!" },
638 + { name: "number", body: "Int!" },
639 + { name: "cursor", body: "String!" }
640 + ],
641 + selections: [
642 + { name: "viewer", body: ["{login}"] },
643 + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){issue(number:$", "number", "){comments(last:100 before:$", "cursor", "){pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}}}"] }
644 + ],
645 + fragments: [
646 + { name: "Reactions", body: ["on Reactable{__typename reactionGroups{content viewerHasReacted reactors(first:10){totalCount nodes{__typename...on User{login}...on Bot{login}...on Organization{login}...on Mannequin{login}}}}}"] }
647 + ]
648 + },
649 + variables: {
650 + owner: Schema.String,
651 + name: Schema.String,
652 + number: Shared.Int,
653 + cursor: Schema.String
654 + },
655 + result: Schema.Struct({
656 + /** The currently authenticated user. */
657 + viewer: ViewerUser,
658 + /** Lookup a given repository by the owner and repository name. */
659 + repository: Schema.NullOr(IssueCommentsRepositoryRepository)
660 + })
661 +})
662 +export declare namespace IssueComments {
663 + export type Variables = typeof IssueComments.variables.Type
664 + export type Result = typeof IssueComments.result.Type
665 +}
666 +
667 +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */
668 +export const IssueNodeIdRepositoryIssueIssue = Schema.Struct({
669 + /** The Node ID of the Issue object */
670 + id: Shared.ID,
671 + /** Identifies the state of the issue. */
672 + state: GraphQL.enumLiterals(Shared.IssueState.literals),
673 + /** Identifies the reason for the issue state. */
674 + stateReason: Schema.NullOr(GraphQL.enumLiterals(Shared.IssueStateReason.literals))
675 +})
676 +export interface IssueNodeIdRepositoryIssueIssue extends Schema.Struct.Type<typeof IssueNodeIdRepositoryIssueIssue.fields> {}
677 +
678 +/** A repository contains the content for a project. */
679 +export const IssueNodeIdRepositoryRepository = Schema.Struct({
680 + /** Returns a single issue from the current repository by number. */
681 + issue: Schema.NullOr(IssueNodeIdRepositoryIssueIssue)
682 +})
683 +export interface IssueNodeIdRepositoryRepository extends Schema.Struct.Type<typeof IssueNodeIdRepositoryRepository.fields> {}
684 +
685 +/** `query IssueNodeId` */
686 +export const IssueNodeId = GraphQL.query("IssueNodeId", {
687 + document: {
688 + variables: [
689 + { name: "owner", body: "String!" },
690 + { name: "name", body: "String!" },
691 + { name: "number", body: "Int!" }
692 + ],
693 + selections: [
694 + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){issue(number:$", "number", "){id state stateReason}}"] }
695 + ],
696 + fragments: []
697 + },
698 + variables: {
699 + owner: Schema.String,
700 + name: Schema.String,
701 + number: Shared.Int
702 + },
703 + result: Schema.Struct({
704 + /** Lookup a given repository by the owner and repository name. */
705 + repository: Schema.NullOr(IssueNodeIdRepositoryRepository)
706 + })
707 +})
708 +export declare namespace IssueNodeId {
709 + export type Variables = typeof IssueNodeId.variables.Type
710 + export type Result = typeof IssueNodeId.result.Type
711 +}
712 +
713 +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */
714 +export const IssueCommentScopeRepositoryIssueIssue = Schema.Struct({
715 + /** The Node ID of the Issue object */
716 + id: Shared.ID
717 +})
718 +export interface IssueCommentScopeRepositoryIssueIssue extends Schema.Struct.Type<typeof IssueCommentScopeRepositoryIssueIssue.fields> {}
719 +
720 +/** A repository contains the content for a project. */
721 +export const IssueCommentScopeRepositoryRepository = Schema.Struct({
722 + /** Returns a single issue from the current repository by number. */
723 + issue: Schema.NullOr(IssueCommentScopeRepositoryIssueIssue)
724 +})
725 +export interface IssueCommentScopeRepositoryRepository extends Schema.Struct.Type<typeof IssueCommentScopeRepositoryRepository.fields> {}
726 +
727 +/** Represents a comment on an Issue. */
728 +export const NodeIssueComment = Schema.Struct({
729 + __typename: Schema.Literal("IssueComment"),
730 + /** Identifies the issue associated with the comment. */
731 + issue: IssueCommentScopeRepositoryIssueIssue
732 +})
733 +export interface NodeIssueComment extends Schema.Struct.Type<typeof NodeIssueComment.fields> {}
734 +
735 +/** An object with an ID. */
736 +export const NodeOther = Schema.Struct({
737 + __typename: GraphQL.otherTypename<Shared.Typename.Node>()(["IssueComment"])
738 +})
739 +export interface NodeOther extends Schema.Struct.Type<typeof NodeOther.fields> {}
740 +
741 +/** `query IssueCommentScope` */
742 +export const IssueCommentScope = GraphQL.query("IssueCommentScope", {
743 + document: {
744 + variables: [
745 + { name: "owner", body: "String!" },
746 + { name: "name", body: "String!" },
747 + { name: "number", body: "Int!" },
748 + { name: "commentId", body: "ID!" }
749 + ],
750 + selections: [
751 + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){issue(number:$", "number", "){id}}"] },
752 + { name: "node", body: ["(id:$", "commentId", "){__typename...on IssueComment{issue{id}}}"] }
753 + ],
754 + fragments: []
755 + },
756 + variables: {
757 + owner: Schema.String,
758 + name: Schema.String,
759 + number: Shared.Int,
760 + commentId: Shared.ID
761 + },
762 + result: Schema.Struct({
763 + /** Lookup a given repository by the owner and repository name. */
764 + repository: Schema.NullOr(IssueCommentScopeRepositoryRepository),
765 + /** Fetches an object given its ID. */
766 + node: Schema.NullOr(Schema.Union([
767 + NodeIssueComment,
768 + NodeOther
769 + ]))
770 + })
771 +})
772 +export declare namespace IssueCommentScope {
773 + export type Variables = typeof IssueCommentScope.variables.Type
774 + export type Result = typeof IssueCommentScope.result.Type
775 +}
776 +
777 +/** Information about pagination in a connection. */
778 +export const LabelsPageInfoPageInfo = Schema.Struct({
779 + /** When paginating forwards, are there more items? */
780 + hasNextPage: Schema.Boolean
781 +})
782 +export interface LabelsPageInfoPageInfo extends Schema.Struct.Type<typeof LabelsPageInfoPageInfo.fields> {}
783 +
784 +/** A label for categorizing Issues, Pull Requests, Milestones, or Discussions with a given Repository. */
785 +export const RepositoryLabelsNodesLabel = Schema.Struct({
786 + /** Identifies the label name. */
787 + name: Schema.String,
788 + /** Identifies the label color. */
789 + color: Schema.String,
790 + /** A brief description of this label. */
791 + description: Schema.NullOr(Schema.String)
792 +})
793 +export interface RepositoryLabelsNodesLabel extends Schema.Struct.Type<typeof RepositoryLabelsNodesLabel.fields> {}
794 +
795 +/** The connection type for Label. */
796 +export const RepositoryLabelsLabelConnection = Schema.Struct({
797 + /** Information to aid in pagination. */
798 + pageInfo: LabelsPageInfoPageInfo,
799 + /** A list of nodes. */
800 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(RepositoryLabelsNodesLabel)))
801 +})
802 +export interface RepositoryLabelsLabelConnection extends Schema.Struct.Type<typeof RepositoryLabelsLabelConnection.fields> {}
803 +
804 +/** A list of users. */
805 +export const AssignableUsersUserConnection = Schema.Struct({
806 + /** Information to aid in pagination. */
807 + pageInfo: LabelsPageInfoPageInfo,
808 + /** A list of nodes. */
809 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(AssigneesNodesUser)))
810 +})
811 +export interface AssignableUsersUserConnection extends Schema.Struct.Type<typeof AssignableUsersUserConnection.fields> {}
812 +
813 +/** A repository contains the content for a project. */
814 +export const IssueCandidatesRepositoryRepository = Schema.Struct({
815 + /** A list of labels associated with the repository. */
816 + labels: Schema.NullOr(RepositoryLabelsLabelConnection),
817 + /** A list of users that can be assigned to issues in this repository. */
818 + assignableUsers: AssignableUsersUserConnection
819 +})
820 +export interface IssueCandidatesRepositoryRepository extends Schema.Struct.Type<typeof IssueCandidatesRepositoryRepository.fields> {}
821 +
822 +/** `query IssueCandidates` */
823 +export const IssueCandidates = GraphQL.query("IssueCandidates", {
824 + document: {
825 + variables: [
826 + { name: "owner", body: "String!" },
827 + { name: "name", body: "String!" }
828 + ],
829 + selections: [
830 + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){labels(first:100){pageInfo{hasNextPage}nodes{name color description}}assignableUsers(first:100){pageInfo{hasNextPage}nodes{login name avatarUrl}}}"] }
831 + ],
832 + fragments: []
833 + },
834 + variables: {
835 + owner: Schema.String,
836 + name: Schema.String
837 + },
838 + result: Schema.Struct({
839 + /** Lookup a given repository by the owner and repository name. */
840 + repository: Schema.NullOr(IssueCandidatesRepositoryRepository)
841 + })
842 +})
843 +export declare namespace IssueCandidates {
844 + export type Variables = typeof IssueCandidates.variables.Type
845 + export type Result = typeof IssueCandidates.result.Type
846 +}
847 +
848 +/** Represents a Git blob. */
849 +export const Blob = Schema.Struct({
850 + __typename: Schema.Literal("Blob"),
851 + /** UTF8 text data or null if the Blob is binary */
852 + text: Schema.NullOr(Schema.String),
853 + /** Indicates whether the contents is truncated */
854 + isTruncated: Schema.Boolean
855 +})
856 +export interface Blob extends Schema.Struct.Type<typeof Blob.fields> {}
857 +
858 +/** Represents a Git object. */
859 +export const ObjectGitObjectOther = Schema.Struct({
860 + __typename: GraphQL.otherTypename<Shared.Typename.GitObject>()(["Blob"])
861 +})
862 +export interface ObjectGitObjectOther extends Schema.Struct.Type<typeof ObjectGitObjectOther.fields> {}
863 +
864 +/** Represents a Git tree entry. */
865 +export const TreeEntry = Schema.Struct({
866 + /** Entry file name. */
867 + name: Schema.String,
868 + /** Entry file object. */
869 + object: Schema.NullOr(Schema.Union([
870 + Blob,
871 + ObjectGitObjectOther
872 + ]))
873 +})
874 +export interface TreeEntry extends Schema.Struct.Type<typeof TreeEntry.fields> {}
875 +
876 +/** Represents a Git tree. */
877 +export const Tree = Schema.Struct({
878 + __typename: Schema.Literal("Tree"),
879 + /** A list of tree entries. */
880 + entries: Schema.NullOr(Schema.Array(TreeEntry))
881 +})
882 +export interface Tree extends Schema.Struct.Type<typeof Tree.fields> {}
883 +
884 +/** Represents a Git object. */
885 +export const TemplateDirectoryGitObjectOther = Schema.Struct({
886 + __typename: GraphQL.otherTypename<Shared.Typename.GitObject>()(["Tree"])
887 +})
888 +export interface TemplateDirectoryGitObjectOther extends Schema.Struct.Type<typeof TemplateDirectoryGitObjectOther.fields> {}
889 +
890 +/** A list of users. */
891 +export const IssueTemplatesAssigneesUserConnection = Schema.Struct({
892 + /** A list of nodes. */
893 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(ViewerUser)))
894 +})
895 +export interface IssueTemplatesAssigneesUserConnection extends Schema.Struct.Type<typeof IssueTemplatesAssigneesUserConnection.fields> {}
896 +
897 +/** The connection type for Label. */
898 +export const IssueTemplatesLabelsLabelConnection = Schema.Struct({
899 + /** A list of nodes. */
900 + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(LabelLabel)))
901 +})
902 +export interface IssueTemplatesLabelsLabelConnection extends Schema.Struct.Type<typeof IssueTemplatesLabelsLabelConnection.fields> {}
903 +
904 +/** A repository issue template. */
905 +export const IssueTemplate = Schema.Struct({
906 + /** The template filename. */
907 + filename: Schema.String,
908 + /** The template name. */
909 + name: Schema.String,
910 + /** The template purpose. */
911 + about: Schema.NullOr(Schema.String),
912 + /** The suggested issue title. */
913 + title: Schema.NullOr(Schema.String),
914 + /** The suggested issue body. */
915 + body: Schema.NullOr(Schema.String),
916 + /** The suggested assignees. */
917 + assignees: IssueTemplatesAssigneesUserConnection,
918 + /** The suggested issue labels */
919 + labels: Schema.NullOr(IssueTemplatesLabelsLabelConnection)
920 +})
921 +export interface IssueTemplate extends Schema.Struct.Type<typeof IssueTemplate.fields> {}
922 +
923 +/** A repository contains the content for a project. */
924 +export const IssueTemplatesRepositoryRepository = Schema.Struct({
925 + /** A Git object in the repository */
926 + templateDirectory: Schema.NullOr(Schema.Union([
927 + Tree,
928 + TemplateDirectoryGitObjectOther
929 + ])),
930 + /** Returns a list of issue templates associated to the repository */
931 + issueTemplates: Schema.NullOr(Schema.Array(IssueTemplate))
932 +})
933 +export interface IssueTemplatesRepositoryRepository extends Schema.Struct.Type<typeof IssueTemplatesRepositoryRepository.fields> {}
934 +
935 +/** `query IssueTemplates` */
936 +export const IssueTemplates = GraphQL.query("IssueTemplates", {
937 + document: {
938 + variables: [
939 + { name: "owner", body: "String!" },
940 + { name: "name", body: "String!" }
941 + ],
942 + selections: [
943 + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){templateDirectory:object(expression:\"HEAD:.github/ISSUE_TEMPLATE\"){__typename...on Tree{entries{name object{__typename...on Blob{text isTruncated}}}}}issueTemplates{filename name about title body assignees(first:25){nodes{login}}labels(first:50){nodes{name}}}}"] }
944 + ],
945 + fragments: []
946 + },
947 + variables: {
948 + owner: Schema.String,
949 + name: Schema.String
950 + },
951 + result: Schema.Struct({
952 + /** Lookup a given repository by the owner and repository name. */
953 + repository: Schema.NullOr(IssueTemplatesRepositoryRepository)
954 + })
955 +})
956 +export declare namespace IssueTemplates {
957 + export type Variables = typeof IssueTemplates.variables.Type
958 + export type Result = typeof IssueTemplates.result.Type
959 +}
960 +
961 +/** `query IssueViewer` */
962 +export const IssueViewer = GraphQL.query("IssueViewer", {
963 + document: {
964 + variables: [],
965 + selections: [
966 + { name: "viewer", body: ["{login}"] }
967 + ],
968 + fragments: []
969 + },
970 + result: Schema.Struct({
971 + /** The currently authenticated user. */
972 + viewer: ViewerUser
973 + })
974 +})
975 +export declare namespace IssueViewer {
976 + export type Variables = typeof IssueViewer.variables.Type
977 + export type Result = typeof IssueViewer.result.Type
978 +}
979 +
980 +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */
981 +export const IssueCollectionsRepositoryIssueIssue = Schema.Struct({
982 + /** A list of labels associated with the object. */
983 + labels: Schema.NullOr(IssueLabelsLabelConnection),
984 + /** A list of Users assigned to this object. */
985 + assignees: IssueAssigneesUserConnection
986 +})
987 +export interface IssueCollectionsRepositoryIssueIssue extends Schema.Struct.Type<typeof IssueCollectionsRepositoryIssueIssue.fields> {}
988 +
989 +/** A repository contains the content for a project. */
990 +export const IssueCollectionsRepositoryRepository = Schema.Struct({
991 + /** Returns a single issue from the current repository by number. */
992 + issue: Schema.NullOr(IssueCollectionsRepositoryIssueIssue)
993 +})
994 +export interface IssueCollectionsRepositoryRepository extends Schema.Struct.Type<typeof IssueCollectionsRepositoryRepository.fields> {}
995 +
996 +/** `query IssueCollections` */
997 +export const IssueCollections = GraphQL.query("IssueCollections", {
998 + document: {
999 + variables: [
1000 + { name: "owner", body: "String!" },
1001 + { name: "name", body: "String!" },
1002 + { name: "number", body: "Int!" },
1003 + { name: "labelsCursor", body: "String" },
1004 + { name: "assigneesCursor", body: "String" }
1005 + ],
1006 + selections: [
1007 + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){issue(number:$", "number", "){labels(first:100 after:$", "labelsCursor", "){pageInfo{hasNextPage endCursor}nodes{name color}}assignees(first:100 after:$", "assigneesCursor", "){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}}}"] }
1008 + ],
1009 + fragments: []
1010 + },
1011 + variables: {
1012 + owner: Schema.String,
1013 + name: Schema.String,
1014 + number: Shared.Int,
1015 + labelsCursor: Schema.optional(Schema.NullOr(Schema.String)),
1016 + assigneesCursor: Schema.optional(Schema.NullOr(Schema.String))
1017 + },
1018 + result: Schema.Struct({
1019 + /** Lookup a given repository by the owner and repository name. */
1020 + repository: Schema.NullOr(IssueCollectionsRepositoryRepository)
1021 + })
1022 +})
1023 +export declare namespace IssueCollections {
1024 + export type Variables = typeof IssueCollections.variables.Type
1025 + export type Result = typeof IssueCollections.result.Type
1026 +}
1027 +
1028 +/** Every operation in issues.graphql. */
1029 +export const IssuesGraphQLGroup = GraphQLGroup.make(IssueSearch, IssueDetail, IssueComments, IssueNodeId, IssueCommentScope, IssueCandidates, IssueTemplates, IssueViewer, IssueCollections)
pnpm-lock.yaml
+3
@@ -2405,6 +2405,9 @@ importers:
2405 effect:
2406 specifier: 4.1.3
2407 version: 4.1.3
2408 + yaml:
2409 + specifier: ^2.9.0
2410 + version: 2.9.0
2411 devDependencies:
2412 '@effect/graphql-generator':
2413 specifier: 'catalog:'