The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 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 | const OPEN: IssueState = { category: "open", name: "Open" }; |
| 63 | const COMPLETED: IssueState = { |
| 64 | category: "closed", |
| 65 | name: "Completed", |
| 66 | closeReason: "completed", |
| 67 | }; |
| 68 | const NOT_PLANNED: IssueState = { |
| 69 | category: "closed", |
| 70 | name: "Not planned", |
| 71 | closeReason: "not-planned", |
| 72 | }; |
| 73 | |
| 74 | const DUPLICATE: IssueState = { category: "closed", name: "Duplicate", closeReason: "duplicate" }; |
| 75 | |
| 76 | /** What an issue can be moved to: open, or closed for one of the reasons GitHub records. */ |
| 77 | export const ISSUE_STATES: ReadonlyArray<IssueState> = [OPEN, COMPLETED, NOT_PLANNED, DUPLICATE]; |
| 78 | |
| 79 | /** GitHub uses uppercase close reasons; an open issue has `""` or `REOPENED`. */ |
| 80 | function toIssueState( |
| 81 | state: string | null | undefined, |
| 82 | stateReason: string | null | undefined, |
| 83 | ): IssueState { |
| 84 | if (state?.trim().toUpperCase() !== "CLOSED") return OPEN; |
| 85 | const reason = stateReason?.trim().toUpperCase(); |
| 86 | if (reason === "COMPLETED") return COMPLETED; |
| 87 | if (reason === "NOT_PLANNED") return NOT_PLANNED; |
| 88 | return reason === "DUPLICATE" ? DUPLICATE : { category: "closed", name: "Closed" }; |
| 89 | } |
| 90 | |
| 91 | function toSummary(raw: Omit<Issues.NodesIssue, "__typename">): TrackerIssueSummary { |
| 92 | return { |
| 93 | key: String(raw.number), |
| 94 | displayKey: `#${raw.number}`, |
| 95 | title: raw.title, |
| 96 | url: raw.url, |
| 97 | author: toActor(raw.author), |
| 98 | state: toIssueState(raw.state, raw.stateReason), |
| 99 | createdAt: raw.createdAt, |
| 100 | updatedAt: raw.updatedAt, |
| 101 | closedAt: trimmed(raw.closedAt), |
| 102 | assignees: toActors(raw.assignees?.nodes), |
| 103 | labels: toLabels(raw.labels?.nodes), |
| 104 | commentCount: Math.max(0, raw.comments?.totalCount ?? 0), |
| 105 | }; |
| 106 | } |
| 107 | |
| 108 | function toPullRequestState(value: string | null | undefined): PullRequestState { |
| 109 | switch (value?.trim().toUpperCase()) { |
| 110 | case "MERGED": |
| 111 | return "merged"; |
| 112 | case "CLOSED": |
| 113 | return "closed"; |
| 114 | default: |
| 115 | return "open"; |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | function toLinkedPullRequest( |
| 120 | raw: Reference | null | undefined, |
| 121 | closesIssue: boolean, |
| 122 | ): IssueLinkedPullRequest | null { |
| 123 | if (raw == null) return null; |
| 124 | const { title, url, number } = raw; |
| 125 | const repository = raw.repository.nameWithOwner; |
| 126 | return { |
| 127 | repository, |
| 128 | number, |
| 129 | title, |
| 130 | url, |
| 131 | state: toPullRequestState(raw.state), |
| 132 | isDraft: raw.isDraft ?? false, |
| 133 | closesIssue, |
| 134 | }; |
| 135 | } |
| 136 | |
| 137 | /** The change GitHub recorded, or null for a kind this page has no vocabulary for. */ |
| 138 | function toEventFields( |
| 139 | raw: TimelineItem, |
| 140 | ): { readonly kind: IssueEventKind; readonly detail: string | null } | null { |
| 141 | switch (raw.__typename) { |
| 142 | case "ClosedEvent": |
| 143 | return { kind: "closed", detail: null }; |
| 144 | case "ReopenedEvent": |
| 145 | return { kind: "reopened", detail: null }; |
| 146 | case "LabeledEvent": |
| 147 | return { kind: "labeled", detail: trimmed(raw.label?.name) }; |
| 148 | case "UnlabeledEvent": |
| 149 | return { kind: "unlabeled", detail: trimmed(raw.label?.name) }; |
| 150 | case "AssignedEvent": |
| 151 | return { |
| 152 | kind: "assigned", |
| 153 | detail: trimmed( |
| 154 | raw.assignee != null && "login" in raw.assignee ? raw.assignee.login : null, |
| 155 | ), |
| 156 | }; |
| 157 | case "UnassignedEvent": |
| 158 | return { |
| 159 | kind: "unassigned", |
| 160 | detail: trimmed( |
| 161 | raw.assignee != null && "login" in raw.assignee ? raw.assignee.login : null, |
| 162 | ), |
| 163 | }; |
| 164 | case "RenamedTitleEvent": |
| 165 | return { kind: "renamed", detail: trimmed(raw.currentTitle) }; |
| 166 | case "CrossReferencedEvent": { |
| 167 | const repository = trimmed( |
| 168 | raw.source != null && "repository" in raw.source |
| 169 | ? raw.source.repository.nameWithOwner |
| 170 | : null, |
| 171 | ); |
| 172 | const number = raw.source != null && "number" in raw.source ? raw.source.number : 0; |
| 173 | return { |
| 174 | kind: "referenced", |
| 175 | detail: repository === null || number <= 0 ? null : `${repository}#${number}`, |
| 176 | }; |
| 177 | } |
| 178 | default: |
| 179 | return null; |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | function toComments( |
| 184 | raw: Comments | null | undefined, |
| 185 | viewer: string | null, |
| 186 | ): ReadonlyArray<IssueComment> { |
| 187 | return (raw?.nodes ?? []).flatMap((comment) => { |
| 188 | const id = trimmed(comment?.id); |
| 189 | if (comment == null || id === null) return []; |
| 190 | return [ |
| 191 | { |
| 192 | id, |
| 193 | author: toActor(comment.author), |
| 194 | body: comment.body ?? "", |
| 195 | createdAt: comment.createdAt, |
| 196 | url: trimmed(comment.url), |
| 197 | reactions: toReactions(comment.reactionGroups, viewer), |
| 198 | }, |
| 199 | ]; |
| 200 | }); |
| 201 | } |
| 202 | |
| 203 | function previousCursorOf( |
| 204 | pageInfo: { readonly hasPreviousPage: boolean; readonly startCursor: string | null } | undefined, |
| 205 | ) { |
| 206 | return pageInfo?.hasPreviousPage === true ? pageInfo.startCursor : null; |
| 207 | } |
| 208 | |
| 209 | function toViewerPermissions(raw: { |
| 210 | readonly viewerPermission?: string | null | undefined; |
| 211 | readonly issue: { |
| 212 | readonly state: string; |
| 213 | readonly viewerCanUpdate: boolean; |
| 214 | readonly viewerCanClose: boolean; |
| 215 | readonly viewerCanReopen: boolean; |
| 216 | } | null; |
| 217 | }): IssueViewerPermissions { |
| 218 | const canUpdate = raw.issue?.viewerCanUpdate !== false; |
| 219 | const canTriage = ["ADMIN", "MAINTAIN", "WRITE", "TRIAGE"].includes( |
| 220 | raw.viewerPermission?.trim().toUpperCase() ?? "", |
| 221 | ); |
| 222 | return { |
| 223 | // Triage may close and reopen an issue it may not edit, so this is not `viewerCanUpdate`. |
| 224 | setState: |
| 225 | raw.issue === null || |
| 226 | (raw.issue.state === "CLOSED" ? raw.issue.viewerCanReopen : raw.issue.viewerCanClose), |
| 227 | comment: true, |
| 228 | edit: canUpdate, |
| 229 | labels: canTriage, |
| 230 | assignees: canTriage, |
| 231 | }; |
| 232 | } |
| 233 | |
| 234 | interface GitHubIssueDetail extends TrackerIssueSummary { |
| 235 | readonly body: string; |
| 236 | readonly viewer: string | null; |
| 237 | readonly viewerPermissions: IssueViewerPermissions; |
| 238 | readonly states: ReadonlyArray<IssueState>; |
| 239 | readonly reactions: ReturnType<typeof toReactions>; |
| 240 | readonly comments: ReadonlyArray<IssueComment>; |
| 241 | readonly commentsCursor: string | null; |
| 242 | readonly events: ReadonlyArray<IssueEvent>; |
| 243 | readonly linkedPullRequests: ReadonlyArray<IssueLinkedPullRequest>; |
| 244 | } |
| 245 | |
| 246 | /** Null for a number that names no issue the viewer can see. */ |
| 247 | export function toIssueDetail({ |
| 248 | viewer: rawViewer, |
| 249 | repository, |
| 250 | }: Issues.IssueDetail.Result): GitHubIssueDetail | null { |
| 251 | const issue = repository?.issue; |
| 252 | if (issue == null) return null; |
| 253 | const viewer = trimmed(rawViewer?.login); |
| 254 | |
| 255 | // Closing references lead; a cross-reference seen twice is filed under the stronger relation. |
| 256 | const links = new Map<string, IssueLinkedPullRequest>(); |
| 257 | for (const node of issue.closedByPullRequestsReferences?.nodes ?? []) { |
| 258 | const link = toLinkedPullRequest(node, true); |
| 259 | if (link !== null) links.set(`${link.repository.toLowerCase()}#${link.number}`, link); |
| 260 | } |
| 261 | const events: IssueEvent[] = []; |
| 262 | for (const entry of issue.timelineItems?.nodes ?? []) { |
| 263 | if (entry === null) continue; |
| 264 | const item = entry; |
| 265 | if (item.__typename === "CrossReferencedEvent") { |
| 266 | const link = |
| 267 | item.source.__typename === "PullRequest" ? toLinkedPullRequest(item.source, false) : null; |
| 268 | const linkKey = link === null ? null : `${link.repository.toLowerCase()}#${link.number}`; |
| 269 | if (link !== null && linkKey !== null && !links.has(linkKey)) links.set(linkKey, link); |
| 270 | } |
| 271 | const fields = toEventFields(item); |
| 272 | const id = trimmed("id" in item ? item.id : null); |
| 273 | const createdAt = trimmed("createdAt" in item ? item.createdAt : null); |
| 274 | if (fields === null || id === null || createdAt === null) continue; |
| 275 | events.push({ id, ...fields, actor: toActor("actor" in item ? item.actor : null), createdAt }); |
| 276 | } |
| 277 | return { |
| 278 | ...toSummary(issue), |
| 279 | body: issue.body ?? "", |
| 280 | viewer, |
| 281 | viewerPermissions: toViewerPermissions({ |
| 282 | viewerPermission: repository?.viewerPermission, |
| 283 | issue, |
| 284 | }), |
| 285 | states: ISSUE_STATES, |
| 286 | reactions: toReactions(issue.reactionGroups, viewer), |
| 287 | comments: toComments(issue.comments, viewer), |
| 288 | commentsCursor: previousCursorOf(issue.comments?.pageInfo), |
| 289 | events, |
| 290 | linkedPullRequests: [...links.values()], |
| 291 | }; |
| 292 | } |
| 293 | |
| 294 | export function toIssueSearch({ search }: Issues.IssueSearch.Result) { |
| 295 | return { |
| 296 | items: (search.nodes ?? []).flatMap((node) => |
| 297 | node !== null && node.__typename === "Issue" ? [toSummary(node)] : [], |
| 298 | ), |
| 299 | nextCursor: search.pageInfo.hasNextPage ? search.pageInfo.endCursor : null, |
| 300 | }; |
| 301 | } |
| 302 | |
| 303 | export function toIssueComments({ viewer, repository }: Issues.IssueComments.Result) { |
| 304 | const comments = repository?.issue?.comments; |
| 305 | return { |
| 306 | comments: toComments(comments, viewer.login), |
| 307 | nextCursor: previousCursorOf(comments?.pageInfo), |
| 308 | }; |
| 309 | } |
| 310 | |
| 311 | export function toIssueCandidates( |
| 312 | repository: NonNullable<Issues.IssueCandidates.Result["repository"]>, |
| 313 | ) { |
| 314 | const { labels, assignableUsers } = repository; |
| 315 | return { |
| 316 | labels: (labels?.nodes ?? []).flatMap((label) => |
| 317 | label === null |
| 318 | ? [] |
| 319 | : [ |
| 320 | { |
| 321 | name: label.name, |
| 322 | color: label.color, |
| 323 | description: label.description, |
| 324 | }, |
| 325 | ], |
| 326 | ), |
| 327 | assignees: toActors(assignableUsers.nodes).map((actor) => ({ ...actor, id: actor.login })), |
| 328 | truncated: |
| 329 | labels?.pageInfo.hasNextPage === true || assignableUsers.pageInfo.hasNextPage === true, |
| 330 | }; |
| 331 | } |
| 332 | |
| 333 | export function toIssueTemplates( |
| 334 | repository: NonNullable<Issues.IssueTemplates.Result["repository"]>, |
| 335 | ): ReadonlyArray<IssueTemplate> { |
| 336 | return (repository.issueTemplates ?? []).flatMap((template) => { |
| 337 | if (template === null || template.filename.trim() === "") return []; |
| 338 | return [ |
| 339 | { |
| 340 | key: template.filename, |
| 341 | name: template.name, |
| 342 | about: template.about ?? "", |
| 343 | title: template.title ?? "", |
| 344 | body: template.body ?? "", |
| 345 | labels: (template.labels?.nodes ?? []).flatMap((node) => node?.name ?? []), |
| 346 | assignees: (template.assignees.nodes ?? []).flatMap((node) => node?.login ?? []), |
| 347 | }, |
| 348 | ]; |
| 349 | }); |
| 350 | } |
| 351 | |
| 352 | const decodeCreatedIssue = decodeJsonResult( |
| 353 | Schema.Struct({ number: Schema.Int, html_url: TrimmedNonEmptyString }), |
| 354 | ); |
| 355 | |
| 356 | const decodeIssueMetadata = decodeJsonResult( |
| 357 | Schema.Struct({ |
| 358 | labels: Schema.Array(Schema.Union([Schema.String, Schema.Struct({ name: Schema.String })])), |
| 359 | assignees: Schema.Array(Schema.Struct({ login: Schema.String })), |
| 360 | }), |
| 361 | ); |
| 362 | |
| 363 | /** The labels and assignees a REST issue answer reports, lower case for comparison. */ |
| 364 | export function decodeIssueMetadataJson(raw: string) { |
| 365 | return Result.map(decodeIssueMetadata(raw), (issue) => ({ |
| 366 | labels: issue.labels.map((label) => |
| 367 | (typeof label === "string" ? label : label.name).trim().toLowerCase(), |
| 368 | ), |
| 369 | assignees: issue.assignees.map((assignee) => assignee.login.trim().toLowerCase()), |
| 370 | })); |
| 371 | } |
| 372 | |
| 373 | export function decodeCreatedIssueJson(raw: string) { |
| 374 | return Result.map(decodeCreatedIssue(raw), (issue) => ({ |
| 375 | number: issue.number, |
| 376 | url: issue.html_url, |
| 377 | })); |
| 378 | } |