Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

issueTrackers.ts

217 lines8.4 KB

1import {
2 IssueTrackerConnectionError,
3 MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES,
4 WS_METHODS,
5 issueTrackerBindingScopes,
6 type IssueTrackerBindProjectInput,
7 type IssueTrackerConnection,
8 type IssueTrackerConnectionList,
9 type IssueTrackerProjectBinding,
10 type ProjectId,
11} from "@t3tools/contracts";
12import * as Effect from "effect/Effect";
13import * as Schema from "effect/Schema";
14import { Atom } from "effect/reactivity";
15import { mFallback, msg, plural, part, type Msg } from "gt-i18n";
16import type { M } from "gt-i18n";
17​
18import {
19 createAtomCommandScheduler,
20 createEnvironmentRpcCommand,
21 createEnvironmentRpcQueryAtomFamily,
22} from "./runtime.ts";
23import type { EnvironmentRegistry } from "../connection/registry.ts";
24import * as Persistence from "../platform/persistence.ts";
25​
26/**
27 * Standalone issue trackers (Linear, Jira) per environment: which are connected, as whom, which
28 * scopes they reach, and which project is bound to which scope. One query carries all of it, and
29 * every mutation refreshes that query, so the settings page never shows a stale status.
30 */
31export function createIssueTrackerEnvironmentAtoms<R, E>(
32 runtime: Atom.AtomRuntime<EnvironmentRegistry | Persistence.EnvironmentCacheStore | R, E>,
33) {
34 const commandScheduler = createAtomCommandScheduler();
35 const connections = createEnvironmentRpcQueryAtomFamily(runtime, {
36 label: "environment-data:issue-trackers:connections",
37 tag: WS_METHODS.issueTrackersList,
38 });
39 const refresh = (environmentId: Parameters<typeof connections>[0]["environmentId"]) =>
40 connections({ environmentId, input: {} });
41 // Connect, disconnect and bind all edit one environment's tracker state; serialized so a
42 // disconnect cannot race the bind of a project to the tracker being removed.
43 const serialPerEnvironment = {
44 mode: "serial" as const,
45 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
46 };
47 return {
48 connections,
49 /** Saves a credential the tracker accepted, or removes the stored one with a null token. */
50 connect: createEnvironmentRpcCommand(runtime, {
51 label: "environment-data:issue-trackers:connect",
52 tag: WS_METHODS.issueTrackersConnect,
53 scheduler: commandScheduler,
54 concurrency: serialPerEnvironment,
55 onSettled: (target, registry) =>
56 Effect.sync(() => registry.refresh(refresh(target.environmentId))),
57 }),
58 bindProject: createEnvironmentRpcCommand(runtime, {
59 label: "environment-data:issue-trackers:bind-project",
60 tag: WS_METHODS.issueTrackersBindProject,
61 scheduler: commandScheduler,
62 concurrency: serialPerEnvironment,
63 onSettled: (target, registry) =>
64 Effect.sync(() => registry.refresh(refresh(target.environmentId))),
65 }),
66 };
68​
69// Tracker packages name their credential and scope in English, so a sentence is translated only
70// when it matches a known tracker's whole sentence; any other tracker keeps the English one.
71function knownTrackerSentence(
72 english: string,
73 candidates: ReadonlyArray<string | Msg>,
74 resolve: M,
75): string {
76 const known = candidates.find((candidate) => mFallback(candidate) === english);
77 return known === undefined ? english : resolve(known);
79​
80const SERVER_TRACKER_DETAILS = [msg("Issues cannot be browsed for this host yet.")];
81​
82/** A tracker's `detail` from the issue list, translated when it is a fixed server line. */
83export function issueTrackerDetailText(detail: string, resolve: M = mFallback): string {
84 return knownTrackerSentence(detail, SERVER_TRACKER_DETAILS, resolve);
86​
87const isConnectionError = Schema.is(IssueTrackerConnectionError);
88​
89/** Why connecting failed, in the tracker's own words rather than the error's "<kind> connection failed:" prefix. */
90export function issueTrackerConnectFailure(error: unknown): string | null {
91 if (isConnectionError(error)) return error.detail;
92 return error instanceof Error ? error.message : null;
94​
95/** Every project's binding, whichever account it was made with. */
96export function issueTrackerBindings(
97 list: IssueTrackerConnectionList | null | undefined,
98): IssueTrackerConnectionList["bindings"] {
99 return { ...list?.bindings, ...list?.accountBindings };
101​
102/** Whether a project binding reads through this account of the tracker. */
103function issueTrackerBindingIsFor(
104 binding: IssueTrackerProjectBinding,
105 tracker: Pick<IssueTrackerConnection, "tracker" | "accountId">,
106): boolean {
107 return binding.tracker === tracker.tracker && binding.accountId === tracker.accountId;
109​
110/**
111 * The line under a tracker's name. A connected tracker lists nothing until a project is linked
112 * to one of its scopes, so the line says how many are, and what to do when none is.
113 */
114export function issueTrackerSummary(
115 tracker: IssueTrackerConnection,
116 bindings: IssueTrackerConnectionList["bindings"],
117 resolve: M = mFallback,
118): string {
119 if (!tracker.connected) {
120 // Mid-sentence case, keeping an acronym: "personal API key", "API token".
121 const credential = tracker.credential.label
122 .split(" ")
123 .map((word) => (word === word.toUpperCase() ? word : word.toLowerCase()))
124 .join(" ");
125 return knownTrackerSentence(
126 `Not connected. Add your ${credential} to list its issues.`,
127 [
128 msg("Not connected. Add your personal API key to list its issues."),
129 msg("Not connected. Add your API token to list its issues."),
130 ],
131 resolve,
132 );
133 }
134 if (tracker.account === null)
135 return tracker.detail ?? resolve(msg("The saved credential was rejected."));
136 const linked = Object.values(bindings).filter((binding) =>
137 issueTrackerBindingIsFor(binding, tracker),
138 ).length;
139 return linked === 0
140 ? knownTrackerSentence(
141 `Connected as ${tracker.account} · no projects linked yet. Link one to a ${tracker.displayName} ${tracker.scopeNoun} to list its issues.`,
142 [
143 msg`Connected as ${{ account: tracker.account }} · no projects linked yet. Link one to a Linear team to list its issues.`,
144 msg`Connected as ${{ account: tracker.account }} · no projects linked yet. Link one to a Jira project to list its issues.`,
145 ],
146 resolve,
147 )
148 : resolve(
149 msg`${plural(
150 { count: linked },
151 {
152 one: part`Connected as ${{ account: tracker.account }} · ${{ count: linked }} project linked`,
153 other: part`Connected as ${{ account: tracker.account }} · ${{ count: linked }} projects linked`,
154 },
155 )}`,
156 );
158​
159type TrackerAccount = Pick<IssueTrackerConnection, "tracker" | "accountId">;
160​
161export function boundIssueTrackerScopes(
162 tracker: TrackerAccount,
163 binding: IssueTrackerProjectBinding | undefined,
164): ReadonlyArray<string> {
165 return binding !== undefined && issueTrackerBindingIsFor(binding, tracker)
166 ? issueTrackerBindingScopes(binding)
167 : [];
169​
170export function issueTrackerBindingFor(
171 { tracker, accountId }: TrackerAccount,
172 current: ReadonlyArray<string>,
173 scopes: ReadonlyArray<string>,
174): IssueTrackerProjectBinding | null {
175 const kept = current.filter((key) => scopes.includes(key));
176 const [scope, ...additionalScopes] = [...kept, ...scopes.filter((key) => !kept.includes(key))];
177 if (scope === undefined) return null;
178 return {
179 tracker,
180 ...(accountId === undefined ? {} : { accountId }),
181 scope,
182 ...(additionalScopes.length === 0 ? {} : { additionalScopes }),
183 };
185​
186/** The request that saves a project's picks under this account; an unbind names the account. */
187export function issueTrackerBindInput(
188 projectId: ProjectId,
189 { accountId }: TrackerAccount,
190 binding: IssueTrackerProjectBinding | null,
191): IssueTrackerBindProjectInput {
192 return binding === null && accountId !== undefined
193 ? { projectId, binding, accountId }
194 : { projectId, binding };
196​
197export function issueTrackerScopeOptions(
198 tracker: IssueTrackerConnection,
199 bound: ReadonlyArray<string>,
200): ReadonlyArray<{ readonly key: string; readonly name: string; readonly addable: boolean }> {
201 const offered = new Set(tracker.scopes.map((scope) => scope.key));
202 const full = bound.length > MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES;
203 return [
204 ...tracker.scopes,
205 ...bound.filter((key) => !offered.has(key)).map((key) => ({ key, name: key })),
206 ].map((scope) => ({ ...scope, addable: !full || bound.includes(scope.key) }));
208​
209export function hasIssueTrackerTeams(
210 tracker: IssueTrackerConnection,
211 bindings: IssueTrackerConnectionList["bindings"],
212): boolean {
213 return (
214 tracker.scopes.length > 0 ||
215 Object.values(bindings).some((binding) => issueTrackerBindingIsFor(binding, tracker))
216 );