Open History to see the last commit
1/**
2 * Azure DevOps work items as an issue tracker, over `az`. Work items belong to a project, so the
3 * scope is `organization/project` and every call names the organization. Listing is a WIQL
4 * query paged by a `(changedDate, id)` keyset cursor, because WIQL has no offset.
5 */
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Result from "effect/Result";
9import * as Schema from "effect/Schema";
10import {
11 IssueTrackerKind,
12 type IssueCapabilities,
13 type IssueEvent,
14 type IssueInvolvement,
15 type IssueLinkedPullRequest,
16 type IssueViewerPermissions,
17} from "@t3tools/contracts";
18import {
19 IssueTrackerError,
20 type IssueTrackerApi,
21} from "@t3tools/source-control-core/server/IssueTracker";
22
23import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
24import {
25 azureDevOpsReactionType,
26 closedStateNames,
27 workItemStates,
28 decodeCommentsJson,
29 decodeProfileJson,
30 decodeUpdatesJson,
31 decodeWorkItemJson,
32 decodeWorkItemsJson,
33 pullRequestNumberOf,
34 type AzureDevOpsWorkItem,
35 type ClosedStates,
36} from "./azureDevOpsIssueJson.ts";
37import { decodePullRequestJson } from "./azureDevOpsPullRequestJson.ts";
38
39const KIND = IssueTrackerKind.make("azure-devops");
40
41const CAPABILITIES: IssueCapabilities = {
42 create: true,
43 edit: true,
44 comment: true,
45 labels: true,
46 assignees: true,
47 // On comments only; a work item itself takes none, and `setReaction` says so.
48 reactions: true,
49 // Azure has no issue templates. Its work item types are picked here, not by the reader.
50 templates: false,
51 linkedPullRequests: true,
52 events: true,
53 search: true,
54};
55
56/**
57 * Everything granted. Azure states no permission anywhere `az boards` reaches: the answer lives
58 * in the security namespaces, behind identity descriptors that would be several calls per work
59 * item to resolve. Controls stay live and a viewer who may not use one is told so by Azure.
60 */
61const VIEWER_PERMISSIONS: IssueViewerPermissions = {
62 setState: true,
63 comment: true,
64 edit: true,
65 labels: true,
66 assignees: true,
67};
68
69const REST_API_VERSION = "7.1";
70const PAGE_SIZE = 100;
71/** Updates are read a page per `az` process, oldest first, so a long history is bounded. */
72const UPDATE_PAGE_LIMIT = 5;
73/** Linked pull requests are read one `az` process each, so a work item's links are bounded. */
74const LINKED_PULL_REQUEST_LIMIT = 10;
75/** Which work item type a new issue is filed as, in order of preference across the stock processes. */
76const CREATE_TYPES = ["Issue", "Bug", "Task", "User Story", "Product Backlog Item"];
77
78const LIST_FIELDS = [
79 "System.Id",
80 "System.Title",
81 "System.State",
82 "System.CreatedDate",
83 "System.ChangedDate",
84 "System.CreatedBy",
85 "System.AssignedTo",
86 "System.CommentCount",
87 "System.Tags",
88 "System.TeamProject",
89 "Microsoft.VSTS.Common.ClosedDate",
90];
91
92const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
93const decodeWiql = Schema.decodeUnknownResult(
94 Schema.Struct({
95 workItems: Schema.optional(Schema.NullOr(Schema.Array(Schema.Struct({ id: Schema.Int })))),
96 }),
97);
98const decodeTypes = Schema.decodeUnknownResult(
99 Schema.Struct({
100 value: Schema.Array(
101 Schema.Struct({
102 name: Schema.String,
103 isDisabled: Schema.optional(Schema.Boolean),
104 states: Schema.optional(
105 Schema.Array(Schema.Struct({ name: Schema.String, category: Schema.String })),
106 ),
107 }),
108 ),
109 }),
110);
111const decodeTags = Schema.decodeUnknownResult(
112 Schema.Struct({ value: Schema.Array(Schema.Struct({ name: Schema.String })) }),
113);
114const decodeTeams = Schema.decodeUnknownResult(Schema.Array(Schema.Struct({ id: Schema.String })));
115const decodeMembers = Schema.decodeUnknownResult(
116 Schema.Array(
117 Schema.Struct({
118 identity: Schema.Struct({
119 uniqueName: Schema.String,
120 displayName: Schema.optional(Schema.NullOr(Schema.String)),
121 imageUrl: Schema.optional(Schema.NullOr(Schema.String)),
122 isContainer: Schema.optional(Schema.Boolean),
123 }),
124 }),
125 ),
126);
127const decodeUnknown = Schema.decodeUnknownResult(Schema.fromJsonString(Schema.Unknown));
128
129/** The parts of an `organization/project` scope, as the organization URL and the project name. */
130function parseScope(
131 host: string,
132 scope: string,
133): { readonly organization: string; readonly project: string } | null {
134 const parts = scope.split("/").flatMap((part) => part.trim() || []);
135 // `az` replaces a value starting with `@` by the contents of that local file.
136 if (parts.some((part) => part.startsWith("@"))) return null;
137 // A legacy organization is its hostname, so its scope may be the project alone.
138 if (host.toLowerCase().endsWith(".visualstudio.com")) {
139 const project = parts.length === 1 || parts.length === 2 ? parts.at(-1) : undefined;
140 return project === undefined ? null : { organization: `https://${host}`, project };
141 }
142 if (parts.length !== 2) return null;
143 const [organization, project] = parts as [string, string];
144 return { organization: `https://${host}/${encodeURIComponent(organization)}`, project };
145}
146
147function parseNumber(key: string): number | null {
148 return /^[1-9]\d{0,9}$/.test(key) ? Number(key) : null;
149}
150
151/** WIQL string literals are single-quoted and escape a quote by doubling it. */
152function quoted(value: string): string {
153 return `'${value.replaceAll("'", "''")}'`;
154}
155
156function involvementClause(involvement: IssueInvolvement): string {
157 switch (involvement) {
158 case "assigned":
159 return " AND [System.AssignedTo] = @Me";
160 case "authored":
161 return " AND [System.CreatedBy] = @Me";
162 // WIQL over REST has no way to ask who was mentioned (`@RecentMentions` is a web portal
163 // macro), so a mention filter has nothing to narrow by.
164 case "mentioned":
165 case "all":
166 return "";
167 }
168}
169
170function stateClause(state: "all" | "open" | "closed", closedStates: ClosedStates): string {
171 const closed = `(${[...closedStates].map(quoted).join(", ")})`;
172 switch (state) {
173 case "open":
174 return ` AND [System.State] NOT IN ${closed}`;
175 case "closed":
176 return ` AND [System.State] IN ${closed}`;
177 case "all":
178 return "";
179 }
180}
181
182/** `<iso date the list is sorted by>|<id>` of the last row handed over, where the next page starts. */
183function parseCursor(cursor: string): { readonly date: string; readonly id: number } | null {
184 const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)\|([1-9]\d{0,9})$/.exec(cursor);
185 return match === null ? null : { date: match[1]!, id: Number(match[2]) };
186}
187
188function reasonFor(error: AzureDevOpsCli.AzureDevOpsCliError): IssueTrackerError["reason"] {
189 switch (error._tag) {
190 case "AzureDevOpsCliUnavailableError":
191 return "missing-tool";
192 case "AzureDevOpsCliAuthenticationError":
193 return "unauthenticated";
194 case "AzureDevOpsCliRateLimitError":
195 return "rate-limited";
196 case "AzureDevOpsPullRequestNotFoundError":
197 return "not-found";
198 default:
199 return "failed";
200 }
201}
202
203export const make: Effect.Effect<
204 IssueTrackerApi,
205 never,
206 AzureDevOpsCli.AzureDevOpsCli | FileSystem.FileSystem
207> = Effect.gen(function* () {
208 const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
209 const fs = yield* FileSystem.FileSystem;
210
211 const fail = (operation: string) => (error: AzureDevOpsCli.AzureDevOpsCliError) =>
212 new IssueTrackerError({
213 tracker: KIND,
214 operation,
215 reason: reasonFor(error),
216 detail: error.detail,
217 cause: error,
218 });
219
220 const refused = (operation: string, detail: string, cause?: unknown) =>
221 new IssueTrackerError({
222 tracker: KIND,
223 operation,
224 reason: "failed",
225 detail,
226 ...(cause === undefined ? {} : { cause }),
227 });
228
229 const unreadable = (operation: string, cause: unknown) =>
230 refused(operation, `Azure DevOps returned an unreadable ${operation} response.`, cause);
231
232 const notFound = (operation: string) =>
233 new IssueTrackerError({
234 tracker: KIND,
235 operation,
236 reason: "not-found",
237 detail: "Azure DevOps could not find the requested work item.",
238 });
239
240 const scoped = (
241 operation: string,
242 input: { readonly host: string; readonly scope: string },
243 ): Effect.Effect<
244 { readonly organization: string; readonly project: string },
245 IssueTrackerError
246 > => {
247 const parsed = parseScope(input.host, input.scope);
248 return parsed === null
249 ? Effect.fail(refused(operation, "An Azure DevOps scope is named `organization/project`."))
250 : Effect.succeed(parsed);
251 };
252
253 const run = (input: {
254 readonly cwd: string;
255 readonly operation: string;
256 readonly args: ReadonlyArray<string>;
257 readonly stdin?: string | undefined;
258 }) =>
259 azure
260 .execute({
261 cwd: input.cwd,
262 args: [...input.args, "--only-show-errors", "--output", "json"],
263 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
264 })
265 .pipe(
266 Effect.map((result) => result.stdout.trim()),
267 Effect.mapError(fail(input.operation)),
268 );
269
270 const read = <A>(input: {
271 readonly cwd: string;
272 readonly operation: string;
273 readonly args: ReadonlyArray<string>;
274 readonly stdin?: string | undefined;
275 readonly decode: (raw: string) => Result.Result<A, unknown>;
276 }): Effect.Effect<A, IssueTrackerError> =>
277 run(input).pipe(
278 Effect.flatMap((raw) => {
279 const decoded = input.decode(raw);
280 return Result.isSuccess(decoded)
281 ? Effect.succeed(decoded.success)
282 : Effect.fail(unreadable(input.operation, decoded.failure));
283 }),
284 );
285
286 const decodeAs =
287 <A>(schema: (value: unknown) => Result.Result<A, unknown>) =>
288 (raw: string): Result.Result<A, unknown> =>
289 Result.flatMap(decodeUnknown(raw), schema);
290
291 /** A `wit` REST route, addressed by resource and route parameters rather than by URL. */
292 const invokeArgs = (input: {
293 readonly organization: string;
294 readonly project: string;
295 readonly resource: string;
296 readonly route?: ReadonlyArray<string>;
297 readonly query?: ReadonlyArray<string>;
298 readonly method?: string;
299 readonly apiVersion?: string;
300 }) => [
301 "devops",
302 "invoke",
303 "--detect",
304 "false",
305 "--organization",
306 input.organization,
307 "--area",
308 "wit",
309 "--resource",
310 input.resource,
311 "--api-version",
312 input.apiVersion ?? REST_API_VERSION,
313 "--route-parameters",
314 `project=${input.project}`,
315 ...(input.route ?? []),
316 ...(input.query === undefined || input.query.length === 0
317 ? []
318 : ["--query-parameters", ...input.query]),
319 ...(input.method === undefined ? [] : ["--http-method", input.method]),
320 ];
321
322 /** A request with a body, which `az devops invoke` only takes from a file. */
323 const invokeWithBody = Effect.fn("AzureDevOpsIssueTracker.invokeWithBody")(function* (input: {
324 readonly cwd: string;
325 readonly operation: string;
326 readonly args: ReadonlyArray<string>;
327 readonly body: unknown;
328 }) {
329 const unwritable = (cause: unknown) =>
330 refused(input.operation, "Could not write the Azure DevOps request body.", cause);
331 const file = yield* fs
332 .makeTempFileScoped({ prefix: "t3-azure-issue-" })
333 .pipe(Effect.mapError(unwritable));
334 yield* fs.writeFileString(file, encodeJson(input.body)).pipe(Effect.mapError(unwritable));
335 return yield* run({
336 cwd: input.cwd,
337 operation: input.operation,
338 args: [...input.args, "--in-file", file, "--media-type", "application/json"],
339 });
340 }, Effect.scoped);
341
342 const workItemTypes = (input: {
343 readonly cwd: string;
344 readonly operation: string;
345 readonly organization: string;
346 readonly project: string;
347 }) =>
348 read({
349 cwd: input.cwd,
350 operation: input.operation,
351 args: invokeArgs({ ...input, resource: "workitemtypes" }),
352 decode: decodeAs(decodeTypes),
353 }).pipe(Effect.map((types) => types.value));
354
355 const closedStates = (input: Parameters<typeof workItemTypes>[0]) =>
356 workItemTypes(input).pipe(Effect.map(closedStateNames));
357
358 const workItem = (input: {
359 readonly cwd: string;
360 readonly operation: string;
361 readonly organization: string;
362 readonly project: string;
363 readonly number: number;
364 readonly closed: ClosedStates;
365 }): Effect.Effect<AzureDevOpsWorkItem, IssueTrackerError> =>
366 read({
367 cwd: input.cwd,
368 operation: input.operation,
369 args: [
370 "boards",
371 "work-item",
372 "show",
373 "--detect",
374 "false",
375 "--organization",
376 input.organization,
377 "--id",
378 String(input.number),
379 "--expand",
380 "relations",
381 ],
382 decode: (raw) => decodeWorkItemJson(raw, input.closed),
383 }).pipe(
384 Effect.filterOrFail(
385 (item) => item !== null,
386 () => notFound(input.operation),
387 ),
388 // `az` addresses a work item by organization and id alone, so one from another project
389 // answers too; the scope names a project, and an item outside it is not this scope's.
390 Effect.filterOrFail(
391 (item) => item.project?.toLowerCase() === input.project.toLowerCase(),
392 () => notFound(input.operation),
393 ),
394 );
395
396 /** The work item as `az` addresses it, or a not-found for a key that names no id. */
397 const target = (
398 operation: string,
399 input: { readonly host: string; readonly scope: string; readonly key: string },
400 ) =>
401 scoped(operation, input).pipe(
402 Effect.flatMap((scope) => {
403 const number = parseNumber(input.key);
404 return number === null
405 ? Effect.fail(notFound(operation))
406 : Effect.succeed({ ...scope, number });
407 }),
408 );
409
410 /** Newest first, so the first page is the current discussion and a cursor leads to older ones. */
411 const comments = (input: {
412 readonly cwd: string;
413 readonly operation: string;
414 readonly organization: string;
415 readonly project: string;
416 readonly number: number;
417 readonly cursor?: string | undefined;
418 }) =>
419 read({
420 cwd: input.cwd,
421 operation: input.operation,
422 args: invokeArgs({
423 ...input,
424 resource: "comments",
425 route: [`workItemId=${input.number}`],
426 apiVersion: "7.1-preview",
427 query: [
428 `$top=${PAGE_SIZE}`,
429 "order=desc",
430 "$expand=reactions",
431 "api-version=7.1-preview.4",
432 ...(input.cursor === undefined ? [] : [`continuationToken=${input.cursor}`]),
433 ],
434 }),
435 decode: decodeCommentsJson,
436 }).pipe(Effect.map((page) => ({ ...page, comments: page.comments.toReversed() })));
437
438 const updates = Effect.fn("AzureDevOpsIssueTracker.updates")(function* (input: {
439 readonly cwd: string;
440 readonly organization: string;
441 readonly project: string;
442 readonly number: number;
443 readonly closed: ClosedStates;
444 }) {
445 const events: IssueEvent[] = [];
446 for (let page = 0; page < UPDATE_PAGE_LIMIT; page += 1) {
447 const answer = yield* read({
448 cwd: input.cwd,
449 operation: "getIssue",
450 args: invokeArgs({
451 ...input,
452 resource: "updates",
453 route: [`id=${input.number}`],
454 query: [`$top=${PAGE_SIZE}`, ...(page === 0 ? [] : [`$skip=${page * PAGE_SIZE}`])],
455 }),
456 decode: (raw) => decodeUpdatesJson(raw, input.closed),
457 });
458 events.push(...answer.events);
459 if (answer.count < PAGE_SIZE) break;
460 }
461 return events;
462 });
463
464 const linkedPullRequests = (input: {
465 readonly cwd: string;
466 readonly organization: string;
467 readonly item: AzureDevOpsWorkItem;
468 }): Effect.Effect<ReadonlyArray<IssueLinkedPullRequest>, IssueTrackerError> => {
469 const numbers = [
470 ...new Set(input.item.relations.flatMap((relation) => pullRequestNumberOf(relation) ?? [])),
471 ].slice(0, LINKED_PULL_REQUEST_LIMIT);
472 return Effect.forEach(
473 numbers,
474 (number) =>
475 read({
476 cwd: input.cwd,
477 operation: "getIssue",
478 args: [
479 "repos",
480 "pr",
481 "show",
482 "--detect",
483 "false",
484 "--organization",
485 input.organization,
486 "--id",
487 String(number),
488 ],
489 decode: decodePullRequestJson,
490 }).pipe(
491 Effect.map((pullRequest) =>
492 pullRequest === null || pullRequest.location === null
493 ? []
494 : [
495 {
496 repository: `${pullRequest.location.project}/${pullRequest.location.repository}`,
497 number: pullRequest.number,
498 title: pullRequest.title,
499 url: pullRequest.url,
500 state: pullRequest.state,
501 isDraft: pullRequest.isDraft,
502 // Azure links a pull request to a work item but never says whether completing
503 // it resolves the item; that lives in a completion option nothing reports.
504 closesIssue: false,
505 },
506 ],
507 ),
508 // A link to a pull request this account cannot see is left out, not a failed detail.
509 Effect.catchIf(
510 (error) => error.reason === "not-found",
511 () => Effect.succeed([]),
512 ),
513 ),
514 { concurrency: 2 },
515 ).pipe(Effect.map((links) => links.flat()));
516 };
517
518 const update = (input: {
519 readonly cwd: string;
520 readonly operation: string;
521 readonly organization: string;
522 readonly number: number;
523 readonly args: ReadonlyArray<string>;
524 readonly stdin?: string | undefined;
525 }) =>
526 run({
527 cwd: input.cwd,
528 operation: input.operation,
529 args: [
530 "boards",
531 "work-item",
532 "update",
533 "--detect",
534 "false",
535 "--organization",
536 input.organization,
537 "--id",
538 String(input.number),
539 ...input.args,
540 ],
541 stdin: input.stdin,
542 }).pipe(Effect.asVoid);
543
544 /** A write names its work item by id alone, so the item is first read to be the scope's own. */
545 const owned = (
546 operation: string,
547 cwd: string,
548 scope: { readonly organization: string; readonly project: string; readonly number: number },
549 ) => workItem({ ...scope, cwd, operation, closed: new Set() }).pipe(Effect.as(scope));
550
551 /** Azure keeps tags as one `; `-joined field and takes exactly one assignee. */
552 const fieldArgs = (
553 operation: string,
554 input: {
555 readonly labels?: ReadonlyArray<string> | undefined;
556 readonly assignees?: ReadonlyArray<string> | undefined;
557 },
558 ): Effect.Effect<ReadonlyArray<string>, IssueTrackerError> => {
559 if ((input.assignees?.length ?? 0) > 1) {
560 return Effect.fail(refused(operation, "An Azure DevOps work item has one assignee at most."));
561 }
562 const fields = [
563 ...(input.labels === undefined ? [] : [["System.Tags", input.labels.join("; ")] as const]),
564 ...(input.assignees === undefined
565 ? []
566 : [["System.AssignedTo", input.assignees[0] ?? ""] as const]),
567 ];
568 // `az` reads `field=@path` as that local file, and a field value has no stdin to go through.
569 if (fields.some(([, value]) => value.startsWith("@"))) {
570 return Effect.fail(
571 refused(operation, "Azure DevOps takes no label or assignee that starts with `@`."),
572 );
573 }
574 return Effect.succeed(
575 fields.length === 0 ? [] : ["--fields", ...fields.map(([name, value]) => `${name}=${value}`)],
576 );
577 };
578
579 return {
580 kind: KIND,
581 capabilities: CAPABILITIES,
582
583 // The profile the token belongs to, which is what WIQL's `@Me` resolves to. Its email is the
584 // `uniqueName` every identity on a work item carries, so the two compare.
585 getViewer: (input) =>
586 read({
587 cwd: input.cwd,
588 operation: "getViewer",
589 args: [
590 "devops",
591 "invoke",
592 "--detect",
593 "true",
594 "--area",
595 "profile",
596 "--resource",
597 "profiles",
598 "--api-version",
599 REST_API_VERSION,
600 "--route-parameters",
601 "id=me",
602 ],
603 decode: decodeProfileJson,
604 }).pipe(
605 Effect.filterOrFail(
606 (login) => login !== null,
607 () => refused("getViewer", "Azure DevOps could not name the signed-in account."),
608 ),
609 ),
610
611 listIssues: Effect.fn("AzureDevOpsIssueTracker.listIssues")(function* (input) {
612 const cursor = input.cursor === undefined ? undefined : parseCursor(input.cursor);
613 if (cursor === null) {
614 return yield* refused("listIssues", "The cursor was not one Azure DevOps handed out.");
615 }
616 const limit = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
617 const text = input.query?.trim() ?? "";
618 const created = input.sort === "created";
619 const dateField = created ? "[System.CreatedDate]" : "[System.ChangedDate]";
620 return yield* scoped("listIssues", input).pipe(
621 Effect.flatMap((scope) =>
622 closedStates({ ...scope, cwd: input.cwd, operation: "listIssues" }).pipe(
623 Effect.map((closed) => ({ scope, closed })),
624 ),
625 ),
626 Effect.flatMap(({ scope, closed }) =>
627 invokeWithBody({
628 cwd: input.cwd,
629 operation: "listIssues",
630 args: invokeArgs({
631 ...scope,
632 resource: "wiql",
633 method: "POST",
634 // One more than the page, which is how a next page reveals itself.
635 query: ["timePrecision=true", `$top=${limit + 1}`],
636 }),
637 body: {
638 query:
639 `SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = ${quoted(scope.project)}` +
640 stateClause(input.state, closed) +
641 involvementClause(input.involvement) +
642 (text.length === 0 ? "" : ` AND [System.Title] CONTAINS ${quoted(text)}`) +
643 (input.labels ?? [])
644 .map((label) => ` AND [System.Tags] CONTAINS ${quoted(label)}`)
645 .join("") +
646 (input.assignee === undefined
647 ? ""
648 : ` AND [System.AssignedTo] = ${quoted(input.assignee)}`) +
649 (cursor === undefined
650 ? ""
651 : ` AND (${dateField} < ${quoted(cursor.date)} OR (${dateField} = ${quoted(cursor.date)} AND [System.Id] < ${cursor.id}))`) +
652 ` ORDER BY ${dateField} DESC, [System.Id] DESC`,
653 },
654 }).pipe(
655 Effect.flatMap((raw) => {
656 const decoded = decodeAs(decodeWiql)(raw);
657 return Result.isSuccess(decoded)
658 ? Effect.succeed(decoded.success.workItems ?? [])
659 : Effect.fail(unreadable("listIssues", decoded.failure));
660 }),
661 Effect.flatMap((ids) =>
662 ids.length === 0
663 ? Effect.succeed({ items: [], nextCursor: null })
664 : read({
665 cwd: input.cwd,
666 operation: "listIssues",
667 args: invokeArgs({
668 ...scope,
669 resource: "workitems",
670 query: [
671 `ids=${ids
672 .slice(0, limit)
673 .map((row) => row.id)
674 .join(",")}`,
675 `fields=${LIST_FIELDS.join(",")}`,
676 ],
677 }),
678 decode: (raw) => decodeWorkItemsJson(raw, closed),
679 }).pipe(
680 Effect.map((hydrated) => {
681 // The cursor is the last row WIQL sorted, so its order is restored.
682 const position = new Map(ids.map((row, index) => [String(row.id), index]));
683 const items = hydrated.toSorted(
684 (left, right) =>
685 (position.get(left.key) ?? 0) - (position.get(right.key) ?? 0),
686 );
687 const last = items.at(-1);
688 return {
689 items,
690 nextCursor:
691 ids.length > limit && last !== undefined
692 ? `${created ? last.createdAt : last.updatedAt}|${last.key}`
693 : null,
694 };
695 }),
696 ),
697 ),
698 ),
699 ),
700 );
701 }),
702
703 getIssue: (input) =>
704 target("getIssue", input).pipe(
705 Effect.flatMap((scope) =>
706 workItemTypes({ ...scope, cwd: input.cwd, operation: "getIssue" }).pipe(
707 Effect.flatMap((types) => {
708 const closed = closedStateNames(types);
709 return workItem({ ...scope, cwd: input.cwd, operation: "getIssue", closed }).pipe(
710 Effect.map((item) => ({ item, closed, states: workItemStates(types, item) })),
711 );
712 }),
713 Effect.flatMap(({ item, closed, states }) =>
714 Effect.all(
715 [
716 comments({ ...scope, cwd: input.cwd, operation: "getIssue" }),
717 updates({ ...scope, cwd: input.cwd, closed }),
718 linkedPullRequests({ cwd: input.cwd, organization: scope.organization, item }),
719 ],
720 { concurrency: 3 },
721 ).pipe(
722 Effect.map(([conversation, events, links]) => ({
723 ...item,
724 // Its type's own entry, so the category is the one that type gives the name.
725 state: states.find((state) => state.name === item.state.name) ?? item.state,
726 states,
727 // Nothing cheap names the viewer here; the service already read it per host.
728 viewer: null,
729 viewerPermissions: VIEWER_PERMISSIONS,
730 comments: conversation.comments,
731 commentsCursor: conversation.nextCursor,
732 events,
733 linkedPullRequests: links,
734 })),
735 ),
736 ),
737 ),
738 ),
739 ),
740
741 getComments: (input) =>
742 target("getComments", input).pipe(
743 // `az` would read a `continuationToken=@path` as that local file.
744 Effect.filterOrFail(
745 () => !input.cursor.startsWith("@"),
746 () => refused("getComments", "The cursor was not one Azure DevOps handed out."),
747 ),
748 Effect.flatMap((scope) =>
749 comments({ ...scope, cwd: input.cwd, operation: "getComments", cursor: input.cursor }),
750 ),
751 ),
752
753 create: (input) => {
754 const title = AzureDevOpsCli.textOption("--title", input.title);
755 const body =
756 input.body.length === 0
757 ? undefined
758 : AzureDevOpsCli.textOption("--description", input.body);
759 // az has one stdin, so a second value read from it goes in a call of its own.
760 const bodyFollows = title.stdin !== undefined && body?.stdin !== undefined;
761 return scoped("create", input).pipe(
762 Effect.flatMap((scope) =>
763 workItemTypes({ ...scope, cwd: input.cwd, operation: "create" }).pipe(
764 Effect.flatMap((types) => {
765 const names = types.flatMap((type) => (type.isDisabled ? [] : [type.name]));
766 const type = CREATE_TYPES.find((name) => names.includes(name)) ?? names[0];
767 return type === undefined
768 ? Effect.fail(refused("create", "The project offers no work item type to file."))
769 : fieldArgs("create", {
770 ...(input.labels.length === 0 ? {} : { labels: input.labels }),
771 ...(input.assignees.length === 0 ? {} : { assignees: input.assignees }),
772 }).pipe(
773 Effect.map((fields) => ({ type, fields, closed: closedStateNames(types) })),
774 );
775 }),
776 Effect.flatMap(({ type, fields, closed }) =>
777 read({
778 cwd: input.cwd,
779 operation: "create",
780 args: [
781 "boards",
782 "work-item",
783 "create",
784 "--detect",
785 "false",
786 "--organization",
787 scope.organization,
788 "--project",
789 scope.project,
790 "--type",
791 type,
792 title.arg,
793 ...(body === undefined || bodyFollows ? [] : [body.arg]),
794 ...fields,
795 ],
796 stdin: title.stdin ?? body?.stdin,
797 decode: (raw) => decodeWorkItemJson(raw, closed),
798 }),
799 ),
800 Effect.filterOrFail(
801 (item) => item !== null,
802 () => unreadable("create", "incomplete-response"),
803 ),
804 Effect.tap((item) =>
805 body === undefined || !bodyFollows
806 ? Effect.void
807 : update({
808 cwd: input.cwd,
809 operation: "create",
810 organization: scope.organization,
811 number: Number(item.key),
812 args: [body.arg],
813 stdin: body.stdin,
814 }),
815 ),
816 Effect.map((item) => ({ key: item.key, displayKey: item.displayKey, url: item.url })),
817 ),
818 ),
819 );
820 },
821
822 comment: (input) =>
823 target("comment", input).pipe(
824 Effect.flatMap((scope) =>
825 invokeWithBody({
826 cwd: input.cwd,
827 operation: "comment",
828 args: invokeArgs({
829 ...scope,
830 resource: "comments",
831 route: [`workItemId=${scope.number}`],
832 method: "POST",
833 apiVersion: "7.1-preview",
834 query: ["format=markdown", "api-version=7.1-preview.4"],
835 }),
836 body: { text: input.body },
837 }),
838 ),
839 Effect.asVoid,
840 ),
841
842 update: (input) => {
843 const texts = [
844 ...(input.title === undefined ? [] : [AzureDevOpsCli.textOption("--title", input.title)]),
845 ...(input.body === undefined
846 ? []
847 : [AzureDevOpsCli.textOption("--description", input.body)]),
848 ];
849 // az has one stdin, so each value read from it needs its own call.
850 const batches =
851 texts.filter((text) => text.stdin !== undefined).length > 1
852 ? texts.map((text) => [text])
853 : [texts];
854 return target("update", input).pipe(
855 Effect.flatMap((scope) =>
856 fieldArgs("update", input).pipe(Effect.map((fields) => ({ scope, fields }))),
857 ),
858 Effect.tap(({ scope }) => owned("update", input.cwd, scope)),
859 Effect.flatMap(({ scope, fields }) =>
860 Effect.forEach(
861 batches,
862 (batch, index) =>
863 update({
864 ...scope,
865 cwd: input.cwd,
866 operation: "update",
867 args: [...batch.map((text) => text.arg), ...(index === 0 ? fields : [])],
868 stdin: batch.find((text) => text.stdin !== undefined)?.stdin,
869 }),
870 { discard: true },
871 ),
872 ),
873 );
874 },
875
876 setState: (input) =>
877 target("setState", input).pipe(
878 // The read also proves the item is the scope's own, as `owned` does for other writes.
879 Effect.flatMap((scope) =>
880 workItem({ ...scope, cwd: input.cwd, operation: "setState", closed: new Set() }).pipe(
881 Effect.flatMap((item) =>
882 workItemTypes({ ...scope, cwd: input.cwd, operation: "setState" }).pipe(
883 Effect.map((types) => workItemStates(types, item)),
884 ),
885 ),
886 Effect.filterOrFail(
887 (states) => states.some((state) => state.name === input.state),
888 () => refused("setState", `This work item has no "${input.state}" state.`),
889 ),
890 Effect.flatMap(() =>
891 update({
892 ...scope,
893 cwd: input.cwd,
894 operation: "setState",
895 args: ["--state", input.state],
896 }),
897 ),
898 ),
899 ),
900 ),
901
902 setReaction: (input) =>
903 target("setReaction", input).pipe(
904 Effect.flatMap((scope) => {
905 const type = azureDevOpsReactionType(input.content);
906 if (input.subjectId === undefined) {
907 return Effect.fail(
908 refused("setReaction", "Azure DevOps reactions go on comments only."),
909 );
910 }
911 if (!/^[1-9]\d{0,9}$/.test(input.subjectId)) {
912 return Effect.fail(
913 refused("setReaction", "The comment id names no Azure DevOps comment."),
914 );
915 }
916 if (type === null) {
917 return Effect.fail(refused("setReaction", "Azure DevOps has no such reaction."));
918 }
919 return run({
920 cwd: input.cwd,
921 operation: "setReaction",
922 args: invokeArgs({
923 ...scope,
924 resource: "commentsReactions",
925 route: [
926 `workItemId=${scope.number}`,
927 `commentId=${input.subjectId}`,
928 `reactionType=${type}`,
929 ],
930 method: input.reacted ? "PUT" : "DELETE",
931 apiVersion: "7.1-preview",
932 query: ["api-version=7.1-preview.1"],
933 }),
934 }).pipe(Effect.asVoid);
935 }),
936 ),
937
938 listCandidates: (input) =>
939 scoped("listCandidates", input).pipe(
940 Effect.flatMap((scope) =>
941 Effect.all(
942 [
943 read({
944 cwd: input.cwd,
945 operation: "listCandidates",
946 args: invokeArgs({ ...scope, resource: "tags" }),
947 decode: decodeAs(decodeTags),
948 }).pipe(
949 Effect.map((tags) =>
950 tags.value.map((tag) => ({ name: tag.name, color: null, description: null })),
951 ),
952 ),
953 // Nothing in `az boards` lists who a work item may go to; the project's teams are
954 // the nearest thing, read a handful at a time.
955 read({
956 cwd: input.cwd,
957 operation: "listCandidates",
958 args: [
959 "devops",
960 "team",
961 "list",
962 "--detect",
963 "false",
964 "--organization",
965 scope.organization,
966 "--project",
967 scope.project,
968 "--top",
969 "10",
970 ],
971 decode: decodeAs(decodeTeams),
972 }).pipe(
973 Effect.flatMap((teams) =>
974 Effect.forEach(
975 teams,
976 (team) =>
977 read({
978 cwd: input.cwd,
979 operation: "listCandidates",
980 args: [
981 "devops",
982 "team",
983 "list-member",
984 "--detect",
985 "false",
986 "--organization",
987 scope.organization,
988 "--project",
989 scope.project,
990 "--team",
991 team.id,
992 "--top",
993 String(PAGE_SIZE),
994 ],
995 decode: decodeAs(decodeMembers),
996 }),
997 { concurrency: 3 },
998 ),
999 ),
1000 Effect.map((members) => {
1001 const byLogin = new Map<
1002 string,
1003 { id: string; login: string; name: string | null; avatarUrl: string | null }
1004 >();
1005 for (const { identity } of members.flat()) {
1006 const login = identity.uniqueName.trim();
1007 if (
1008 identity.isContainer ||
1009 login.length === 0 ||
1010 byLogin.has(login.toLowerCase())
1011 ) {
1012 continue;
1013 }
1014 byLogin.set(login.toLowerCase(), {
1015 id: login,
1016 login,
1017 name: identity.displayName?.trim() || null,
1018 avatarUrl: identity.imageUrl?.trim() || null,
1019 });
1020 }
1021 return [...byLogin.values()];
1022 }),
1023 ),
1024 ],
1025 { concurrency: 2 },
1026 ),
1027 ),
1028 // Teams are a sample of who can be assigned, so somebody missing is not ineligible.
1029 Effect.map(([labels, assignees]) => ({ labels, assignees, truncated: true })),
1030 ),
1031 };
1032});