The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /** |
| 2 | * Linear as an issue tracker. A scope is a team key (`ENG`) and an issue key its identifier |
| 3 | * (`ENG-123`). A workflow state is closed when its type is `completed` or `canceled`, so closing |
| 4 | * picks the team's first state of that type, as Linear's own "Done" and "Canceled" do. |
| 5 | */ |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Schema from "effect/Schema"; |
| 8 | import { |
| 9 | type IssueActor, |
| 10 | type IssueCapabilities, |
| 11 | type IssueComment, |
| 12 | type IssueEvent, |
| 13 | type IssueExternalTemplate, |
| 14 | type IssueLinkedPullRequest, |
| 15 | type IssueReaction, |
| 16 | type IssueReactionContent, |
| 17 | type IssueState, |
| 18 | type IssueTemplate, |
| 19 | type IssueViewerPermissions, |
| 20 | type StandaloneIssueTrackerDescriptor, |
| 21 | } from "@t3tools/contracts"; |
| 22 | import { |
| 23 | IssueTrackerError, |
| 24 | type IssueInvolvementFilter, |
| 25 | type StandaloneIssueTrackerApi, |
| 26 | type TrackerIssueSummary, |
| 27 | } from "@t3tools/source-control-core/server/IssueTracker"; |
| 28 | |
| 29 | import { LINEAR_HOST, parseLinearIssueUrl } from "../shared/issueUrl.ts"; |
| 30 | import * as LinearApi from "./LinearApi.ts"; |
| 31 | |
| 32 | const DESCRIPTOR: StandaloneIssueTrackerDescriptor = { |
| 33 | tracker: LinearApi.KIND, |
| 34 | displayName: "Linear", |
| 35 | host: LINEAR_HOST, |
| 36 | scopeNoun: "team", |
| 37 | credential: { |
| 38 | label: "Personal API key", |
| 39 | helpUrl: "https://linear.app/settings/account/security", |
| 40 | }, |
| 41 | }; |
| 42 | |
| 43 | /** |
| 44 | * Only the two categories here: Linear's actual columns differ per team and are offered to the |
| 45 | * detail page through `getIssue`'s state, while the service's `setState` guard needs a fixed list. |
| 46 | * The driver maps `open` to the team's default state and `closed` to its first completed state, |
| 47 | * with `canceled` as the close reason for its first canceled state. |
| 48 | */ |
| 49 | const CAPABILITIES: IssueCapabilities = { |
| 50 | create: true, |
| 51 | edit: true, |
| 52 | comment: true, |
| 53 | labels: true, |
| 54 | assignees: true, |
| 55 | reactions: true, |
| 56 | templates: true, |
| 57 | linkedPullRequests: true, |
| 58 | events: true, |
| 59 | search: true, |
| 60 | }; |
| 61 | |
| 62 | /** Everything granted: Linear's API reports no per-issue permissions and refuses with a message. */ |
| 63 | const VIEWER_PERMISSIONS: IssueViewerPermissions = { |
| 64 | setState: true, |
| 65 | comment: true, |
| 66 | edit: true, |
| 67 | labels: true, |
| 68 | assignees: true, |
| 69 | }; |
| 70 | |
| 71 | const COMMENTS_PAGE = 50; |
| 72 | const CLOSED_STATE_TYPES = ["completed", "canceled", "duplicate"]; |
| 73 | /** The order Linear lists a workflow in; within a type, its own `position` decides. */ |
| 74 | const STATE_TYPE_ORDER = [ |
| 75 | "triage", |
| 76 | "backlog", |
| 77 | "unstarted", |
| 78 | "started", |
| 79 | "completed", |
| 80 | "canceled", |
| 81 | "duplicate", |
| 82 | ]; |
| 83 | |
| 84 | function inWorkflowOrder( |
| 85 | states: ReadonlyArray<LinearApi.LinearWorkflowState>, |
| 86 | ): ReadonlyArray<LinearApi.LinearWorkflowState> { |
| 87 | return states.toSorted( |
| 88 | (a, b) => |
| 89 | STATE_TYPE_ORDER.indexOf(a.type) - STATE_TYPE_ORDER.indexOf(b.type) || |
| 90 | (a.position ?? 0) - (b.position ?? 0), |
| 91 | ); |
| 92 | } |
| 93 | |
| 94 | /** Linear reacts with the emoji itself; GitHub's names are the contract's vocabulary. */ |
| 95 | const EMOJI_BY_CONTENT: Record<IssueReactionContent, string> = { |
| 96 | "thumbs-up": "👍", |
| 97 | "thumbs-down": "👎", |
| 98 | laugh: "😄", |
| 99 | hooray: "🎉", |
| 100 | confused: "😕", |
| 101 | heart: "❤️", |
| 102 | rocket: "🚀", |
| 103 | eyes: "👀", |
| 104 | }; |
| 105 | /** Linear takes the emoji on a write and answers with its short name, so a read knows both. */ |
| 106 | const EMOJI_NAME_BY_CONTENT: Record<IssueReactionContent, string> = { |
| 107 | "thumbs-up": "+1", |
| 108 | "thumbs-down": "-1", |
| 109 | laugh: "smile", |
| 110 | hooray: "tada", |
| 111 | confused: "confused", |
| 112 | heart: "heart", |
| 113 | rocket: "rocket", |
| 114 | eyes: "eyes", |
| 115 | }; |
| 116 | const CONTENT_BY_EMOJI = new Map( |
| 117 | [EMOJI_BY_CONTENT, EMOJI_NAME_BY_CONTENT].flatMap((spellings) => |
| 118 | Object.entries(spellings).map( |
| 119 | ([content, emoji]) => [emoji, content as IssueReactionContent] as const, |
| 120 | ), |
| 121 | ), |
| 122 | ); |
| 123 | |
| 124 | /** `ENG-123`, or null for anything that is not a Linear identifier. */ |
| 125 | function parseIdentifier(key: string): string | null { |
| 126 | return /^[A-Za-z][A-Za-z0-9]*-[1-9]\d*$/.test(key.trim()) ? key.trim().toUpperCase() : null; |
| 127 | } |
| 128 | |
| 129 | function toState(state: LinearApi.LinearWorkflowState): IssueState { |
| 130 | return CLOSED_STATE_TYPES.includes(state.type) |
| 131 | ? { category: "closed", name: state.name, closeReason: state.type } |
| 132 | : { category: "open", name: state.name }; |
| 133 | } |
| 134 | |
| 135 | /** |
| 136 | * The login is Linear's handle (its `displayName`, unique in a workspace), which is what people |
| 137 | * see and what filters and writes are named by; the id stays inside this adapter. |
| 138 | */ |
| 139 | function toActor(user: LinearApi.LinearUser): IssueActor { |
| 140 | return { |
| 141 | login: user.displayName || user.id, |
| 142 | name: user.name ?? null, |
| 143 | avatarUrl: user.avatarUrl ?? null, |
| 144 | }; |
| 145 | } |
| 146 | |
| 147 | type LinearBot = NonNullable<LinearApi.LinearIssue["botActor"]>; |
| 148 | |
| 149 | /** |
| 150 | * Who did it: the person, else the integration that acted (GitHub moving an issue, a form filing |
| 151 | * one), which Linear reports beside an empty user. |
| 152 | */ |
| 153 | function actorOf(user: LinearApi.LinearUser | null, bot: LinearBot | null): IssueActor | null { |
| 154 | if (user !== null) return toActor(user); |
| 155 | const name = bot?.userDisplayName ?? bot?.name; |
| 156 | if (bot == null || !name) return null; |
| 157 | return { isBot: true, login: bot.name ?? name, name, avatarUrl: bot.avatarUrl ?? null }; |
| 158 | } |
| 159 | |
| 160 | /** How a user shows in a picker and an event: display name first, falling back to the id. */ |
| 161 | function userName(user: LinearApi.LinearUser): string { |
| 162 | return user.displayName ?? user.name ?? user.email ?? user.id; |
| 163 | } |
| 164 | |
| 165 | /** Linear's connections report no totals, so a listing shows no comment count. */ |
| 166 | function toSummary(issue: LinearApi.LinearIssue, commentCount = 0): TrackerIssueSummary { |
| 167 | return { |
| 168 | key: issue.identifier, |
| 169 | displayKey: issue.identifier, |
| 170 | title: issue.title, |
| 171 | url: issue.url, |
| 172 | author: actorOf(issue.creator, issue.botActor), |
| 173 | state: toState(issue.state), |
| 174 | createdAt: issue.createdAt, |
| 175 | updatedAt: issue.updatedAt, |
| 176 | closedAt: issue.completedAt ?? issue.canceledAt ?? null, |
| 177 | assignees: issue.assignee === null ? [] : [toActor(issue.assignee)], |
| 178 | labels: issue.labels.nodes.map((label) => ({ name: label.name, color: label.color })), |
| 179 | commentCount, |
| 180 | }; |
| 181 | } |
| 182 | |
| 183 | function toReactions( |
| 184 | reactions: ReadonlyArray<LinearApi.LinearReaction>, |
| 185 | viewerId: string | null, |
| 186 | ): IssueReaction[] { |
| 187 | const grouped = new Map<IssueReactionContent, IssueReaction>(); |
| 188 | for (const reaction of reactions) { |
| 189 | const content = CONTENT_BY_EMOJI.get(reaction.emoji); |
| 190 | if (content === undefined) continue; |
| 191 | const mine = reaction.user !== null && reaction.user.id === viewerId; |
| 192 | const existing = grouped.get(content); |
| 193 | const actor = reaction.user === null || mine ? [] : [userName(reaction.user)]; |
| 194 | grouped.set( |
| 195 | content, |
| 196 | existing === undefined |
| 197 | ? { content, count: 1, actors: actor, viewerHasReacted: mine } |
| 198 | : { |
| 199 | ...existing, |
| 200 | count: existing.count + 1, |
| 201 | actors: [...existing.actors, ...actor], |
| 202 | viewerHasReacted: existing.viewerHasReacted || mine, |
| 203 | }, |
| 204 | ); |
| 205 | } |
| 206 | return [...grouped.values()]; |
| 207 | } |
| 208 | |
| 209 | function toComment(comment: LinearApi.LinearComment, viewerId: string | null): IssueComment { |
| 210 | return { |
| 211 | id: comment.id, |
| 212 | author: actorOf(comment.user, comment.botActor), |
| 213 | body: comment.body, |
| 214 | createdAt: comment.createdAt, |
| 215 | url: comment.url, |
| 216 | reactions: toReactions(comment.reactions, viewerId), |
| 217 | }; |
| 218 | } |
| 219 | |
| 220 | function toEvents(history: ReadonlyArray<LinearApi.LinearHistoryEntry>): IssueEvent[] { |
| 221 | const events: IssueEvent[] = []; |
| 222 | for (const entry of history) { |
| 223 | const actor = actorOf(entry.actor, entry.botActor); |
| 224 | const add = (kind: IssueEvent["kind"], detail: string | null, suffix: string) => |
| 225 | events.push({ id: `${entry.id}:${suffix}`, kind, actor, createdAt: entry.createdAt, detail }); |
| 226 | if (entry.toState !== null && entry.toState.id !== entry.fromState?.id) { |
| 227 | const wasClosed = |
| 228 | entry.fromState !== null && CLOSED_STATE_TYPES.includes(entry.fromState.type); |
| 229 | const isClosed = CLOSED_STATE_TYPES.includes(entry.toState.type); |
| 230 | add( |
| 231 | isClosed && !wasClosed ? "closed" : wasClosed && !isClosed ? "reopened" : "state-changed", |
| 232 | entry.toState.name, |
| 233 | "state", |
| 234 | ); |
| 235 | } |
| 236 | for (const label of entry.addedLabels ?? []) add("labeled", label.name, `label+${label.id}`); |
| 237 | for (const label of entry.removedLabels ?? []) |
| 238 | add("unlabeled", label.name, `label-${label.id}`); |
| 239 | if (entry.fromAssignee !== null && entry.fromAssignee.id !== entry.toAssignee?.id) |
| 240 | add("unassigned", userName(entry.fromAssignee), "unassigned"); |
| 241 | if (entry.toAssignee !== null && entry.toAssignee.id !== entry.fromAssignee?.id) |
| 242 | add("assigned", userName(entry.toAssignee), "assigned"); |
| 243 | if (entry.toTitle !== null && entry.toTitle !== entry.fromTitle) |
| 244 | add("renamed", entry.toTitle, "title"); |
| 245 | } |
| 246 | return events; |
| 247 | } |
| 248 | |
| 249 | const PULL_REQUEST_URL = |
| 250 | /^https:\/\/(?:github\.com\/([^/]+\/[^/]+)\/pull|gitlab\.com\/(.+?)\/-\/merge_requests)\/(\d+)\/?(?:[?#]|$)/u; |
| 251 | |
| 252 | const isJsonObject = Schema.is(Schema.Record(Schema.String, Schema.Json)); |
| 253 | |
| 254 | /** Linear's GitHub and GitLab integrations record change requests as attachments. */ |
| 255 | function toLinkedPullRequests( |
| 256 | attachments: ReadonlyArray<LinearApi.LinearAttachment>, |
| 257 | ): IssueLinkedPullRequest[] { |
| 258 | const seen = new Set<string>(); |
| 259 | return attachments.flatMap((attachment) => { |
| 260 | const match = PULL_REQUEST_URL.exec(attachment.url); |
| 261 | if (match === null || seen.has(attachment.url)) return []; |
| 262 | seen.add(attachment.url); |
| 263 | const fields = isJsonObject(attachment.metadata) ? attachment.metadata : {}; |
| 264 | const status = fields["status"]; |
| 265 | return [ |
| 266 | { |
| 267 | repository: match[1] ?? match[2]!, |
| 268 | number: Number(match[3]), |
| 269 | title: attachment.title.trim() || attachment.url, |
| 270 | url: attachment.url, |
| 271 | state: status === "merged" ? "merged" : status === "closed" ? "closed" : "open", |
| 272 | isDraft: status === "draft" || fields["draft"] === true, |
| 273 | closesIssue: false, |
| 274 | } as const, |
| 275 | ]; |
| 276 | }); |
| 277 | } |
| 278 | |
| 279 | /** |
| 280 | * A template the composer can hold: markdown content, no form fields. Anything else is offered |
| 281 | * as a link into Linear, where the exact template renders. |
| 282 | */ |
| 283 | export function toTemplate( |
| 284 | template: LinearApi.LinearTemplate, |
| 285 | teamKey: string, |
| 286 | labelNames: ReadonlyMap<string, string>, |
| 287 | ): { readonly template: IssueTemplate } | { readonly link: IssueExternalTemplate } { |
| 288 | const data = template.templateData; |
| 289 | const body = template.content ?? (typeof data.description === "string" ? data.description : null); |
| 290 | if (template.hasFormFields || (body === null && data.descriptionData != null)) { |
| 291 | const url = new URL(`https://linear.app/team/${encodeURIComponent(teamKey)}/new`); |
| 292 | url.searchParams.set("template", template.id); |
| 293 | return { link: { name: template.name, about: template.description ?? "", url: url.href } }; |
| 294 | } |
| 295 | return { |
| 296 | template: { |
| 297 | key: template.id, |
| 298 | name: template.name, |
| 299 | about: template.description ?? "", |
| 300 | title: data.title ?? "", |
| 301 | body: body ?? "", |
| 302 | labels: (data.labelIds ?? []).flatMap((id) => { |
| 303 | const name = labelNames.get(id); |
| 304 | return name === undefined ? [] : [name]; |
| 305 | }), |
| 306 | assignees: data.assigneeId ? [data.assigneeId] : [], |
| 307 | }, |
| 308 | }; |
| 309 | } |
| 310 | |
| 311 | function involvementFilter(input: IssueInvolvementFilter): LinearApi.IssueFilter { |
| 312 | switch (input.involvement) { |
| 313 | case "assigned": |
| 314 | return { assignee: { displayName: { eq: input.viewer } } }; |
| 315 | case "authored": |
| 316 | return { creator: { displayName: { eq: input.viewer } } }; |
| 317 | case "mentioned": |
| 318 | return { subscribers: { some: { displayName: { eq: input.viewer } } } }; |
| 319 | case "all": |
| 320 | return {}; |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | const notFound = (operation: string) => |
| 325 | new IssueTrackerError({ |
| 326 | tracker: LinearApi.KIND, |
| 327 | operation, |
| 328 | reason: "not-found", |
| 329 | detail: "Linear has no issue by that identifier, or this account cannot see it.", |
| 330 | }); |
| 331 | |
| 332 | const failed = (operation: string, detail: string) => |
| 333 | new IssueTrackerError({ tracker: LinearApi.KIND, operation, reason: "failed", detail }); |
| 334 | |
| 335 | export const make: Effect.Effect<StandaloneIssueTrackerApi, never, LinearApi.LinearApi> = |
| 336 | Effect.gen(function* () { |
| 337 | const linear = yield* LinearApi.LinearApi; |
| 338 | |
| 339 | const requireIdentifier = (operation: string, key: string) => { |
| 340 | const identifier = parseIdentifier(key); |
| 341 | return identifier === null ? Effect.fail(notFound(operation)) : Effect.succeed(identifier); |
| 342 | }; |
| 343 | |
| 344 | /** |
| 345 | * The issue a write names, refused unless it sits in the bound team: an identifier from |
| 346 | * another team, or one that moved away, still resolves in Linear. |
| 347 | */ |
| 348 | const requireTeamIssue = Effect.fn("LinearIssueTracker.requireTeamIssue")(function* ( |
| 349 | operation: string, |
| 350 | input: { readonly scope: string; readonly key: string }, |
| 351 | ) { |
| 352 | const identifier = yield* requireIdentifier(operation, input.key); |
| 353 | // One comment, not none: Linear refuses a page of zero. |
| 354 | const issue = yield* linear.getIssue(identifier, 1); |
| 355 | if (issue === null) return yield* notFound(operation); |
| 356 | const team = input.scope.trim().toUpperCase(); |
| 357 | if (issue.team.key !== team) { |
| 358 | return yield* failed( |
| 359 | operation, |
| 360 | `${issue.identifier} belongs to Linear team ${issue.team.key}, not ${team}.`, |
| 361 | ); |
| 362 | } |
| 363 | return issue; |
| 364 | }); |
| 365 | |
| 366 | const requireTeam = (operation: string, scope: string) => |
| 367 | linear.getTeam(scope.trim().toUpperCase()).pipe( |
| 368 | Effect.filterOrFail( |
| 369 | (team): team is LinearApi.LinearTeamScope => team !== null, |
| 370 | () => failed(operation, `No Linear team has the key "${scope}".`), |
| 371 | ), |
| 372 | ); |
| 373 | |
| 374 | /** Names to label ids, within the team's and the workspace's labels. */ |
| 375 | const labelIds = ( |
| 376 | operation: string, |
| 377 | scope: LinearApi.LinearTeamScope, |
| 378 | names: ReadonlyArray<string>, |
| 379 | ) => |
| 380 | Effect.forEach(names, (name) => { |
| 381 | const match = [...scope.team.labels.nodes, ...scope.workspaceLabels].find( |
| 382 | (label) => label.name.toLowerCase() === name.trim().toLowerCase(), |
| 383 | ); |
| 384 | return match === undefined |
| 385 | ? Effect.fail(failed(operation, `Linear has no label named "${name}" for this team.`)) |
| 386 | : Effect.succeed(match.id); |
| 387 | }); |
| 388 | |
| 389 | /** One assignee at most: Linear issues have a single assignee. */ |
| 390 | const assigneeId = ( |
| 391 | operation: string, |
| 392 | scope: LinearApi.LinearTeamScope, |
| 393 | assignees: ReadonlyArray<string>, |
| 394 | ): Effect.Effect<string | null, IssueTrackerError> => { |
| 395 | const [first, ...rest] = assignees; |
| 396 | if (first === undefined) return Effect.succeed(null); |
| 397 | if (rest.length > 0) |
| 398 | return Effect.fail(failed(operation, "A Linear issue has one assignee at most.")); |
| 399 | const member = scope.team.members.nodes.find( |
| 400 | (user) => |
| 401 | user.id === first || |
| 402 | user.email?.toLowerCase() === first.toLowerCase() || |
| 403 | user.displayName?.toLowerCase() === first.toLowerCase(), |
| 404 | ); |
| 405 | return member === undefined |
| 406 | ? Effect.fail(failed(operation, `"${first}" is not a member of this Linear team.`)) |
| 407 | : Effect.succeed(member.id); |
| 408 | }; |
| 409 | |
| 410 | const viewerId: Effect.Effect<string | null> = linear.viewer().pipe( |
| 411 | Effect.map((data) => data.viewer.id), |
| 412 | Effect.orElseSucceed(() => null), |
| 413 | ); |
| 414 | |
| 415 | const api: StandaloneIssueTrackerApi = { |
| 416 | kind: LinearApi.KIND, |
| 417 | capabilities: CAPABILITIES, |
| 418 | standalone: DESCRIPTOR, |
| 419 | parseIssueUrl: parseLinearIssueUrl, |
| 420 | |
| 421 | probeCredential: (token) => |
| 422 | linear.viewer(token).pipe( |
| 423 | Effect.map((data) => ({ |
| 424 | account: userName(data.viewer), |
| 425 | workspace: data.workspace, |
| 426 | scopes: data.teams.map((team) => ({ key: team.key, name: team.name })), |
| 427 | })), |
| 428 | ), |
| 429 | |
| 430 | // The id, not the display name: it is what the involvement filters compare against. |
| 431 | getViewer: () => linear.viewer().pipe(Effect.map((data) => toActor(data.viewer).login)), |
| 432 | |
| 433 | listIssues: Effect.fn("LinearIssueTracker.listIssues")((input) => { |
| 434 | const team = input.scope.trim().toUpperCase(); |
| 435 | // A qualified issue number applies only to its own team. Text can match anywhere. |
| 436 | const reference = |
| 437 | input.query === undefined |
| 438 | ? null |
| 439 | : /^(?:([A-Za-z][A-Za-z0-9]*)-|#)?(\d+)$/.exec(input.query.trim()); |
| 440 | const number = |
| 441 | reference !== null && (reference[1] === undefined || reference[1].toUpperCase() === team) |
| 442 | ? Number(reference[2]) |
| 443 | : undefined; |
| 444 | // Each is its own clause: an assignee filter must narrow "assigned to me", not replace it. |
| 445 | const clauses: LinearApi.IssueFilter[] = [ |
| 446 | ...(input.assignee === undefined |
| 447 | ? [] |
| 448 | : [{ assignee: { displayName: { eq: input.assignee } } }]), |
| 449 | ...(input.labels ?? []).map((name) => ({ labels: { some: { name: { eq: name } } } })), |
| 450 | ]; |
| 451 | const filter: LinearApi.IssueFilter = { |
| 452 | team: { key: { eq: team } }, |
| 453 | ...involvementFilter(input), |
| 454 | ...(input.state === "all" |
| 455 | ? {} |
| 456 | : { |
| 457 | state: { |
| 458 | type: |
| 459 | input.state === "closed" |
| 460 | ? { in: CLOSED_STATE_TYPES } |
| 461 | : { nin: CLOSED_STATE_TYPES }, |
| 462 | }, |
| 463 | }), |
| 464 | ...(clauses.length === 0 ? {} : { and: clauses }), |
| 465 | ...(input.query === undefined |
| 466 | ? {} |
| 467 | : { |
| 468 | or: [ |
| 469 | { title: { containsIgnoreCase: input.query } }, |
| 470 | { description: { containsIgnoreCase: input.query } }, |
| 471 | ...(number === undefined ? [] : [{ number: { eq: number } }]), |
| 472 | ], |
| 473 | }), |
| 474 | }; |
| 475 | return linear |
| 476 | .listIssues({ |
| 477 | filter, |
| 478 | first: input.limit, |
| 479 | after: input.cursor, |
| 480 | orderBy: input.sort === "created" ? "createdAt" : "updatedAt", |
| 481 | }) |
| 482 | .pipe( |
| 483 | Effect.map((page) => ({ |
| 484 | items: page.nodes.map((node) => toSummary(node)), |
| 485 | nextCursor: page.nextCursor, |
| 486 | })), |
| 487 | ); |
| 488 | }), |
| 489 | |
| 490 | getIssue: Effect.fn("LinearIssueTracker.getIssue")(function* (input) { |
| 491 | const identifier = yield* requireIdentifier("getIssue", input.key); |
| 492 | // One read of the viewer: the id matches reactions, the handle is what the client sees. |
| 493 | // A missing issue interrupts it rather than waiting for it. |
| 494 | const [issue, me] = yield* Effect.all( |
| 495 | [ |
| 496 | linear.getIssue(identifier, COMMENTS_PAGE).pipe( |
| 497 | Effect.filterOrElse( |
| 498 | (issue) => issue !== null, |
| 499 | () => notFound("getIssue"), |
| 500 | ), |
| 501 | ), |
| 502 | linear.viewer().pipe( |
| 503 | Effect.map((data) => data.viewer), |
| 504 | Effect.orElseSucceed(() => null), |
| 505 | ), |
| 506 | ], |
| 507 | { concurrency: 2 }, |
| 508 | ); |
| 509 | const viewer = me?.id ?? null; |
| 510 | return { |
| 511 | ...toSummary(issue, issue.comments.nodes.length), |
| 512 | body: issue.description ?? "", |
| 513 | viewer: me === null ? null : toActor(me).login, |
| 514 | viewerPermissions: VIEWER_PERMISSIONS, |
| 515 | states: inWorkflowOrder(issue.team.states.nodes).map(toState), |
| 516 | reactions: toReactions(issue.reactions, viewer), |
| 517 | comments: issue.comments.nodes.map((comment) => toComment(comment, viewer)), |
| 518 | commentsCursor: issue.comments.pageInfo.hasNextPage |
| 519 | ? issue.comments.pageInfo.endCursor |
| 520 | : null, |
| 521 | events: toEvents(issue.history.nodes), |
| 522 | linkedPullRequests: toLinkedPullRequests(issue.attachments.nodes), |
| 523 | }; |
| 524 | }), |
| 525 | |
| 526 | getComments: Effect.fn("LinearIssueTracker.getComments")(function* (input) { |
| 527 | const identifier = yield* requireIdentifier("getComments", input.key); |
| 528 | const page = yield* linear.getComments({ |
| 529 | identifier, |
| 530 | first: COMMENTS_PAGE, |
| 531 | after: input.cursor, |
| 532 | }); |
| 533 | const viewer = page.nodes.some((comment) => comment.reactions.length > 0) |
| 534 | ? yield* viewerId |
| 535 | : null; |
| 536 | return { |
| 537 | comments: page.nodes.map((comment) => toComment(comment, viewer)), |
| 538 | nextCursor: page.nextCursor, |
| 539 | }; |
| 540 | }), |
| 541 | |
| 542 | create: Effect.fn("LinearIssueTracker.create")(function* (input) { |
| 543 | const scope = yield* requireTeam("create", input.scope); |
| 544 | const labels = yield* labelIds("create", scope, input.labels); |
| 545 | const assignee = yield* assigneeId("create", scope, input.assignees); |
| 546 | const created = yield* linear.createIssue({ |
| 547 | teamId: scope.team.id, |
| 548 | title: input.title, |
| 549 | description: input.body, |
| 550 | labelIds: labels, |
| 551 | ...(assignee === null ? {} : { assigneeId: assignee }), |
| 552 | }); |
| 553 | return { key: created.identifier, displayKey: created.identifier, url: created.url }; |
| 554 | }), |
| 555 | |
| 556 | comment: Effect.fn("LinearIssueTracker.comment")(function* (input) { |
| 557 | const issue = yield* requireTeamIssue("comment", input); |
| 558 | yield* linear.createComment({ issueId: issue.id, body: input.body }); |
| 559 | }), |
| 560 | |
| 561 | update: Effect.fn("LinearIssueTracker.update")(function* (input) { |
| 562 | const { identifier } = yield* requireTeamIssue("update", input); |
| 563 | const scope = |
| 564 | input.labels !== undefined || input.assignees !== undefined |
| 565 | ? yield* requireTeam("update", input.scope) |
| 566 | : null; |
| 567 | yield* linear.updateIssue(identifier, { |
| 568 | ...(input.title === undefined ? {} : { title: input.title }), |
| 569 | ...(input.body === undefined ? {} : { description: input.body }), |
| 570 | ...(scope === null || input.labels === undefined |
| 571 | ? {} |
| 572 | : { labelIds: yield* labelIds("update", scope, input.labels) }), |
| 573 | ...(scope === null || input.assignees === undefined |
| 574 | ? {} |
| 575 | : { assigneeId: yield* assigneeId("update", scope, input.assignees) }), |
| 576 | }); |
| 577 | }), |
| 578 | |
| 579 | setState: Effect.fn("LinearIssueTracker.setState")(function* (input) { |
| 580 | const { identifier } = yield* requireTeamIssue("setState", input); |
| 581 | const scope = yield* requireTeam("setState", input.scope); |
| 582 | const wanted = scope.team.states.nodes.find((state) => state.name === input.state); |
| 583 | if (wanted === undefined) |
| 584 | return yield* failed("setState", `This team's workflow has no "${input.state}" state.`); |
| 585 | yield* linear.updateIssue(identifier, { stateId: wanted.id }); |
| 586 | }), |
| 587 | |
| 588 | setReaction: Effect.fn("LinearIssueTracker.setReaction")(function* (input) { |
| 589 | const issue = yield* requireTeamIssue("setReaction", input); |
| 590 | const emoji = EMOJI_BY_CONTENT[input.content]; |
| 591 | const target = |
| 592 | input.subjectId === undefined ? { issueId: issue.id } : { commentId: input.subjectId }; |
| 593 | // Comment ids are global: prove the comment belongs to this issue before writing. |
| 594 | const subject = |
| 595 | input.subjectId === undefined && input.reacted |
| 596 | ? null |
| 597 | : yield* linear.listReactions(target); |
| 598 | if (subject !== null && subject.issueId !== issue.id) { |
| 599 | return yield* failed("setReaction", "The comment does not belong to the selected issue."); |
| 600 | } |
| 601 | if (subject === null || input.reacted) { |
| 602 | yield* linear.createReaction({ ...target, emoji }); |
| 603 | return; |
| 604 | } |
| 605 | const viewer = yield* viewerId; |
| 606 | const { reactions } = subject; |
| 607 | const own = reactions.find( |
| 608 | (reaction) => |
| 609 | CONTENT_BY_EMOJI.get(reaction.emoji) === input.content && reaction.user?.id === viewer, |
| 610 | ); |
| 611 | if (own !== undefined) yield* linear.deleteReaction(own.id); |
| 612 | }), |
| 613 | |
| 614 | listTemplates: (input) => |
| 615 | requireTeam("listTemplates", input.scope).pipe( |
| 616 | Effect.map((scope) => { |
| 617 | const labelNames = new Map( |
| 618 | [...scope.team.labels.nodes, ...scope.workspaceLabels].map((label) => [ |
| 619 | label.id, |
| 620 | label.name, |
| 621 | ]), |
| 622 | ); |
| 623 | const templates: IssueTemplate[] = []; |
| 624 | const externalTemplates: IssueExternalTemplate[] = []; |
| 625 | for (const template of scope.team.templates.nodes) { |
| 626 | if (template.type !== "issue") continue; |
| 627 | const mapped = toTemplate(template, scope.team.key, labelNames); |
| 628 | if ("template" in mapped) templates.push(mapped.template); |
| 629 | else externalTemplates.push(mapped.link); |
| 630 | } |
| 631 | return { templates, externalTemplates, blankIssuesEnabled: true }; |
| 632 | }), |
| 633 | ), |
| 634 | |
| 635 | listCandidates: (input) => |
| 636 | requireTeam("listCandidates", input.scope).pipe( |
| 637 | Effect.map((scope) => ({ |
| 638 | labels: [...scope.team.labels.nodes, ...scope.workspaceLabels].map((label) => ({ |
| 639 | name: label.name, |
| 640 | color: label.color, |
| 641 | description: label.description ?? null, |
| 642 | })), |
| 643 | assignees: scope.team.members.nodes.map((user) => ({ ...toActor(user), id: user.id })), |
| 644 | truncated: scope.truncated, |
| 645 | })), |
| 646 | ), |
| 647 | }; |
| 648 | return api; |
| 649 | }); |