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

azureDevOpsIssueJson.ts

427 lines16.1 KB

1/**
2 * Decoders for Azure DevOps work items as `az boards` and the `wit` REST area answer them. Azure
3 * keeps everything under `fields`, keyed by reference name, and a project may add fields of its
4 * own, so only the ones every work item type carries are read.
5 *
6 * @module source-control-azure-devops/server/azureDevOpsIssueJson
7 */
8import * as Exit from "effect/Exit";
9import * as Result from "effect/Result";
10import * as Schema from "effect/Schema";
11import type {
12 IssueActor,
13 IssueComment,
14 IssueEvent,
15 IssueLabel,
16 IssueReaction,
17 IssueReactionContent,
18 IssueState,
19} from "@t3tools/contracts";
20import { decodeJsonResult } from "@t3tools/shared/schemaJson";
21import type { TrackerIssueSummary } from "@t3tools/source-control-core/server/IssueTracker";
22​
23/** Lowercased names of the states a project treats as finished, read by `closedStateNames`. */
24export type ClosedStates = ReadonlySet<string>;
25​
26/** The finished states of Azure's stock processes, for a project whose types report none. */
27const STOCK_CLOSED_STATES: ClosedStates = new Set([
28 "closed",
29 "done",
30 "removed",
31 "resolved",
32 "completed",
33]);
34​
35const FINISHED_CATEGORIES: ReadonlySet<string> = new Set(["Resolved", "Completed", "Removed"]);
36​
37/** The stock Basic, Agile and Scrum states, for a work item whose type reports none. */
38const STOCK_STATES: ReadonlyArray<IssueState> = [
39 { category: "open", name: "New" },
40 { category: "open", name: "To Do" },
41 { category: "open", name: "Active" },
42 { category: "open", name: "Doing" },
43 { category: "closed", name: "Resolved" },
44 { category: "closed", name: "Done" },
45 { category: "closed", name: "Closed" },
46 { category: "closed", name: "Removed" },
47];
48​
49type WorkItemTypes = ReadonlyArray<{
50 readonly name: string;
51 readonly states?: ReadonlyArray<{ readonly name: string; readonly category: string }> | undefined;
52}>;
53​
54/**
55 * A project's finished states, from its work item types' state categories. Custom processes
56 * name their own columns, so the category, not the name, says whether one is finished.
57 */
58export function closedStateNames(types: WorkItemTypes): ClosedStates {
59 const names = types.flatMap((type) =>
60 (type.states ?? []).flatMap((state) =>
61 FINISHED_CATEGORIES.has(state.category) ? [state.name.toLowerCase()] : [],
62 ),
63 );
64 return names.length === 0 ? STOCK_CLOSED_STATES : new Set(names);
66​
67const Identity = Schema.Struct({
68 displayName: Schema.optional(Schema.NullOr(Schema.String)),
69 uniqueName: Schema.optional(Schema.NullOr(Schema.String)),
70 imageUrl: Schema.optional(Schema.NullOr(Schema.String)),
71});
72​
73/** WIQL answers an identity as an object; a project rule can leave a plain "Name <email>" string. */
74const IdentityValue = Schema.NullOr(Schema.Union([Identity, Schema.String]));
75​
76const Fields = Schema.Struct({
77 "System.CommentCount": Schema.optional(Schema.NullOr(Schema.Int)),
78 "System.Title": Schema.optional(Schema.NullOr(Schema.String)),
79 "System.State": Schema.optional(Schema.NullOr(Schema.String)),
80 "System.CreatedDate": Schema.optional(Schema.NullOr(Schema.String)),
81 "System.ChangedDate": Schema.optional(Schema.NullOr(Schema.String)),
82 "Microsoft.VSTS.Common.ClosedDate": Schema.optional(Schema.NullOr(Schema.String)),
83 "System.Description": Schema.optional(Schema.NullOr(Schema.String)),
84 "System.Tags": Schema.optional(Schema.NullOr(Schema.String)),
85 "System.TeamProject": Schema.optional(Schema.NullOr(Schema.String)),
86 "System.WorkItemType": Schema.optional(Schema.NullOr(Schema.String)),
87 "System.CreatedBy": Schema.optional(IdentityValue),
88 "System.AssignedTo": Schema.optional(IdentityValue),
89});
90​
91const Relation = Schema.Struct({ rel: Schema.String, url: Schema.String });
92​
93const WorkItem = Schema.Struct({
94 id: Schema.Int,
95 url: Schema.optional(Schema.NullOr(Schema.String)),
96 fields: Schema.optional(Schema.NullOr(Fields)),
97 relations: Schema.optional(Schema.NullOr(Schema.Array(Relation))),
98});
99​
100const decodeWorkItemEntry = Schema.decodeUnknownExit(WorkItem);
101const decodeWorkItemList = decodeJsonResult(
102 Schema.Struct({ value: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))) }),
103);
104const decodeWorkItem = decodeJsonResult(WorkItem);
105​
106type DecodeFailure =
107 ReturnType<typeof decodeWorkItem> extends Result.Result<unknown, infer E> ? E : never;
108​
109function trimmed(value: string | null | undefined): string | null {
110 const text = value?.trim() ?? "";
111 return text.length > 0 ? text : null;
113​
114/**
115 * The organization link `az` returns addresses the REST resource, which is not a page anybody can
116 * open. The one a reader wants is the board's own item, which Azure spells this way.
117 */
118function browserUrl(
119 apiUrl: string | null | undefined,
120 id: number,
121 project: string | null,
122): string | null {
123 if (apiUrl === null || apiUrl === undefined || project === null) return null;
124 const match = /^(https?:\/\/([^/]+))(?:\/([^/]+))?(?:\/[^/]+)?\/_apis\/wit\/workItems\//i.exec(
125 apiUrl,
126 );
127 if (match === null) return null;
128 const [, origin, host, organization] = match;
129 // A legacy organization is its hostname, so whatever the path starts with is a project.
130 const base = host!.toLowerCase().endsWith(".visualstudio.com")
131 ? origin
132 : organization === undefined
133 ? null
134 : `${origin}/${organization}`;
135 return base === null ? null : `${base}/${encodeURIComponent(project)}/_workitems/edit/${id}`;
137​
138function toActor(value: typeof IdentityValue.Type | undefined): IssueActor | null {
139 if (value === null || value === undefined) return null;
140 if (typeof value === "string") {
141 const login = trimmed(value);
142 return login === null ? null : { login, name: null, avatarUrl: null };
143 }
144 const login = trimmed(value.uniqueName) ?? trimmed(value.displayName);
145 return login === null
146 ? null
147 : { login, name: trimmed(value.displayName), avatarUrl: trimmed(value.imageUrl) };
149​
150function toIssueState(name: string | null | undefined, closed: ClosedStates): IssueState {
151 const state = trimmed(name) ?? "New";
152 return { category: closed.has(state.toLowerCase()) ? "closed" : "open", name: state };
154​
155/** Azure keeps tags as one `; `-separated string, with no colour anywhere. */
156function toLabels(tags: string | null | undefined): ReadonlyArray<IssueLabel> {
157 return [...new Set((tags ?? "").split(";").flatMap((tag) => trimmed(tag) ?? []))].map((name) => ({
158 name,
159 color: null,
160 }));
162​
163export interface AzureDevOpsWorkItem extends TrackerIssueSummary {
164 readonly body: string;
165 readonly project: string | null;
166 readonly workItemType: string | null;
167 readonly relations: ReadonlyArray<typeof Relation.Type>;
169​
170/** Null for a row this cannot place: no title, no dates, or no project to build a link from. */
171function toWorkItem(raw: typeof WorkItem.Type, closed: ClosedStates): AzureDevOpsWorkItem | null {
172 const fields = raw.fields ?? {};
173 const title = trimmed(fields["System.Title"]);
174 const createdAt = trimmed(fields["System.CreatedDate"]);
175 const updatedAt = trimmed(fields["System.ChangedDate"]) ?? createdAt;
176 const project = trimmed(fields["System.TeamProject"]);
177 const url = browserUrl(raw.url, raw.id, project);
178 if (raw.id <= 0 || title === null || createdAt === null || updatedAt === null || url === null) {
179 return null;
180 }
181 const assignee = toActor(fields["System.AssignedTo"]);
182 return {
183 key: String(raw.id),
184 displayKey: `#${raw.id}`,
185 title,
186 url,
187 author: toActor(fields["System.CreatedBy"]),
188 state: toIssueState(fields["System.State"], closed),
189 createdAt,
190 updatedAt,
191 closedAt: trimmed(fields["Microsoft.VSTS.Common.ClosedDate"]),
192 assignees: assignee === null ? [] : [assignee],
193 labels: toLabels(fields["System.Tags"]),
194 commentCount: Math.max(0, fields["System.CommentCount"] ?? 0),
195 body: fields["System.Description"] ?? "",
196 project,
197 workItemType: trimmed(fields["System.WorkItemType"]),
198 relations: raw.relations ?? [],
199 };
201​
202/**
203 * The states a work item can be in: its own type's, in the order Azure lists them, which differ
204 * per type and per process. The item's current state is always among them, even when the type
205 * could not be read and the stock list stands in.
206 */
207export function workItemStates(
208 types: WorkItemTypes,
209 item: Pick<AzureDevOpsWorkItem, "workItemType" | "state">,
210): ReadonlyArray<IssueState> {
211 const type = types.find((entry) => entry.name.toLowerCase() === item.workItemType?.toLowerCase());
212 const own = (type?.states ?? []).flatMap((state): ReadonlyArray<IssueState> => {
213 const name = trimmed(state.name);
214 return name === null
215 ? []
216 : [{ category: FINISHED_CATEGORIES.has(state.category) ? "closed" : "open", name }];
217 });
218 const states = own.length === 0 ? STOCK_STATES : own;
219 return states.some((state) => state.name === item.state.name) ? states : [...states, item.state];
221​
222/** The `{ count, value }` page `wit/workitemsbatch` answers; a row this cannot place is skipped. */
223export function decodeWorkItemsJson(
224 raw: string,
225 closed: ClosedStates,
226): Result.Result<ReadonlyArray<AzureDevOpsWorkItem>, DecodeFailure> {
227 return Result.map(decodeWorkItemList(raw), (page) =>
228 (page.value ?? []).flatMap((entry) => {
229 const item = decodeWorkItemEntry(entry);
230 if (Exit.isFailure(item)) return [];
231 return toWorkItem(item.value, closed) ?? [];
232 }),
233 );
235​
236/** Null where az answered with a work item this cannot place, which the caller reports as such. */
237export function decodeWorkItemJson(
238 raw: string,
239 closed: ClosedStates,
240): Result.Result<AzureDevOpsWorkItem | null, DecodeFailure> {
241 return Result.map(decodeWorkItem(raw), (item) => toWorkItem(item, closed));
243​
244/** Azure names comment reactions after its own icons; the six it has map onto the contract's. */
245const CONTENT_BY_REACTION: Readonly<Record<string, IssueReactionContent>> = {
246 like: "thumbs-up",
247 dislike: "thumbs-down",
248 heart: "heart",
249 hooray: "hooray",
250 smile: "laugh",
251 confused: "confused",
252};
253​
254export function azureDevOpsReactionType(content: IssueReactionContent): string | null {
255 return Object.entries(CONTENT_BY_REACTION).find(([, mapped]) => mapped === content)?.[0] ?? null;
257​
258const Comment = Schema.Struct({
259 id: Schema.Int,
260 text: Schema.optional(Schema.NullOr(Schema.String)),
261 createdDate: Schema.String,
262 createdBy: Schema.optional(Schema.NullOr(Identity)),
263 isDeleted: Schema.optional(Schema.Boolean),
264 reactions: Schema.optional(
265 Schema.NullOr(
266 Schema.Array(
267 Schema.Struct({
268 type: Schema.String,
269 count: Schema.Int,
270 isCurrentUserEngaged: Schema.optional(Schema.Boolean),
271 }),
272 ),
273 ),
274 ),
275});
276​
277const CommentsPage = Schema.Struct({
278 comments: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))),
279 continuationToken: Schema.optional(Schema.NullOr(Schema.String)),
280});
281​
282const decodeCommentsPage = decodeJsonResult(CommentsPage);
283const decodeCommentEntry = Schema.decodeUnknownExit(Comment);
284​
285function toReactions(raw: (typeof Comment.Type)["reactions"]): ReadonlyArray<IssueReaction> {
286 return (raw ?? []).flatMap((reaction) => {
287 const content = CONTENT_BY_REACTION[reaction.type.toLowerCase()];
288 return content === undefined || reaction.count <= 0
289 ? []
290 : [
291 {
292 content,
293 count: reaction.count,
294 // Azure counts reactions and says whether the reader is among them, but names nobody.
295 actors: [],
296 viewerHasReacted: reaction.isCurrentUserEngaged ?? false,
297 },
298 ];
299 });
301​
302export function decodeCommentsJson(
303 raw: string,
304): Result.Result<
305 { readonly comments: ReadonlyArray<IssueComment>; readonly nextCursor: string | null },
306 DecodeFailure
307> {
308 return Result.map(decodeCommentsPage(raw), (page) => ({
309 comments: (page.comments ?? []).flatMap((entry) => {
310 const comment = decodeCommentEntry(entry);
311 if (Exit.isFailure(comment) || comment.value.isDeleted === true) return [];
312 return [
313 {
314 id: String(comment.value.id),
315 author: toActor(comment.value.createdBy),
316 body: comment.value.text ?? "",
317 createdAt: comment.value.createdDate,
318 url: null,
319 reactions: toReactions(comment.value.reactions),
320 },
321 ];
322 }),
323 nextCursor: trimmed(page.continuationToken),
324 }));
326​
327const FieldChange = Schema.Struct({
328 oldValue: Schema.optional(Schema.Unknown),
329 newValue: Schema.optional(Schema.Unknown),
330});
331​
332const Update = Schema.Struct({
333 id: Schema.Int,
334 revisedDate: Schema.String,
335 revisedBy: Schema.optional(Schema.NullOr(Identity)),
336 fields: Schema.optional(Schema.NullOr(Schema.Record(Schema.String, FieldChange))),
337});
338​
339const decodeUpdatesPage = decodeJsonResult(
340 Schema.Struct({ value: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))) }),
341);
342const decodeUpdateEntry = Schema.decodeUnknownExit(Update);
343const decodeIdentityValue = Schema.decodeUnknownExit(IdentityValue);
344​
345function identityLogin(value: unknown): string | null {
346 const decoded = decodeIdentityValue(value);
347 return Exit.isSuccess(decoded) ? (toActor(decoded.value)?.login ?? null) : null;
349​
350/**
351 * The timeline, read out of each revision's field changes, with how many updates the page held.
352 * `revisedDate` is when a revision was superseded, `9999-01-01` on the newest, so an event is
353 * dated by the revision's changed date where Azure states one.
354 */
355export function decodeUpdatesJson(
356 raw: string,
357 closed: ClosedStates,
358): Result.Result<
359 { readonly events: ReadonlyArray<IssueEvent>; readonly count: number },
360 DecodeFailure
361> {
362 return Result.map(decodeUpdatesPage(raw), (page) => ({
363 count: (page.value ?? []).length,
364 events: (page.value ?? []).flatMap((entry) => {
365 const update = decodeUpdateEntry(entry);
366 if (Exit.isFailure(update) || update.value.id === 1) return [];
367 const { id, revisedBy, revisedDate } = update.value;
368 const fields = update.value.fields ?? {};
369 const changedDate = fields["System.ChangedDate"]?.newValue;
370 const createdAt = typeof changedDate === "string" ? changedDate : revisedDate;
371 const events: IssueEvent[] = [];
372 const add = (kind: IssueEvent["kind"], detail: string | null) =>
373 events.push({
374 id: `update-${id}-${events.length}`,
375 kind,
376 actor: toActor(revisedBy),
377 createdAt,
378 detail,
379 });
380 const state = fields["System.State"];
381 if (typeof state?.oldValue === "string" && typeof state.newValue === "string") {
382 const was = toIssueState(state.oldValue, closed);
383 const now = toIssueState(state.newValue, closed);
384 add(
385 was.category === now.category
386 ? "state-changed"
387 : now.category === "closed"
388 ? "closed"
389 : "reopened",
390 now.name,
391 );
392 }
393 const title = fields["System.Title"];
394 if (typeof title?.oldValue === "string" && typeof title.newValue === "string") {
395 add("renamed", trimmed(title.newValue));
396 }
397 const tags = fields["System.Tags"];
398 if (tags !== undefined) {
399 const before = toLabels(typeof tags.oldValue === "string" ? tags.oldValue : null);
400 const after = toLabels(typeof tags.newValue === "string" ? tags.newValue : null);
401 for (const tag of before)
402 if (!after.some((label) => label.name === tag.name)) add("unlabeled", tag.name);
403 for (const tag of after)
404 if (!before.some((label) => label.name === tag.name)) add("labeled", tag.name);
405 }
406 const assigned = fields["System.AssignedTo"];
407 if (assigned !== undefined) {
408 const before = identityLogin(assigned.oldValue);
409 const after = identityLogin(assigned.newValue);
410 if (before !== after) {
411 if (before !== null) add("unassigned", before);
412 if (after !== null) add("assigned", after);
413 }
414 }
415 return events;
416 }),
417 }));
419​
420/** A relation that links a pull request, as Azure spells it: `vstfs:///Git/PullRequestId/{project}/{repo}/{id}`. */
421export function pullRequestNumberOf(relation: typeof Relation.Type): number | null {
422 if (relation.rel !== "ArtifactLink") return null;
423 const match = /^vstfs:\/\/\/Git\/PullRequestId\/(.+)$/.exec(relation.url);
424 if (match === null) return null;
425 const number = decodeURIComponent(match[1]!).split("/").at(-1) ?? "";
426 return /^[1-9]\d{0,9}$/.test(number) ? Number(number) : null;