The best way to control Claude Code, Codex and more from any computer or phone

main
ts 652 lines 23.2 KB
Raw
1 import {
2 trimOptionalString as trimmed,
3 normalizeRefName,
4 } from "@t3tools/source-control-core/server/pullRequestUtils";
5 import * as Cause from "effect/Cause";
6 import * as Exit from "effect/Exit";
7 import * as Result from "effect/Result";
8 import * as Schema from "effect/Schema";
9 import type {
10 PullRequestActor,
11 PullRequestCheck,
12 PullRequestComment,
13 PullRequestLabel,
14 PullRequestMergeMethod,
15 PullRequestMergeability,
16 PullRequestState,
17 } from "@t3tools/contracts";
18 import { TrimmedNonEmptyString } from "@t3tools/contracts";
19 import { decodeJsonResult } from "@t3tools/shared/schemaJson";
20
21 import { azureDevOpsPullRequestWebUrl } from "./azureDevOpsPullRequests.ts";
22
23 // CLI fields vary by command; unknown enum values must not fail the payload.
24 const RawIdentitySchema = Schema.Struct({
25 displayName: Schema.optional(Schema.NullOr(Schema.String)),
26 uniqueName: Schema.optional(Schema.NullOr(Schema.String)),
27 imageUrl: Schema.optional(Schema.NullOr(Schema.String)),
28 });
29
30 const RawLabelSchema = Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) });
31
32 const RawPullRequestSchema = Schema.Struct({
33 pullRequestId: Schema.Int,
34 title: Schema.String,
35 description: Schema.optional(Schema.NullOr(Schema.String)),
36 status: Schema.optional(Schema.NullOr(Schema.String)),
37 isDraft: Schema.optional(Schema.NullOr(Schema.Boolean)),
38 /** This identity's presence indicates auto-complete. */
39 autoCompleteSetBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
40 completionOptions: Schema.optional(
41 Schema.NullOr(
42 Schema.Struct({
43 mergeStrategy: Schema.optional(Schema.NullOr(Schema.String)),
44 squashMerge: Schema.optional(Schema.NullOr(Schema.Boolean)),
45 }),
46 ),
47 ),
48 mergeStatus: Schema.optional(Schema.NullOr(Schema.String)),
49 createdBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
50 reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawIdentitySchema))),
51 /** `az repos pr list` fills this; `az repos pr show` returns null. */
52 labels: Schema.optional(Schema.NullOr(Schema.Array(RawLabelSchema))),
53 sourceRefName: TrimmedNonEmptyString,
54 targetRefName: TrimmedNonEmptyString,
55 creationDate: TrimmedNonEmptyString,
56 closedDate: Schema.optional(Schema.NullOr(Schema.String)),
57 url: Schema.optional(Schema.NullOr(Schema.String)),
58 repository: Schema.optional(
59 Schema.NullOr(
60 Schema.Struct({
61 name: Schema.optional(Schema.NullOr(Schema.String)),
62 webUrl: Schema.optional(Schema.NullOr(Schema.String)),
63 project: Schema.optional(
64 Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) })),
65 ),
66 }),
67 ),
68 ),
69 _links: Schema.optional(
70 Schema.NullOr(
71 Schema.Struct({
72 web: Schema.optional(
73 Schema.NullOr(Schema.Struct({ href: Schema.optional(Schema.String) })),
74 ),
75 }),
76 ),
77 ),
78 });
79
80 const RawThreadSchema = Schema.Struct({
81 id: Schema.Int,
82 isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
83 threadContext: Schema.optional(
84 Schema.NullOr(Schema.Struct({ filePath: Schema.optional(Schema.NullOr(Schema.String)) })),
85 ),
86 comments: Schema.optional(
87 Schema.NullOr(
88 Schema.Array(
89 Schema.Struct({
90 id: Schema.optional(Schema.NullOr(Schema.Int)),
91 content: Schema.optional(Schema.NullOr(Schema.String)),
92 author: Schema.optional(Schema.NullOr(RawIdentitySchema)),
93 publishedDate: Schema.optional(Schema.NullOr(Schema.String)),
94 isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
95 commentType: Schema.optional(Schema.NullOr(Schema.String)),
96 }),
97 ),
98 ),
99 ),
100 });
101
102 const RawThreadPageSchema = Schema.Struct({
103 value: Schema.Array(Schema.Unknown),
104 });
105
106 const RawViewerSchema = Schema.Struct({
107 user: Schema.optional(
108 Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) })),
109 ),
110 });
111
112 const RawPolicyEvaluationSchema = Schema.Struct({
113 status: Schema.String,
114 context: Schema.optional(
115 Schema.NullOr(
116 Schema.Struct({
117 buildId: Schema.optional(Schema.NullOr(Schema.Int)),
118 buildDefinitionName: Schema.optional(Schema.NullOr(Schema.String)),
119 isExpired: Schema.optional(Schema.NullOr(Schema.Boolean)),
120 }),
121 ),
122 ),
123 configuration: Schema.Struct({
124 url: Schema.optional(Schema.NullOr(Schema.String)),
125 isBlocking: Schema.optional(Schema.NullOr(Schema.Boolean)),
126 isEnabled: Schema.optional(Schema.NullOr(Schema.Boolean)),
127 isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
128 type: Schema.Struct({
129 id: Schema.String,
130 displayName: Schema.optional(Schema.NullOr(Schema.String)),
131 }),
132 settings: Schema.optional(
133 Schema.NullOr(
134 Schema.Struct({
135 displayName: Schema.optional(Schema.NullOr(Schema.String)),
136 defaultDisplayName: Schema.optional(Schema.NullOr(Schema.String)),
137 statusName: Schema.optional(Schema.NullOr(Schema.String)),
138 manualQueueOnly: Schema.optional(Schema.NullOr(Schema.Boolean)),
139 }),
140 ),
141 ),
142 }),
143 });
144
145 export interface AzureDevOpsRepositoryLocation {
146 readonly project: string;
147 readonly repository: string;
148 }
149
150 export interface AzureDevOpsPullRequest {
151 readonly number: number;
152 readonly title: string;
153 readonly url: string;
154 readonly author: PullRequestActor | null;
155 readonly headBranch: string;
156 readonly baseBranch: string;
157 readonly state: PullRequestState;
158 readonly isDraft: boolean;
159 readonly mergeability: PullRequestMergeability;
160 readonly createdAt: string;
161 readonly updatedAt: string;
162 readonly closedAt: string | null;
163 readonly body: string;
164 readonly reviewRequestLogins: ReadonlyArray<string>;
165 readonly reviewers: ReadonlyArray<PullRequestActor>;
166 readonly labels: ReadonlyArray<PullRequestLabel>;
167 readonly location: AzureDevOpsRepositoryLocation | null;
168 readonly autoMergeEnabled: boolean;
169 readonly autoMergeMethod?: PullRequestMergeMethod;
170 }
171
172 /** Logins must match the email from `az account show`. */
173 function toActor(raw: Schema.Schema.Type<typeof RawIdentitySchema> | null | undefined) {
174 const login = trimmed(raw?.uniqueName) ?? trimmed(raw?.displayName);
175 return login === null
176 ? null
177 : { login, name: trimmed(raw?.displayName), avatarUrl: trimmed(raw?.imageUrl) };
178 }
179
180 function toLabels(
181 raw: ReadonlyArray<Schema.Schema.Type<typeof RawLabelSchema>> | null | undefined,
182 ): ReadonlyArray<PullRequestLabel> {
183 return (raw ?? []).flatMap((label) => {
184 const name = trimmed(label.name);
185 return name === null ? [] : [{ name, color: null }];
186 });
187 }
188
189 function toState(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): PullRequestState {
190 switch (raw.status?.trim().toLowerCase()) {
191 case "completed":
192 return "merged";
193 case "abandoned":
194 return "closed";
195 default:
196 return "open";
197 }
198 }
199
200 function toMergeability(value: string | null | undefined): PullRequestMergeability {
201 switch (value?.trim().toLowerCase()) {
202 case "succeeded":
203 return "mergeable";
204 case "conflicts":
205 case "failure":
206 case "rejectedbypolicy":
207 return "conflicting";
208 default:
209 return "unknown";
210 }
211 }
212
213 function toLocation(
214 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
215 ): AzureDevOpsRepositoryLocation | null {
216 const project = trimmed(raw.repository?.project?.name);
217 const repository = trimmed(raw.repository?.name);
218 if (project === null || repository === null) return null;
219 return { project, repository };
220 }
221
222 function toAutoMergeMethod(
223 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
224 ): PullRequestMergeMethod | undefined {
225 if (raw.autoCompleteSetBy == null) return undefined;
226 switch (raw.completionOptions?.mergeStrategy?.trim().toLowerCase()) {
227 case "squash":
228 return "squash";
229 case "rebase":
230 case "rebasemerge":
231 return "rebase";
232 case "nofastforward":
233 return "merge";
234 default:
235 return raw.completionOptions?.squashMerge === true ? "squash" : undefined;
236 }
237 }
238
239 function toPullRequest(
240 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
241 ): AzureDevOpsPullRequest | null {
242 const autoMergeMethod = toAutoMergeMethod(raw);
243 const reviewers = (raw.reviewers ?? []).flatMap((reviewer) => {
244 const actor = toActor(reviewer);
245 return actor === null ? [] : [actor];
246 });
247 const closedAt = trimmed(raw.closedDate);
248 const url = trimmed(
249 azureDevOpsPullRequestWebUrl({
250 pullRequestId: raw.pullRequestId,
251 webLink: raw._links?.web?.href,
252 repositoryWebUrl: raw.repository?.webUrl,
253 restApiUrl: raw.url,
254 projectName: raw.repository?.project?.name,
255 repositoryName: raw.repository?.name,
256 }),
257 );
258 const headBranch = trimmed(normalizeRefName(raw.sourceRefName));
259 const baseBranch = trimmed(normalizeRefName(raw.targetRefName));
260 if (url === null || headBranch === null || baseBranch === null) return null;
261 return {
262 number: raw.pullRequestId,
263 title: raw.title,
264 url,
265 author: toActor(raw.createdBy),
266 headBranch,
267 baseBranch,
268 state: toState(raw),
269 isDraft: raw.isDraft ?? false,
270 mergeability: toMergeability(raw.mergeStatus),
271 createdAt: raw.creationDate,
272 updatedAt: closedAt ?? raw.creationDate,
273 closedAt,
274 body: raw.description ?? "",
275 reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),
276 reviewers,
277 labels: toLabels(raw.labels),
278 location: toLocation(raw),
279 autoMergeEnabled: (raw.autoCompleteSetBy ?? null) !== null,
280 ...(autoMergeMethod === undefined ? {} : { autoMergeMethod }),
281 };
282 }
283
284 const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
285 const decodePullRequestEntry = Schema.decodeUnknownExit(RawPullRequestSchema);
286 const decodePullRequest = decodeJsonResult(RawPullRequestSchema);
287 const decodeThreadPage = decodeJsonResult(RawThreadPageSchema);
288 const decodeThreadEntry = Schema.decodeUnknownExit(RawThreadSchema);
289 const decodeViewer = decodeJsonResult(RawViewerSchema);
290 const decodeLabelPage = decodeJsonResult(Schema.Struct({ value: Schema.Array(Schema.Unknown) }));
291 const decodeLabelEntry = Schema.decodeUnknownExit(RawLabelSchema);
292 const decodePolicyEvaluations = decodeJsonResult(Schema.Array(RawPolicyEvaluationSchema));
293
294 type DecodeFailure = Cause.Cause<Schema.SchemaError>;
295
296 export interface AzureDevOpsPullRequestBatch {
297 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
298 readonly rawIndexes: ReadonlyArray<number>;
299 /** Count before decoding to avoid ending pagination on skipped rows. */
300 readonly rawCount: number;
301 }
302
303 export function decodePullRequestListJson(
304 raw: string,
305 ): Result.Result<AzureDevOpsPullRequestBatch, DecodeFailure> {
306 const decoded = decodeUnknownList(raw);
307 if (!Result.isSuccess(decoded)) {
308 return Result.fail(decoded.failure);
309 }
310 const items: AzureDevOpsPullRequest[] = [];
311 const rawIndexes: number[] = [];
312 for (const [rawIndex, entry] of decoded.success.entries()) {
313 const item = decodePullRequestEntry(entry);
314 if (Exit.isFailure(item)) continue;
315 const pullRequest = toPullRequest(item.value);
316 if (pullRequest !== null) {
317 items.push(pullRequest);
318 rawIndexes.push(rawIndex);
319 }
320 }
321 return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length });
322 }
323
324 /** Null means Azure returned insufficient data. */
325 export function decodePullRequestJson(
326 raw: string,
327 ): Result.Result<AzureDevOpsPullRequest | null, DecodeFailure> {
328 const decoded = decodePullRequest(raw);
329 return Result.isSuccess(decoded)
330 ? Result.succeed(toPullRequest(decoded.success))
331 : Result.fail(decoded.failure);
332 }
333
334 export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
335 const decoded = decodeViewer(raw);
336 return Result.isSuccess(decoded)
337 ? Result.succeed(trimmed(decoded.success.user?.name))
338 : Result.fail(decoded.failure);
339 }
340
341 export function decodeLabelsJson(
342 raw: string,
343 ): Result.Result<ReadonlyArray<PullRequestLabel>, DecodeFailure> {
344 const decoded = decodeLabelPage(raw);
345 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
346 return Result.succeed(
347 toLabels(
348 decoded.success.value.flatMap((entry) => {
349 const label = decodeLabelEntry(entry);
350 return Exit.isFailure(label) ? [] : [label.value];
351 }),
352 ),
353 );
354 }
355
356 export function decodeThreadsJson(
357 raw: string,
358 ): Result.Result<ReadonlyArray<PullRequestComment>, DecodeFailure> {
359 const decoded = decodeThreadPage(raw);
360 if (!Result.isSuccess(decoded)) {
361 return Result.fail(decoded.failure);
362 }
363 const comments: PullRequestComment[] = [];
364 for (const entry of decoded.success.value) {
365 const decodedThread = decodeThreadEntry(entry);
366 if (Exit.isFailure(decodedThread)) continue;
367 const thread = decodedThread.value;
368 if (thread.isDeleted === true) continue;
369 const path = toRepositoryPath(thread.threadContext?.filePath);
370 for (const comment of thread.comments ?? []) {
371 const publishedDate = trimmed(comment.publishedDate);
372 if (
373 comment.isDeleted === true ||
374 comment.commentType?.trim().toLowerCase() === "system" ||
375 (comment.content ?? "").trim().length === 0 ||
376 publishedDate === null
377 ) {
378 continue;
379 }
380 comments.push({
381 id: `${thread.id}:${comment.id ?? 0}`,
382 kind: path === null ? "issue-comment" : "review-comment",
383 author: toActor(comment.author),
384 body: comment.content ?? "",
385 createdAt: publishedDate,
386 url: null,
387 path,
388 reviewState: null,
389 });
390 }
391 }
392 return Result.succeed(
393 comments.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
394 );
395 }
396
397 type RawPolicyEvaluation = Schema.Schema.Type<typeof RawPolicyEvaluationSchema>;
398
399 const BUILD_POLICY_TYPE = "0609b952-1397-4640-95ec-e00a01b2c241";
400 const STATUS_POLICY_TYPE = "cbdc66da-9728-4af8-aada-9a5a32e4a226";
401 // Other policy types wait on people or restrict pushes, so they would read as checks that never end.
402 const CHECK_POLICY_TYPES = new Set([BUILD_POLICY_TYPE, STATUS_POLICY_TYPE]);
403
404 /** Azure reports `queued` for a build that will never start on its own, so name those apart. */
405 function toPolicyCheckProgress(
406 raw: RawPolicyEvaluation,
407 ): Pick<PullRequestCheck, "status" | "description"> {
408 const settled = (status: PullRequestCheck["status"]) => ({ status, description: null });
409 switch (raw.status.trim().toLowerCase()) {
410 case "approved":
411 return settled("success");
412 case "rejected":
413 case "broken":
414 return settled("failure");
415 case "running":
416 return settled("pending");
417 case "notapplicable":
418 return settled("skipped");
419 case "queued":
420 break;
421 default:
422 // A watch counts anything settled as passed, so an unknown status cannot be.
423 return settled("pending");
424 }
425 const expired = raw.context?.isExpired === true;
426 if (!expired && raw.configuration.settings?.manualQueueOnly !== true) return settled("pending");
427 // Only a blocking build holds the pull request; an optional one nobody queues never runs.
428 return {
429 status: raw.configuration.isBlocking === true ? "action-required" : "skipped",
430 description: expired ? "Expired. Queue it again on Azure DevOps." : "Queue it on Azure DevOps.",
431 };
432 }
433
434 /** The evaluation's configuration URL opens at the project the policy belongs to. */
435 function toPolicyCheckUrl(raw: RawPolicyEvaluation): string | null {
436 const buildId = raw.context?.buildId;
437 const [projectUrl, rest] = (raw.configuration.url ?? "").split("/_apis/", 2);
438 return buildId == null || rest === undefined
439 ? null
440 : `${projectUrl}/_build/results?buildId=${buildId}`;
441 }
442
443 function toPolicyCheck(raw: RawPolicyEvaluation, isDraft: boolean): PullRequestCheck | null {
444 const { configuration, context } = raw;
445 if (
446 !CHECK_POLICY_TYPES.has(configuration.type.id.toLowerCase()) ||
447 configuration.isEnabled === false ||
448 configuration.isDeleted === true
449 ) {
450 return null;
451 }
452 // A build Azure holds back on a draft stays out, as nothing would ever finish it.
453 if (isDraft && raw.status.trim().toLowerCase() === "queued" && context?.buildId == null) {
454 return null;
455 }
456 return {
457 name:
458 trimmed(configuration.settings?.displayName) ??
459 trimmed(configuration.settings?.defaultDisplayName) ??
460 trimmed(context?.buildDefinitionName) ??
461 trimmed(configuration.settings?.statusName) ??
462 trimmed(configuration.type.displayName) ??
463 "Policy",
464 ...toPolicyCheckProgress(raw),
465 url: toPolicyCheckUrl(raw),
466 required: configuration.isBlocking === true,
467 };
468 }
469
470 export interface AzureDevOpsPolicyCheckPage {
471 readonly checks: ReadonlyArray<PullRequestCheck>;
472 /** Evaluations of every policy type, so filtered rows cannot hide a next page. */
473 readonly rawCount: number;
474 }
475
476 /** Unlike the tolerant decoders above, one bad row fails the page: a lost required check reads as passed. */
477 export function decodePolicyChecksJson(
478 raw: string,
479 input: { readonly isDraft: boolean },
480 ): Result.Result<AzureDevOpsPolicyCheckPage, DecodeFailure> {
481 const decoded = decodePolicyEvaluations(raw);
482 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
483 return Result.succeed({
484 checks: decoded.success.flatMap((evaluation) => {
485 const check = toPolicyCheck(evaluation, input.isDraft);
486 return check === null ? [] : [check];
487 }),
488 rawCount: decoded.success.length,
489 });
490 }
491
492 const RawIterationSchema = Schema.Struct({
493 id: Schema.Int,
494 sourceRefCommit: Schema.optional(
495 Schema.NullOr(Schema.Struct({ commitId: Schema.optional(Schema.NullOr(Schema.String)) })),
496 ),
497 commonRefCommit: Schema.optional(
498 Schema.NullOr(Schema.Struct({ commitId: Schema.optional(Schema.NullOr(Schema.String)) })),
499 ),
500 });
501
502 const RawIterationPageSchema = Schema.Struct({ value: Schema.Array(Schema.Unknown) });
503
504 const RawChangeEntrySchema = Schema.Struct({
505 changeType: Schema.optional(Schema.NullOr(Schema.String)),
506 sourceServerItem: Schema.optional(Schema.NullOr(Schema.String)),
507 originalPath: Schema.optional(Schema.NullOr(Schema.String)),
508 item: Schema.optional(
509 Schema.NullOr(
510 Schema.Struct({
511 path: Schema.optional(Schema.NullOr(Schema.String)),
512 objectId: Schema.optional(Schema.NullOr(Schema.String)),
513 originalObjectId: Schema.optional(Schema.NullOr(Schema.String)),
514 isFolder: Schema.optional(Schema.NullOr(Schema.Boolean)),
515 gitObjectType: Schema.optional(Schema.NullOr(Schema.String)),
516 }),
517 ),
518 ),
519 });
520
521 const RawChangePageSchema = Schema.Struct({
522 changeEntries: Schema.Array(Schema.Unknown),
523 nextSkip: Schema.optional(Schema.NullOr(Schema.Number)),
524 });
525
526 const RawItemContentSchema = Schema.Struct({
527 content: Schema.optional(Schema.NullOr(Schema.String)),
528 contentMetadata: Schema.optional(
529 Schema.NullOr(Schema.Struct({ isBinary: Schema.optional(Schema.NullOr(Schema.Boolean)) })),
530 ),
531 });
532
533 export interface AzureDevOpsIteration {
534 readonly id: number;
535 readonly headCommit: string;
536 readonly mergeBaseCommit: string;
537 }
538
539 export interface AzureDevOpsChangeEntry {
540 readonly path: string;
541 readonly oldPath: string;
542 readonly changeKind: "new" | "deleted" | "change" | "rename-pure" | "rename-changed";
543 readonly objectId: string | null;
544 readonly originalObjectId: string | null;
545 }
546
547 export interface AzureDevOpsChangePage {
548 readonly changes: ReadonlyArray<AzureDevOpsChangeEntry>;
549 readonly nextSkip: number | null;
550 }
551
552 export interface AzureDevOpsItemContent {
553 readonly contents: string;
554 readonly isBinary: boolean;
555 }
556
557 const decodeIterationPage = decodeJsonResult(RawIterationPageSchema);
558 const decodeIterationEntry = Schema.decodeUnknownExit(RawIterationSchema);
559 const decodeChangePage = decodeJsonResult(RawChangePageSchema);
560 const decodeChangeEntry = Schema.decodeUnknownExit(RawChangeEntrySchema);
561 const decodeItemContent = decodeJsonResult(RawItemContentSchema);
562
563 /** Preserve whitespace to match patch paths and viewed marks. */
564 function toRepositoryPath(value: string | null | undefined): string | null {
565 if (value === undefined || value === null) return null;
566 const path = value.replace(/^\/+/, "");
567 return path.length === 0 ? null : path;
568 }
569
570 function toChangeKind(
571 raw: string | null | undefined,
572 renamed: boolean,
573 ): AzureDevOpsChangeEntry["changeKind"] {
574 const parts = new Set(
575 (raw ?? "")
576 .toLowerCase()
577 .split(",")
578 .map((part) => part.trim())
579 .filter((part) => part.length > 0),
580 );
581 if (parts.has("delete")) return "deleted";
582 if (renamed || parts.has("rename")) return parts.has("edit") ? "rename-changed" : "rename-pure";
583 if (parts.has("add")) return "new";
584 return "change";
585 }
586
587 export function decodeIterationsJson(
588 raw: string,
589 ): Result.Result<ReadonlyArray<AzureDevOpsIteration>, DecodeFailure> {
590 const decoded = decodeIterationPage(raw);
591 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
592 const iterations: AzureDevOpsIteration[] = [];
593 for (const entry of decoded.success.value) {
594 const decodedIteration = decodeIterationEntry(entry);
595 if (Exit.isFailure(decodedIteration)) continue;
596 const iteration = decodedIteration.value;
597 const headCommit = trimmed(iteration.sourceRefCommit?.commitId);
598 const mergeBaseCommit = trimmed(iteration.commonRefCommit?.commitId);
599 if (headCommit === null || mergeBaseCommit === null) continue;
600 iterations.push({ id: iteration.id, headCommit, mergeBaseCommit });
601 }
602 return Result.succeed(iterations.toSorted((left, right) => left.id - right.id));
603 }
604
605 export function decodeIterationChangesJson(
606 raw: string,
607 ): Result.Result<AzureDevOpsChangePage, DecodeFailure> {
608 const decoded = decodeChangePage(raw);
609 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
610 const changes: AzureDevOpsChangeEntry[] = [];
611 for (const entry of decoded.success.changeEntries) {
612 const decodedChange = decodeChangeEntry(entry);
613 if (Exit.isFailure(decodedChange)) continue;
614 const change = decodedChange.value;
615 // Azure uses either field for renames, depending on route/version.
616 const sourcePath =
617 toRepositoryPath(change.sourceServerItem) ?? toRepositoryPath(change.originalPath);
618 const deleted = toChangeKind(change.changeType, false) === "deleted";
619 // A deleted file has no `item.path`; only the source fields name it.
620 const path = toRepositoryPath(change.item?.path) ?? (deleted ? sourcePath : null);
621 if (path === null) continue;
622 if (change.item?.isFolder === true) continue;
623 if ((change.item?.gitObjectType ?? "blob").toLowerCase() !== "blob") continue;
624 const oldPath = sourcePath ?? path;
625 changes.push({
626 path,
627 oldPath,
628 changeKind: toChangeKind(change.changeType, oldPath !== path),
629 // Viewed marks read a deleted file at the empty revision, not a blob id.
630 objectId: deleted ? null : trimmed(change.item?.objectId),
631 originalObjectId: trimmed(change.item?.originalObjectId),
632 });
633 }
634 const nextSkip = decoded.success.nextSkip ?? null;
635 return Result.succeed({
636 changes,
637 nextSkip: nextSkip !== null && Number.isSafeInteger(nextSkip) && nextSkip > 0 ? nextSkip : null,
638 });
639 }
640
641 /** Azure returns an empty body for absent files. Binary status comes from its metadata. */
642 export function decodeItemContentJson(
643 raw: string,
644 ): Result.Result<AzureDevOpsItemContent, DecodeFailure> {
645 const decoded = decodeItemContent(raw);
646 return Result.isSuccess(decoded)
647 ? Result.succeed({
648 contents: decoded.success.content ?? "",
649 isBinary: decoded.success.contentMetadata?.isBinary === true,
650 })
651 : Result.fail(decoded.failure);
652 }