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