Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4
5import * as Redacted from "effect/Redacted";
6import * as Schema from "effect/Schema";
7import { HttpClient, HttpClientResponse } from "effect/http";
8import { IssueTemplateList } from "@t3tools/contracts";
9import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
10import * as GitHubCredentials from "./GitHubCredentials.ts";
11import * as GitHubRest from "./GitHubRest.ts";
12import * as GitHubQuota from "./GitHubQuota.ts";
13import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
14import * as GitHubIssueTracker from "./GitHubIssueTracker.ts";
15
16const 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 pageInfo: { hasNextPage: true, endCursor: "links-next" },
84 nodes: [
85 {
86 number: 50,
87 title: "fix(web): keep composer focus",
88 url: "https://github.com/acme/web/pull/50",
89 state: "MERGED",
90 isDraft: false,
91 repository: { nameWithOwner: "acme/web" },
92 },
93 ],
94 },
95 timelineItems: {
96 nodes: [
97 {
98 __typename: "LabeledEvent",
99 id: "LE_1",
100 createdAt: "2026-07-01T01:00:00Z",
101 actor: { __typename: "User", login: "theo", avatarUrl: "https://avatars/theo" },
102 label: { name: "bug" },
103 },
104 {
105 __typename: "CrossReferencedEvent",
106 id: "CRE_1",
107 createdAt: "2026-07-02T01:00:00Z",
108 actor: { __typename: "User", login: "julius", avatarUrl: "https://avatars/julius" },
109 source: {
110 __typename: "PullRequest",
111 number: 50,
112 title: "fix(web): keep composer focus",
113 url: "https://github.com/acme/web/pull/50",
114 state: "MERGED",
115 isDraft: false,
116 repository: { nameWithOwner: "acme/web" },
117 },
118 },
119 { __typename: "MentionedEvent", id: "ME_1", createdAt: "2026-07-02T02:00:00Z" },
120 {
121 __typename: "ClosedEvent",
122 id: "CE_1",
123 createdAt: "2026-07-03T00:00:00Z",
124 actor: null,
125 },
126 ],
127 },
128 },
129 },
130 },
131});
132
133/** A repository GitHub has not given issue statuses yet. */
134const NO_STATUSES = {
135 data: {
136 repository: { planningStatuses: null, issue: { viewerCanSetStatus: true, status: null } },
137 },
138};
139
140const decodeVariables = Schema.decodeUnknownSync(
141 Schema.fromJsonString(
142 Schema.Struct({
143 query: Schema.String,
144 variables: Schema.Record(Schema.String, Schema.Unknown),
145 }),
146 ),
147);
148
149function transport(httpClient: HttpClient.HttpClient) {
150 return GitHubRest.layer.pipe(
151 Layer.provideMerge(
152 Layer.mergeAll(
153 GitHubQuota.layer,
154 SourceControlRateLimit.layer,
155 Layer.mock(GitHubCredentials.GitHubCredentials)({
156 saved: () => Effect.succeedNone,
157 get: (host) =>
158 Effect.succeed({
159 host,
160 token: Redacted.make("test-token"),
161 source: "gh" as const,
162 fingerprint: "test",
163 }),
164 }),
165 Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
166 enabled: false,
167 token: () => Effect.succeedNone,
168 invalidate: () => Effect.void,
169 }),
170 Layer.succeed(HttpClient.HttpClient, httpClient),
171 ),
172 ),
173 );
174}
175
176function tracker(onRequest: (variables: unknown) => void, templateRepository?: unknown) {
177 return GitHubIssueTracker.make.pipe(
178 Effect.provide(
179 transport(
180 HttpClient.make((request) => {
181 if (request.body._tag !== "Uint8Array")
182 return Effect.die("Expected a GraphQL JSON request.");
183 const { query, variables } = decodeVariables(new TextDecoder().decode(request.body.body));
184 const statusRead = query.includes("query IssueStatuses");
185 if (!statusRead) onRequest(variables);
186 const body = statusRead
187 ? JSON.stringify(NO_STATUSES)
188 : templateRepository !== undefined
189 ? JSON.stringify({ data: { repository: templateRepository } })
190 : "labelsCursor" in variables
191 ? JSON.stringify({
192 data: {
193 repository: {
194 issue: {
195 labels: {
196 pageInfo: { hasNextPage: false, endCursor: null },
197 nodes: [{ name: "needs repro", color: "ffffff" }],
198 },
199 closedByPullRequestsReferences: {
200 pageInfo: { hasNextPage: false, endCursor: null },
201 nodes: [
202 {
203 number: 61,
204 title: "fix(web): restore focus after paste",
205 url: "https://github.com/acme/web/pull/61",
206 state: "OPEN",
207 isDraft: true,
208 repository: { nameWithOwner: "acme/web" },
209 },
210 ],
211 },
212 },
213 },
214 },
215 })
216 : DETAIL_RESPONSE;
217 return Effect.succeed(
218 HttpClientResponse.fromWeb(
219 request,
220 new Response(body, {
221 headers: { "content-type": "application/json" },
222 }),
223 ),
224 );
225 }),
226 ),
227 ),
228 );
229}
230
231const encodeTemplateList = Schema.encodeSync(IssueTemplateList);
232
233const decodeBody = Schema.decodeUnknownSync(
234 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
235);
236
237describe("GitHubIssueTracker", () => {
238 it.effect("reads only the fields needed to link a GitHub issue and rejects missing issues", () =>
239 Effect.gen(function* () {
240 const requests: unknown[] = [];
241 const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" };
242 const url = "https://github.com/acme/web/issues/42";
243 const found = yield* tracker((input) => requests.push(input), {
244 issue: { number: 42, title: "Fixture issue", url },
245 });
246 expect(yield* found.getIssueLink(target)).toEqual({
247 displayKey: "#42",
248 title: "Fixture issue",
249 url,
250 });
251
252 const missing = yield* tracker((input) => requests.push(input), { issue: null });
253 expect(yield* Effect.flip(missing.getIssueLink(target))).toMatchObject({
254 reason: "not-found",
255 });
256 expect(requests).toEqual([
257 { owner: "acme", name: "web", number: 42 },
258 { owner: "acme", name: "web", number: 42 },
259 ]);
260 }),
261 );
262
263 it.effect("writes an issue lifecycle without mutating pull requests or foreign comments", () =>
264 Effect.gen(function* () {
265 const writes: unknown[] = [];
266 let issueState: { state: string; stateReason: string | null } = {
267 state: "OPEN",
268 stateReason: null,
269 };
270 const http = HttpClient.make((request) => {
271 if (request.body._tag !== "Uint8Array") return Effect.die("Expected a JSON request.");
272 const text = new TextDecoder().decode(request.body.body);
273 let response: unknown = {};
274 if (request.url === "https://api.github.com/graphql") {
275 const { query, variables } = decodeVariables(text);
276 expect(request.method).toBe("POST");
277 const operation = query.match(/(?:query|mutation)\s+(\w+)/)?.[1];
278 if (operation === "IssueStatuses") {
279 response = NO_STATUSES;
280 } else if (operation === "IssueNodeId" || operation === "IssueCommentScope") {
281 expect(variables).toMatchObject({ owner: "acme", name: "web" });
282 response = {
283 data: {
284 repository: {
285 issue: variables["number"] === 42 ? { id: "I_42", ...issueState } : null,
286 },
287 ...(operation === "IssueCommentScope"
288 ? { node: { __typename: "IssueComment", issue: { id: "I_other" } } }
289 : {}),
290 },
291 };
292 } else {
293 expect(["AddReaction", "RemoveReaction"]).toContain(operation);
294 expect(variables).toEqual({ subjectId: "I_42", content: "THUMBS_UP" });
295 writes.push(operation);
296 response = {
297 data: {
298 [operation === "AddReaction" ? "addReaction" : "removeReaction"]: {
299 reaction: { content: "THUMBS_UP" },
300 },
301 },
302 };
303 }
304 } else {
305 const body = decodeBody(text);
306 writes.push([request.method, request.url, body]);
307 if (typeof body["state"] === "string") {
308 issueState = {
309 state: body["state"].toUpperCase(),
310 stateReason:
311 typeof body["state_reason"] === "string"
312 ? body["state_reason"].toUpperCase()
313 : null,
314 };
315 }
316 if (request.url.endsWith("/issues")) {
317 response = { number: 42, html_url: "https://github.com/acme/web/issues/42" };
318 } else if (request.method === "PATCH" && body["title"] === "Dropped") {
319 // What GitHub answers a caller without triage access: success, metadata untouched.
320 response = { labels: [{ name: "Bug" }], assignees: [] };
321 } else if (request.method === "PATCH") {
322 response = { labels: [], assignees: [] };
323 }
324 }
325 return Effect.succeed(
326 HttpClientResponse.fromWeb(
327 request,
328 new Response(JSON.stringify(response), {
329 headers: { "content-type": "application/json" },
330 }),
331 ),
332 );
333 });
334 const api = yield* GitHubIssueTracker.make.pipe(Effect.provide(transport(http)));
335 const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" };
336 expect(
337 yield* api.create({
338 ...target,
339 title: "Fixture",
340 body: "Body",
341 labels: ["bug"],
342 assignees: ["octocat"],
343 }),
344 ).toEqual({
345 key: "42",
346 displayKey: "#42",
347 url: "https://github.com/acme/web/issues/42",
348 });
349 yield* api.comment({ ...target, body: "Comment" });
350 yield* api.update({ ...target, title: "Updated", body: "Edited", labels: [], assignees: [] });
351 expect(
352 yield* Effect.flip(api.update({ ...target, title: "Dropped", labels: ["bug", "p1"] })),
353 ).toMatchObject({ operation: "update", reason: "failed" });
354 yield* api.update({ ...target, title: "Dropped", labels: ["bug"], assignees: [] });
355 expect(yield* Effect.flip(api.setState({ ...target, state: "closed" }))).toMatchObject({
356 operation: "setState",
357 reason: "failed",
358 });
359 yield* api.setState({ ...target, state: "Not planned" });
360 // GitHub ignores a new reason on a closed issue, so it is refused instead of sent.
361 expect(
362 yield* api.setState({ ...target, state: "Completed" }).pipe(Effect.result),
363 ).toMatchObject({ _tag: "Failure", failure: { operation: "setState", reason: "failed" } });
364 yield* api.setState({ ...target, state: "Open" });
365 yield* api.setState({ ...target, state: "Duplicate" });
366 yield* api.setState({ ...target, state: "Open" });
367 yield* api.setReaction({ ...target, content: "thumbs-up", reacted: true });
368 yield* api.setReaction({ ...target, content: "thumbs-up", reacted: false });
369
370 const pullRequest = { ...target, key: "50" };
371 expect(
372 yield* api.update({ ...pullRequest, title: "Do not edit" }).pipe(Effect.result),
373 ).toMatchObject({ _tag: "Failure", failure: { operation: "update", reason: "not-found" } });
374 expect(
375 yield* api.setState({ ...pullRequest, state: "Completed" }).pipe(Effect.result),
376 ).toMatchObject({
377 _tag: "Failure",
378 failure: { operation: "setState", reason: "not-found" },
379 });
380 expect(
381 yield* api.comment({ ...pullRequest, body: "Do not comment" }).pipe(Effect.result),
382 ).toMatchObject({ _tag: "Failure", failure: { operation: "comment", reason: "not-found" } });
383 expect(
384 yield* Effect.flip(
385 api.setReaction({
386 ...target,
387 subjectId: "IC_other",
388 content: "thumbs-up",
389 reacted: true,
390 }),
391 ),
392 ).toMatchObject({ operation: "setReaction", reason: "failed" });
393
394 expect(writes).toEqual([
395 [
396 "POST",
397 "https://api.github.com/repos/acme/web/issues",
398 { title: "Fixture", body: "Body", labels: ["bug"], assignees: ["octocat"] },
399 ],
400 ["POST", "https://api.github.com/repos/acme/web/issues/42/comments", { body: "Comment" }],
401 [
402 "PATCH",
403 "https://api.github.com/repos/acme/web/issues/42",
404 { title: "Updated", body: "Edited", labels: [], assignees: [] },
405 ],
406 [
407 "PATCH",
408 "https://api.github.com/repos/acme/web/issues/42",
409 { title: "Dropped", labels: ["bug", "p1"] },
410 ],
411 [
412 "PATCH",
413 "https://api.github.com/repos/acme/web/issues/42",
414 { title: "Dropped", labels: ["bug"], assignees: [] },
415 ],
416 [
417 "PATCH",
418 "https://api.github.com/repos/acme/web/issues/42",
419 { state: "closed", state_reason: "not_planned" },
420 ],
421 ["PATCH", "https://api.github.com/repos/acme/web/issues/42", { state: "open" }],
422 [
423 "PATCH",
424 "https://api.github.com/repos/acme/web/issues/42",
425 { state: "closed", state_reason: "duplicate" },
426 ],
427 ["PATCH", "https://api.github.com/repos/acme/web/issues/42", { state: "open" }],
428 "AddReaction",
429 "RemoveReaction",
430 ]);
431 }),
432 );
433
434 it.effect("moves an issue between the repository's issue statuses", () =>
435 Effect.gen(function* () {
436 const status = (id: string, name: string, key: string, stateReason: string | null) => ({
437 id,
438 name,
439 category: { key, state: stateReason === null ? "OPEN" : "CLOSED", stateReason },
440 });
441 const planningStatuses = {
442 nodes: [
443 status("IS_1", "Backlog", "backlog", null),
444 status("IS_2", "In review", "started", null),
445 status("IS_3", "Done", "completed", "COMPLETED"),
446 status("IS_4", "Duplicate", "duplicate", "DUPLICATE"),
447 ],
448 };
449 const fixture = JSON.parse(DETAIL_RESPONSE);
450 const page = { hasNextPage: false, endCursor: null };
451 Object.assign(fixture.data.repository.issue, {
452 state: "OPEN",
453 stateReason: null,
454 labels: { pageInfo: page, nodes: [] },
455 closedByPullRequestsReferences: { pageInfo: page, nodes: [] },
456 });
457 const writes: unknown[] = [];
458 const http = HttpClient.make((request) => {
459 if (request.body._tag !== "Uint8Array") return Effect.die("Expected a JSON request.");
460 const text = new TextDecoder().decode(request.body.body);
461 let response: unknown = {};
462 if (request.url === "https://api.github.com/graphql") {
463 const { query, variables } = decodeVariables(text);
464 const operation = query.match(/(?:query|mutation)\s+(\w+)/)?.[1];
465 if (operation === "IssueDetail") {
466 response = fixture;
467 } else if (operation === "IssueStatuses") {
468 response = {
469 data: {
470 repository: {
471 planningStatuses,
472 issue: { viewerCanSetStatus: false, status: planningStatuses.nodes[1] },
473 },
474 },
475 };
476 } else if (operation === "IssueNodeId") {
477 response = {
478 data: {
479 repository: { issue: { id: "I_42", state: "OPEN", stateReason: null } },
480 },
481 };
482 } else {
483 writes.push([operation, variables]);
484 response = { data: { setIssueStatus: { clientMutationId: null } } };
485 }
486 } else {
487 writes.push([request.method, request.url, decodeBody(text)]);
488 }
489 return Effect.succeed(
490 HttpClientResponse.fromWeb(
491 request,
492 new Response(JSON.stringify(response), {
493 headers: { "content-type": "application/json" },
494 }),
495 ),
496 );
497 });
498 const api = yield* GitHubIssueTracker.make.pipe(Effect.provide(transport(http)));
499 const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" };
500
501 const issue = yield* api.getIssue(target);
502 expect(issue.state).toEqual({ category: "open", name: "In review" });
503 expect(issue.states).toEqual([
504 { category: "open", name: "Backlog" },
505 { category: "open", name: "In review" },
506 { category: "closed", name: "Done", closeReason: "completed" },
507 { category: "closed", name: "Duplicate", closeReason: "duplicate" },
508 ]);
509 expect(issue.viewerPermissions.setState).toBe(false);
510
511 yield* api.setState({ ...target, state: "Backlog" });
512 // Closing as a duplicate through a status needs the original issue, so it closes over REST.
513 yield* api.setState({ ...target, state: "Duplicate" });
514 expect(yield* Effect.flip(api.setState({ ...target, state: "Open" }))).toMatchObject({
515 operation: "setState",
516 reason: "failed",
517 });
518 expect(writes).toEqual([
519 ["SetIssueStatus", { issueId: "I_42", statusId: "IS_1" }],
520 [
521 "PATCH",
522 "https://api.github.com/repos/acme/web/issues/42",
523 { state: "closed", state_reason: "duplicate" },
524 ],
525 ]);
526 }),
527 );
528
529 it.effect("never names issue statuses to an Enterprise server", () =>
530 Effect.gen(function* () {
531 const queries: string[] = [];
532 const http = HttpClient.make((request) => {
533 if (request.body._tag !== "Uint8Array") return Effect.die("Expected a JSON request.");
534 const { query } = decodeVariables(new TextDecoder().decode(request.body.body));
535 queries.push(query);
536 const page = { hasNextPage: false, endCursor: null };
537 const detail = JSON.parse(DETAIL_RESPONSE);
538 Object.assign(detail.data.repository.issue, {
539 labels: { pageInfo: page, nodes: [] },
540 closedByPullRequestsReferences: { pageInfo: page, nodes: [] },
541 });
542 const body = query.includes("query IssueSearch")
543 ? { data: { search: { pageInfo: page, nodes: [] } } }
544 : detail;
545 return Effect.succeed(
546 HttpClientResponse.fromWeb(
547 request,
548 new Response(JSON.stringify(body), {
549 headers: { "content-type": "application/json" },
550 }),
551 ),
552 );
553 });
554 const api = yield* GitHubIssueTracker.make.pipe(Effect.provide(transport(http)));
555 const target = { cwd: "/w", host: "ghe.example.com", scope: "acme/web" };
556 yield* api.listIssues({
557 ...target,
558 state: "open",
559 involvement: "all",
560 sort: "updated",
561 limit: 10,
562 });
563 yield* api.getIssue({ ...target, key: "42" });
564 expect(queries).toHaveLength(2);
565 for (const query of queries) expect(query).not.toMatch(/status|planningStatuses/i);
566 }),
567 );
568
569 it.effect("lists issues without statuses when GitHub refuses the status fields", () =>
570 Effect.gen(function* () {
571 const operations: string[] = [];
572 const http = HttpClient.make((request) => {
573 if (request.body._tag !== "Uint8Array") return Effect.die("Expected a JSON request.");
574 const { query } = decodeVariables(new TextDecoder().decode(request.body.body));
575 const operation = query.match(/query\s+(\w+)/)?.[1] ?? "";
576 operations.push(operation);
577 const body =
578 operation === "IssueSearchWithStatus"
579 ? {
580 data: null,
581 errors: [{ message: "Field 'status' doesn't exist on type 'Issue'" }],
582 }
583 : {
584 data: { search: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] } },
585 };
586 return Effect.succeed(
587 HttpClientResponse.fromWeb(
588 request,
589 new Response(JSON.stringify(body), {
590 headers: { "content-type": "application/json" },
591 }),
592 ),
593 );
594 });
595 const api = yield* GitHubIssueTracker.make.pipe(Effect.provide(transport(http)));
596 const listing = yield* api.listIssues({
597 cwd: "/w",
598 host: "github.com",
599 scope: "acme/web",
600 state: "open",
601 involvement: "all",
602 sort: "updated",
603 limit: 10,
604 });
605 expect(listing.items).toEqual([]);
606 expect(operations).toEqual(["IssueSearchWithStatus", "IssueSearch"]);
607 }),
608 );
609
610 it.effect("asks search for the labels, assignee and order a listing names", () =>
611 Effect.gen(function* () {
612 const seen: unknown[] = [];
613 const api = yield* tracker((variables) => seen.push(variables));
614 // The canned answer is not a search result; only the query sent matters here.
615 yield* api
616 .listIssues({
617 cwd: "/w",
618 host: "github.com",
619 scope: "acme/web",
620 state: "open",
621 involvement: "all",
622 labels: ['needs "repro"'],
623 assignee: "theo",
624 sort: "created",
625 limit: 10,
626 })
627 .pipe(Effect.exit);
628 expect(seen[0]).toMatchObject({
629 q: 'is:issue repo:acme/web is:open label:"needs \\"repro\\"" assignee:"theo" sort:created-desc',
630 });
631 }),
632 );
633
634 it.effect("offers YAML issue forms when blank issues are disabled", () =>
635 Effect.gen(function* () {
636 const form = {
637 __typename: "Blob",
638 isTruncated: false,
639 text: `name: Bug report
640description: Report broken behavior.
641title: "[Bug]: "
642labels: [bug, needs-triage]
643assignees: "octocat, theo"
644body:
645 - type: markdown
646 attributes:
647 value: Search existing issues first.
648 - type: checkboxes
649 attributes:
650 label: Before submitting
651 options:
652 - label: I searched existing issues.
653 required: true
654 - type: dropdown
655 attributes:
656 label: Area
657 description: Which part is affected?
658 options: [Web, Server]
659 default: 1
660 validations:
661 required: true
662 - type: textarea
663 attributes:
664 label: Steps to reproduce
665 placeholder: Start the app.
666 - type: input
667 attributes:
668 label: Version
669 value: main
670 - type: upload
671 attributes:
672 label: Supporting files
673 description: Redact secrets before uploading.
674`,
675 };
676 const config = {
677 __typename: "Blob",
678 isTruncated: false,
679 text: '"blank_issues_enabled": false # use a template',
680 };
681 const repository = {
682 issueTemplates: [],
683 templateDirectory: {
684 __typename: "Tree",
685 entries: [
686 { name: "config.yml", object: config },
687 { name: "bug_report.yml", object: form },
688 {
689 name: "empty_name.yml",
690 object: { ...form, text: 'name: ""\ndescription: Empty name\nbody: []' },
691 },
692 {
693 name: "blank_name.yml",
694 object: { ...form, text: 'name: " "\ndescription: Blank name\nbody: []' },
695 },
696 {
697 name: "invalid.yml",
698 object: { ...form, text: "name: Missing required metadata\nbody: []" },
699 },
700 ],
701 },
702 };
703 const api = yield* tracker(() => {}, repository);
704 const input = { cwd: "/w", host: "github.com", scope: "acme/web" };
705 const result = yield* api.listTemplates!(input);
706 expect(encodeTemplateList(result)).toEqual(result);
707 expect(result.blankIssuesEnabled).toBe(false);
708 expect(result.templates).toHaveLength(1);
709 expect(result.templates[0]).toMatchObject({
710 key: "bug_report.yml",
711 name: "Bug report",
712 about: "Report broken behavior.",
713 title: "[Bug]: ",
714 labels: ["bug", "needs-triage"],
715 assignees: ["octocat", "theo"],
716 });
717 expect(result.templates[0]?.body).toBe(`Search existing issues first.
718
719### Before submitting
720
721- [ ] I searched existing issues. (required)
722
723### Area
724
725Which part is affected?
726
727Required.
728
729Choose one:
730
731- Web
732- Server (default)
733
734### Steps to reproduce
735
736Example:
737> Start the app.
738
739### Version
740
741main
742
743### Supporting files
744
745Redact secrets before uploading.`);
746 config.isTruncated = true;
747 expect(yield* Effect.flip(api.listTemplates!(input))).toMatchObject({
748 reason: "failed",
749 detail: "GitHub returned incomplete issue template contents.",
750 });
751 }),
752 );
753
754 it.effect("maps a detail read to the neutral issue shape", () =>
755 Effect.gen(function* () {
756 const seen: unknown[] = [];
757 const api = yield* tracker((variables) => {
758 seen.push(variables);
759 });
760 const issue = yield* api.getIssue({
761 cwd: "/w",
762 host: "github.com",
763 scope: "acme/web",
764 key: "42",
765 });
766 expect(seen).toEqual([
767 { owner: "acme", name: "web", number: 42 },
768 {
769 owner: "acme",
770 name: "web",
771 number: 42,
772 labelsCursor: "labels-next",
773 assigneesCursor: null,
774 closingPullRequestsCursor: "links-next",
775 withLabels: true,
776 withAssignees: false,
777 withClosingPullRequests: true,
778 },
779 ]);
780 expect(issue).toMatchObject({
781 key: "42",
782 displayKey: "#42",
783 title: "Composer loses focus",
784 body: "Typing in the composer drops focus after a paste.",
785 state: { category: "closed", name: "Duplicate", closeReason: "duplicate" },
786 states: [
787 { category: "open", name: "Open" },
788 { category: "closed", name: "Completed", closeReason: "completed" },
789 { category: "closed", name: "Not planned", closeReason: "not-planned" },
790 { category: "closed", name: "Duplicate", closeReason: "duplicate" },
791 ],
792 author: {
793 login: "octocat",
794 name: "Octo Cat",
795 avatarUrl: "https://avatars/octocat",
796 },
797 assignees: [{ login: "theo" }],
798 labels: [
799 { name: "bug", color: "d73a4a" },
800 { name: "needs repro", color: "ffffff" },
801 ],
802 commentCount: 3,
803 viewer: "julius",
804 // Triage may label, assign, close and reopen; `viewerCanUpdate: false` withholds edits.
805 viewerPermissions: {
806 setState: true,
807 edit: false,
808 labels: true,
809 assignees: true,
810 comment: true,
811 },
812 commentsCursor: "Y3Vyc29y",
813 });
814 // The viewer is left out of `actors` and shown as "You"; an empty group is dropped.
815 expect(issue.comments[0]?.reactions).toEqual([
816 { content: "thumbs-up", count: 2, actors: ["theo"], viewerHasReacted: true },
817 ]);
818 // The closing reference wins over the cross-reference sighting of the same pull request.
819 expect(issue.linkedPullRequests).toEqual([
820 {
821 repository: "acme/web",
822 number: 50,
823 title: "fix(web): keep composer focus",
824 url: "https://github.com/acme/web/pull/50",
825 state: "merged",
826 isDraft: false,
827 closesIssue: true,
828 },
829 // A closing reference past the first page, with no timeline sighting, still shows.
830 {
831 repository: "acme/web",
832 number: 61,
833 title: "fix(web): restore focus after paste",
834 url: "https://github.com/acme/web/pull/61",
835 state: "open",
836 isDraft: true,
837 closesIssue: true,
838 },
839 ]);
840 // An event kind this page has no vocabulary for is dropped rather than guessed at.
841 expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
842 ["labeled", "bug"],
843 ["referenced", "acme/web#50"],
844 ["closed", null],
845 ]);
846 // A cross-reference keeps what a surface needs to open its source, not only a label.
847 expect(issue.events.find((event) => event.kind === "referenced")).toMatchObject({
848 reference: {
849 repository: "acme/web",
850 number: 50,
851 kind: "pull-request",
852 url: "https://github.com/acme/web/pull/50",
853 },
854 });
855 }),
856 );
857});