Open History to see the last commit
1import {
2 IssueTrackerKind,
3 type IssueCapabilities,
4 type IssueComment,
5 type IssueEvent,
6 type IssueState,
7} from "@t3tools/contracts";
8import {
9 IssueTrackerError,
10 type IssueScopeTarget,
11 type IssueTrackerApi,
12 type TrackerIssueSummary,
13} from "@t3tools/source-control-core/server/IssueTracker";
14import * as Effect from "effect/Effect";
15import * as Schema from "effect/Schema";
16
17import { definition } from "../shared/definition.ts";
18import * as TanStackSourceApi from "./TanStackSourceApi.ts";
19import * as Hosts from "./tanStackSourceHosts.ts";
20import * as Json from "./tanStackSourceJson.ts";
21import * as Listing from "./tanStackSourceListing.ts";
22
23const KIND = IssueTrackerKind.make(definition.kind);
24
25const CAPABILITIES: IssueCapabilities = {
26 create: true,
27 edit: true,
28 comment: true,
29 labels: true,
30 assignees: true,
31 // Source documents no REST route for reactions.
32 reactions: false,
33 templates: false,
34 linkedPullRequests: true,
35 events: true,
36 search: true,
37};
38
39const OPEN: IssueState = { category: "open", name: "Open" };
40const CLOSED: IssueState = { category: "closed", name: "Closed" };
41const STATES: ReadonlyArray<IssueState> = [OPEN, CLOSED];
42
43/** Source keeps no update time; the newest timeline entry stands in where one was read. */
44const EVENT_KINDS: Readonly<Record<string, IssueEvent["kind"]>> = {
45 closed: "closed",
46 reopened: "reopened",
47 labeled: "labeled",
48 unlabeled: "unlabeled",
49 assigned: "assigned",
50 unassigned: "unassigned",
51 renamed: "renamed",
52 linked_from: "referenced",
53 referenced: "referenced",
54};
55
56const Assignee = Schema.Union([Schema.String, Schema.Struct({ username: Schema.String })]);
57const IssueRow = Schema.Struct({
58 number: Schema.Int,
59 title: Schema.String,
60 state: Schema.String,
61 author: Schema.NullOr(Schema.String),
62 labels: Schema.optional(Schema.Array(Schema.String)),
63 assignees: Schema.optional(Schema.Array(Assignee)),
64 comments: Schema.optional(Schema.Int),
65 createdAt: Schema.Finite,
66 moderation: Schema.optional(Schema.String),
67});
68type IssueRow = typeof IssueRow.Type;
69const IssueRows = Schema.Struct({
70 items: Schema.Array(IssueRow),
71 next: Schema.NullOr(Schema.String),
72});
73
74const TimelineEntry = Schema.Struct({
75 id: Schema.optional(Schema.Int),
76 comment: Schema.optional(Schema.NullOr(Schema.String)),
77 event: Schema.optional(Schema.String),
78 author: Schema.optional(Schema.NullOr(Schema.String)),
79 actor: Schema.optional(Schema.NullOr(Schema.String)),
80 at: Schema.Finite,
81 moderation: Schema.optional(Schema.String),
82});
83const IssueDetail = Schema.Struct({
84 ...IssueRow.fields,
85 kind: Schema.optional(Schema.String),
86 body: Schema.NullOr(Schema.String),
87 locked: Schema.optional(Schema.Boolean),
88 timeline: Schema.Array(TimelineEntry),
89 next: Schema.NullOr(Schema.String),
90 fixedBy: Schema.optional(
91 Schema.Array(Schema.Struct({ number: Schema.Int, title: Schema.String, state: Schema.String })),
92 ),
93});
94type IssueDetail = typeof IssueDetail.Type;
95const Created = Schema.Struct({ number: Schema.Int });
96const PAGE_LIMIT = 5;
97
98const issueUrl = (host: string, scope: string, number: number | string) =>
99 `https://${host}/@${scope}/issues/${number}`;
100const assigneeLogin = (assignee: typeof Assignee.Type) =>
101 typeof assignee === "string" ? assignee : assignee.username;
102const pullState = (state: string) =>
103 state === "merged"
104 ? ("merged" as const)
105 : state === "closed"
106 ? ("closed" as const)
107 : ("open" as const);
108
109export const make = Effect.gen(function* () {
110 const api = yield* TanStackSourceApi.TanStackSourceApi;
111
112 const failure = (operation: string, detail: string, cause?: unknown) =>
113 new IssueTrackerError({
114 tracker: KIND,
115 operation,
116 reason: "failed",
117 detail,
118 ...(cause === undefined ? {} : { cause }),
119 });
120
121 const base = (operation: string, input: IssueScopeTarget) => {
122 const repository = Hosts.tanStackSourceRepositoryPath(input.scope);
123 return Hosts.tanStackSourceHost(input.host) !== null && repository !== null
124 ? Effect.succeed(`/repos/${repository}`)
125 : Effect.fail(failure(operation, "TanStack Source issues live in owner/name repositories."));
126 };
127
128 /** The key is checked here because it becomes a path segment of the request. */
129 const issuePath = (operation: string, input: IssueScopeTarget & { readonly key: string }) =>
130 /^[1-9]\d*$/u.test(input.key)
131 ? Effect.map(base(operation, input), (path) => `${path}/issues/${input.key}`)
132 : Effect.fail(failure(operation, "TanStack Source issue keys are numbers."));
133
134 const send = (
135 operation: string,
136 input: Pick<IssueScopeTarget, "host">,
137 request: Omit<TanStackSourceApi.TanStackSourceApiRequest, "operation" | "host">,
138 ) =>
139 api.request({ ...request, host: input.host, operation }).pipe(
140 Effect.mapError(
141 (error) =>
142 new IssueTrackerError({
143 tracker: KIND,
144 operation,
145 // A refused write is the request's, not a reason to switch the tracker off.
146 reason: error.reason === "forbidden" ? "failed" : error.reason,
147 detail: error.detail,
148 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
149 cause: error,
150 }),
151 ),
152 );
153
154 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
155 operation: string,
156 input: Pick<IssueScopeTarget, "host">,
157 request: Omit<TanStackSourceApi.TanStackSourceApiRequest, "operation" | "host">,
158 schema: S,
159 ) =>
160 send(operation, input, request).pipe(
161 Effect.flatMap((raw) =>
162 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
163 Effect.mapError((cause) =>
164 failure(operation, "TanStack Source returned an unreadable response.", cause),
165 ),
166 ),
167 ),
168 );
169
170 const toSummary = (
171 issue: IssueRow,
172 input: IssueScopeTarget,
173 updatedAt = issue.createdAt,
174 ): TrackerIssueSummary => {
175 const created = Json.iso(issue.createdAt);
176 return {
177 key: String(issue.number),
178 displayKey: `#${issue.number}`,
179 title: issue.title.trim() || `#${issue.number}`,
180 url: issueUrl(input.host, input.scope, issue.number),
181 author: Json.toActor(issue.author, input.host),
182 state: issue.state === "closed" ? CLOSED : OPEN,
183 createdAt: created,
184 updatedAt: Json.iso(Math.max(updatedAt, issue.createdAt)),
185 // Source reports no close time.
186 closedAt: null,
187 assignees: (issue.assignees ?? []).flatMap((assignee) => {
188 const actor = Json.toActor(assigneeLogin(assignee), input.host);
189 return actor === null ? [] : [actor];
190 }),
191 labels: (issue.labels ?? []).map((name) => ({ name, color: null })),
192 commentCount: issue.comments ?? 0,
193 };
194 };
195
196 const toConversation = (detail: IssueDetail, input: IssueScopeTarget & { key: string }) => {
197 const comments: Array<IssueComment> = [];
198 const events: Array<IssueEvent> = [];
199 for (const [index, entry] of detail.timeline.entries()) {
200 if (entry.moderation !== undefined && entry.moderation !== "visible") continue;
201 if (entry.event !== undefined) {
202 const kind = EVENT_KINDS[entry.event];
203 if (kind !== undefined)
204 events.push({
205 id: `${input.key}:${entry.at}:${index}`,
206 kind,
207 actor: Json.toActor(entry.actor ?? null, input.host),
208 createdAt: Json.iso(entry.at),
209 detail: null,
210 });
211 continue;
212 }
213 if (entry.id === undefined) continue;
214 comments.push({
215 id: String(entry.id),
216 author: Json.toActor(entry.author ?? null, input.host),
217 body: entry.comment ?? "",
218 createdAt: Json.iso(entry.at),
219 url: `${issueUrl(input.host, input.scope, input.key)}#comment-${entry.id}`,
220 });
221 }
222 return { comments, events };
223 };
224
225 const readDetail = Effect.fn("TanStackSourceIssueTracker.readDetail")(function* (
226 operation: string,
227 input: IssueScopeTarget & { readonly key: string },
228 ) {
229 const path = yield* issuePath(operation, input);
230 return yield* read(operation, input, { path }, IssueDetail);
231 });
232
233 const tracker: IssueTrackerApi = {
234 kind: KIND,
235 capabilities: CAPABILITIES,
236 getViewer: (input) =>
237 read("getViewer", input, { path: "/user" }, Json.SourceUser).pipe(
238 Effect.map((user) => user.username),
239 ),
240
241 listIssues: Effect.fn("TanStackSourceIssueTracker.listIssues")(function* (input) {
242 const path = yield* base("listIssues", input);
243 const query = new URLSearchParams();
244 if (input.query?.trim()) query.set("query", input.query.trim());
245 // Source narrows by one label; the rest are matched below.
246 const [label, ...moreLabels] = input.labels ?? [];
247 if (label !== undefined) query.set("label", label);
248 // An explicit assignee narrows on Source; being assigned too is checked on the rows.
249 if (input.assignee !== undefined) query.set("assignee", input.assignee);
250 else if (input.involvement === "assigned") query.set("assignee", "@me");
251 if (input.involvement === "authored") query.set("author", "@me");
252 if (input.involvement === "mentioned") query.set("mention", "@me");
253 const viewer = input.involvement === "all" ? null : input.viewer.toLowerCase();
254 const listing = yield* Listing.readMerged({
255 states: input.state === "all" ? ["open", "closed"] : [input.state],
256 cursor: input.cursor,
257 limit: Math.max(1, input.limit),
258 maxPages: PAGE_LIMIT,
259 readPage: (state, page) => {
260 const params = new URLSearchParams(query);
261 params.set("state", state);
262 if (page !== null) params.set("cursor", page);
263 return read("listIssues", input, { path: `${path}/issues?${params}` }, IssueRows);
264 },
265 keep: (issue) =>
266 (issue.moderation === undefined || issue.moderation === "visible") &&
267 moreLabels.every((name) => issue.labels?.includes(name) === true) &&
268 (input.involvement !== "assigned" ||
269 input.assignee === undefined ||
270 (issue.assignees ?? []).some(
271 (assignee) => assigneeLogin(assignee).toLowerCase() === viewer,
272 )),
273 });
274 return {
275 items: listing.items.map((issue) => toSummary(issue, input)),
276 nextCursor: listing.next,
277 };
278 }),
279
280 getIssue: Effect.fn("TanStackSourceIssueTracker.getIssue")(function* (input) {
281 const [detail, viewer] = yield* Effect.all(
282 [
283 readDetail("getIssue", input),
284 tracker.getViewer(input).pipe(Effect.orElseSucceed(() => null)),
285 ],
286 { concurrency: 2 },
287 );
288 if (detail.kind === "pull")
289 return yield* failure("getIssue", `#${input.key} is a pull request, not an issue.`);
290 const { comments, events } = toConversation(detail, input);
291 const latest = detail.timeline.reduce((newest, entry) => Math.max(newest, entry.at), 0);
292 return {
293 ...toSummary(detail, input, latest),
294 commentCount: detail.comments ?? comments.length,
295 body: detail.body ?? "",
296 viewer,
297 viewerPermissions: {
298 setState: viewer !== null,
299 comment: viewer !== null && detail.locked !== true,
300 edit: viewer !== null,
301 labels: viewer !== null,
302 assignees: viewer !== null,
303 },
304 states: STATES,
305 comments,
306 commentsCursor: detail.next,
307 events,
308 linkedPullRequests: (detail.fixedBy ?? []).map((pull) => ({
309 repository: input.scope,
310 number: pull.number,
311 title: pull.title.trim() || `#${pull.number}`,
312 url: Json.pullUrl(input.host, input.scope, pull.number),
313 state: pullState(pull.state),
314 isDraft: false,
315 closesIssue: true,
316 })),
317 };
318 }),
319
320 getComments: Effect.fn("TanStackSourceIssueTracker.getComments")(function* (input) {
321 const path = yield* issuePath("getComments", input);
322 const detail = yield* read(
323 "getComments",
324 input,
325 { path: `${path}?${new URLSearchParams({ cursor: input.cursor })}` },
326 IssueDetail,
327 );
328 return { comments: toConversation(detail, input).comments, nextCursor: detail.next };
329 }),
330
331 create: Effect.fn("TanStackSourceIssueTracker.create")(function* (input) {
332 const path = yield* base("create", input);
333 const created = yield* read(
334 "create",
335 input,
336 {
337 method: "POST",
338 path: `${path}/issues`,
339 body: {
340 title: input.title,
341 ...(input.body.trim() === "" ? {} : { body: input.body }),
342 },
343 },
344 Created,
345 );
346 const key = String(created.number);
347 // Source takes labels and assignees on their own routes.
348 if (input.labels.length > 0)
349 yield* send("create", input, {
350 method: "PUT",
351 path: `${path}/issues/${key}/labels`,
352 body: { labels: input.labels },
353 });
354 if (input.assignees.length > 0)
355 yield* send("create", input, {
356 method: "PUT",
357 path: `${path}/issues/${key}/assignees`,
358 body: { assignees: input.assignees },
359 });
360 return { key, displayKey: `#${key}`, url: issueUrl(input.host, input.scope, key) };
361 }),
362
363 comment: Effect.fn("TanStackSourceIssueTracker.comment")(function* (input) {
364 const path = yield* issuePath("comment", input);
365 yield* send("comment", input, {
366 method: "POST",
367 path: `${path}/comments`,
368 body: { body: input.body },
369 });
370 }),
371
372 update: Effect.fn("TanStackSourceIssueTracker.update")(function* (input) {
373 const path = yield* issuePath("update", input);
374 if (input.title !== undefined || input.body !== undefined)
375 yield* send("update", input, {
376 method: "PATCH",
377 path,
378 body: {
379 ...(input.title === undefined ? {} : { title: input.title }),
380 ...(input.body === undefined ? {} : { body: input.body }),
381 },
382 });
383 if (input.labels !== undefined)
384 yield* send("update", input, {
385 method: "PUT",
386 path: `${path}/labels`,
387 body: { labels: input.labels },
388 });
389 if (input.assignees !== undefined)
390 yield* send("update", input, {
391 method: "PUT",
392 path: `${path}/assignees`,
393 body: { assignees: input.assignees },
394 });
395 }),
396
397 setState: Effect.fn("TanStackSourceIssueTracker.setState")(function* (input) {
398 const state = STATES.find((candidate) => candidate.name === input.state);
399 if (state === undefined)
400 return yield* failure("setState", `TanStack Source issues have no "${input.state}" state.`);
401 const path = yield* issuePath("setState", input);
402 yield* send("setState", input, {
403 method: "PATCH",
404 path,
405 body: { state: state.category },
406 });
407 }),
408
409 listCandidates: Effect.fn("TanStackSourceIssueTracker.listCandidates")(function* (input) {
410 const path = yield* base("listCandidates", input);
411 const [labels, viewer] = yield* Effect.all(
412 [
413 read("listCandidates", input, { path: `${path}/labels` }, Json.SourceLabels),
414 tracker.getViewer(input).pipe(Effect.orElseSucceed(() => null)),
415 ],
416 { concurrency: 2 },
417 );
418 const self = Json.toActor(viewer, input.host);
419 return {
420 labels: labels.map((label) => ({
421 name: label.name,
422 color: label.color,
423 description: label.description ?? null,
424 })),
425 // Source lists no collaborators, so only the viewer is offered.
426 assignees: self === null ? [] : [{ ...self, id: self.login }],
427 truncated: true,
428 };
429 }),
430 };
431 return tracker;
432});