Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- Builds the zip Azure returns and stands in for az writing it.
2import * as NodeFS from "node:fs";
3import * as NodeZlib from "node:zlib";
4
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { afterEach, assert, expect, it, vi } from "@effect/vitest";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import { ChildProcessSpawner } from "effect/process";
10
11import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
12import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
13import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
14
15const mockedExecute = vi.fn<AzureDevOpsCli.AzureDevOpsCli["Service"]["execute"]>();
16
17const layer = it.layer(
18 AzureDevOpsPullRequestCli.layer.pipe(
19 Layer.provide(
20 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
21 execute: mockedExecute,
22 }),
23 ),
24 Layer.provide(NodeServices.layer),
25 ),
26);
27
28function output(stdout: string) {
29 return {
30 exitCode: ChildProcessSpawner.ExitCode(0),
31 stdout,
32 stderr: "",
33 stdoutTruncated: false,
34 stderrTruncated: false,
35 };
36}
37
38const VCS_DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
39
40function outputWithin(maxOutputBytes: number | undefined, response: string) {
41 const ceiling = maxOutputBytes ?? VCS_DEFAULT_MAX_OUTPUT_BYTES;
42 return ceiling >= Buffer.byteLength(response)
43 ? output(response)
44 : { ...output(response.slice(0, ceiling)), stdoutTruncated: true };
45}
46
47const json = (value: Record<string, unknown>) => JSON.stringify(value);
48
49const pullRequestRow = {
50 pullRequestId: 42,
51 title: "Add the page",
52 status: "active",
53 sourceRefName: "refs/heads/feat/page",
54 targetRefName: "refs/heads/main",
55 creationDate: "2026-07-01T00:00:00Z",
56 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
57 repository: { name: "web", project: { name: "platform" } },
58};
59
60const oneIteration = {
61 value: [
62 {
63 id: 1,
64 sourceRefCommit: { commitId: "a".repeat(40) },
65 commonRefCommit: { commitId: "b".repeat(40) },
66 },
67 ],
68};
69
70function pullRequestRows(
71 count: number,
72 firstNumber: number,
73): ReadonlyArray<Record<string, unknown>> {
74 return Array.from({ length: count }, (_, index) => ({
75 pullRequestId: firstNumber + index,
76 title: `Pull request ${firstNumber + index}`,
77 status: "active",
78 sourceRefName: "refs/heads/feat/page",
79 targetRefName: "refs/heads/main",
80 creationDate: "2026-07-01T00:00:00Z",
81 repository: { name: "web", project: { name: "platform" } },
82 url: `https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/${firstNumber + index}`,
83 }));
84}
85
86function pullRequests(count: number, firstNumber: number): string {
87 return JSON.stringify(pullRequestRows(count, firstNumber));
88}
89
90/** Entries as Azure streams them: data descriptors, with sizes only in the central directory. */
91function streamedZip(
92 entries: ReadonlyArray<{
93 readonly name: string;
94 readonly data: Uint8Array;
95 readonly stored?: true;
96 }>,
97): Buffer {
98 const parts: Buffer[] = [];
99 const directory: Buffer[] = [];
100 let offset = 0;
101 for (const entry of entries) {
102 const name = Buffer.from(entry.name);
103 const method = entry.stored ? 0 : 8;
104 const body = entry.stored ? Buffer.from(entry.data) : NodeZlib.deflateRawSync(entry.data);
105 const local = Buffer.alloc(30);
106 local.writeUInt32LE(0x04034b50, 0);
107 local.writeUInt16LE(0x0008, 6);
108 local.writeUInt16LE(method, 8);
109 local.writeUInt16LE(name.length, 26);
110 const descriptor = Buffer.alloc(16);
111 descriptor.writeUInt32LE(0x08074b50, 0);
112 descriptor.writeUInt32LE(body.length, 8);
113 descriptor.writeUInt32LE(entry.data.length, 12);
114 const central = Buffer.alloc(46);
115 central.writeUInt32LE(0x02014b50, 0);
116 central.writeUInt16LE(0x0008, 8);
117 central.writeUInt16LE(method, 10);
118 central.writeUInt32LE(body.length, 20);
119 central.writeUInt32LE(entry.data.length, 24);
120 central.writeUInt16LE(name.length, 28);
121 central.writeUInt32LE(offset, 42);
122 parts.push(local, name, body, descriptor);
123 directory.push(central, name);
124 offset += local.length + name.length + body.length + descriptor.length;
125 }
126 const centralDirectory = Buffer.concat(directory);
127 const end = Buffer.alloc(22);
128 end.writeUInt32LE(0x06054b50, 0);
129 end.writeUInt16LE(entries.length, 8);
130 end.writeUInt16LE(entries.length, 10);
131 end.writeUInt32LE(centralDirectory.length, 12);
132 end.writeUInt32LE(offset, 16);
133 return Buffer.concat([...parts, centralDirectory, end]);
134}
135
136function argsOfCall(index: number): ReadonlyArray<string> {
137 const call = mockedExecute.mock.calls[index];
138 assert.isDefined(call);
139 return call[0].args;
140}
141
142function changeEntries(count: number): ReadonlyArray<Record<string, unknown>> {
143 const commit = "c".repeat(40);
144 return Array.from({ length: count }, (_, index) => {
145 const path = `/apps/server/src/generated/module-${index}/persisted-projection-${index}.ts`;
146 return {
147 changeType: "edit",
148 item: {
149 path,
150 objectId: "a".repeat(40),
151 originalObjectId: "b".repeat(40),
152 commitId: commit,
153 gitObjectType: "blob",
154 url: `https://dev.azure.com/acme/platform/_apis/git/repositories/6f9c9b7f-0000-0000-0000-000000000000/items${path}?versionType=Commit&version=${commit}`,
155 },
156 };
157 });
158}
159
160afterEach(() => {
161 mockedExecute.mockReset();
162});
163
164layer("AzureDevOpsPullRequestCli.layer", (it) => {
165 it.effect("reports the latest pushed source commit even while the trial merge is stale", () =>
166 Effect.gen(function* () {
167 const previousHead = "a".repeat(40);
168 const latestHead = "c".repeat(40);
169 mockedExecute
170 .mockReturnValueOnce(
171 Effect.succeed(
172 output(json({ ...pullRequestRow, lastMergeSourceCommit: { commitId: previousHead } })),
173 ),
174 )
175 .mockReturnValueOnce(
176 Effect.succeed(
177 output(
178 json({
179 value: [
180 {
181 id: 2,
182 sourceRefCommit: { commitId: latestHead },
183 commonRefCommit: { commitId: "b".repeat(40) },
184 },
185 ...oneIteration.value,
186 ],
187 }),
188 ),
189 ),
190 )
191 .mockReturnValueOnce(Effect.succeed(output(json({ changeEntries: [] }))))
192 .mockReturnValueOnce(Effect.succeed(output("[]")));
193 const provider = yield* AzureDevOpsPullRequestProvider.make;
194 const detail = yield* provider.getChangeRequest({
195 cwd: "/w",
196 repository: "platform/web",
197 host: "dev.azure.com",
198 number: 42,
199 });
200
201 expect(detail.headSha).toBe(latestHead);
202 expect(argsOfCall(2)).toContain("iterationId=2");
203 expect(mockedExecute).toHaveBeenCalledTimes(4);
204 }),
205 );
206
207 it.effect("reads an Azure pull request page larger than the VCS default output limit", () =>
208 Effect.gen(function* () {
209 const rows = pullRequestRows(100, 1).map((row) => ({
210 ...row,
211 description: "x".repeat(10_000),
212 }));
213 const response = JSON.stringify(rows);
214 expect(Buffer.byteLength(response)).toBeGreaterThan(1_000_000);
215
216 mockedExecute.mockImplementationOnce((input) =>
217 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
218 );
219 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
220
221 const batch = yield* cli.listPullRequests({
222 cwd: "/w",
223 repository: "web",
224 state: "merged",
225 involvement: "all",
226 viewer: "bilal@acme.dev",
227 limit: 99,
228 });
229
230 assert.strictEqual(batch.items.length, 99);
231 assert.isTrue(batch.truncated);
232 }),
233 );
234
235 it.effect("steps over what it has already handed over, which is all Azure can be told", () =>
236 Effect.gen(function* () {
237 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(3, 1))));
238 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
239
240 yield* cli.listPullRequests({
241 cwd: "/w",
242 repository: "web",
243 state: "open",
244 involvement: "all",
245 viewer: "bilal@acme.dev",
246 limit: 10,
247 cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 20 },
248 });
249
250 const args = argsOfCall(0);
251 expect(args).toContain("--skip");
252 assert.strictEqual(args[args.indexOf("--skip") + 1], "20");
253 expect(args).not.toContain("2026-07-02T00:00:00Z");
254 }),
255 );
256
257 it.effect("asks Azure for the author's pull requests by creator", () =>
258 Effect.gen(function* () {
259 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(1, 1))));
260 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
261
262 yield* cli.listPullRequests({
263 cwd: "/w",
264 repository: "web",
265 state: "open",
266 involvement: "reviewing",
267 viewer: "bilal@acme.dev",
268 limit: 10,
269 author: "ana@acme.dev",
270 });
271
272 const args = argsOfCall(0);
273 assert.strictEqual(args[args.indexOf("--creator") + 1], "ana@acme.dev");
274 assert.strictEqual(args[args.indexOf("--reviewer") + 1], "bilal@acme.dev");
275 }),
276 );
277
278 it.effect("advances by malformed raw rows and keeps reading until the page is full", () =>
279 Effect.gen(function* () {
280 mockedExecute
281 .mockReturnValueOnce(
282 Effect.succeed(
283 output(
284 JSON.stringify([
285 { pullRequestId: "malformed" },
286 pullRequestRows(1, 1)[0],
287 { pullRequestId: "also malformed" },
288 ]),
289 ),
290 ),
291 )
292 .mockReturnValueOnce(Effect.succeed(output(pullRequests(2, 2))));
293 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
294
295 const batch = yield* cli.listPullRequests({
296 cwd: "/w",
297 repository: "web",
298 state: "open",
299 involvement: "all",
300 viewer: "bilal@acme.dev",
301 limit: 2,
302 });
303
304 expect(batch.items.map((item) => item.number)).toEqual([1, 2]);
305 assert.isTrue(batch.truncated);
306 assert.strictEqual(batch.cursorAdvance, 4);
307 const secondArgs = argsOfCall(1);
308 assert.strictEqual(secondArgs[secondArgs.indexOf("--skip") + 1], "3");
309 assert.strictEqual(secondArgs[secondArgs.indexOf("--top") + 1], "2");
310 }),
311 );
312
313 it.effect("reads the signed-in account, which az reports as a bare value", () =>
314 Effect.gen(function* () {
315 mockedExecute.mockReturnValueOnce(
316 Effect.succeed(output(JSON.stringify({ name: "bilal@acme.dev", type: "user" }))),
317 );
318 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
319
320 const viewer = yield* cli.getViewer({ cwd: "/w" });
321
322 assert.strictEqual(viewer, "bilal@acme.dev");
323 expect(argsOfCall(0)).toEqual([
324 "account",
325 "show",
326 "--query",
327 "user",
328 "--only-show-errors",
329 "--output",
330 "json",
331 ]);
332 }),
333 );
334
335 it.effect("names a token sign-in by the viewer's own pull request", () =>
336 Effect.gen(function* () {
337 const notLoggedIn = new AzureDevOpsCli.AzureDevOpsCliAuthenticationError({
338 operation: "execute",
339 command: "az",
340 cwd: "/w",
341 argumentCount: 7,
342 cause: new Error("Please run 'az login' to setup account."),
343 });
344 mockedExecute
345 .mockReturnValueOnce(Effect.fail(notLoggedIn))
346 .mockReturnValueOnce(
347 Effect.succeed(
348 output(
349 JSON.stringify([{ ...pullRequestRow, createdBy: { uniqueName: "bilal@acme.dev" } }]),
350 ),
351 ),
352 )
353 .mockReturnValueOnce(Effect.succeed(output("")))
354 .mockReturnValueOnce(Effect.succeed(output("[]")));
355 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
356
357 assert.strictEqual(yield* cli.getViewer({ cwd: "/w" }), "bilal@acme.dev");
358 expect(argsOfCall(1)).toEqual(expect.arrayContaining(["--creator", "me", "--top", "1"]));
359 const error = yield* Effect.flip(cli.getViewer({ cwd: "/w" }));
360 assert.strictEqual(error._tag, "AzureDevOpsViewerUnavailableError");
361 }),
362 );
363
364 it.effect("fails when no sign-in can read pull requests", () =>
365 Effect.gen(function* () {
366 const signedOut = new AzureDevOpsCli.AzureDevOpsCliAuthenticationError({
367 operation: "execute",
368 command: "az",
369 cwd: "/w",
370 argumentCount: 7,
371 cause: new Error("signed out"),
372 });
373 mockedExecute.mockReturnValue(Effect.fail(signedOut));
374 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
375
376 const error = yield* Effect.flip(cli.getViewer({ cwd: "/w" }));
377
378 assert.strictEqual(error._tag, "AzureDevOpsCliAuthenticationError");
379 }),
380 );
381
382 const policyRow = (name: string, status: string) => ({
383 status,
384 configuration: {
385 url: "https://dev.azure.com/acme/platform/_apis/policy/configurations/54",
386 isBlocking: true,
387 type: { id: "0609b952-1397-4640-95ec-e00a01b2c241" },
388 settings: { displayName: name },
389 },
390 });
391
392 it.effect("follows every page of policies and puts failures first", () =>
393 Effect.gen(function* () {
394 const fullPage = Array.from({ length: 100 }, () => policyRow("Lint", "approved"));
395 mockedExecute
396 .mockReturnValueOnce(Effect.succeed(output(JSON.stringify(fullPage))))
397 .mockReturnValueOnce(
398 Effect.succeed(output(JSON.stringify([policyRow("Tests", "rejected")]))),
399 );
400 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
401 const checks = yield* cli.listPolicyChecks({ cwd: "/w", number: 42, isDraft: false });
402 assert.deepStrictEqual(argsOfCall(1).slice(0, 12), [
403 "repos",
404 "pr",
405 "policy",
406 "list",
407 "--detect",
408 "true",
409 "--id",
410 "42",
411 "--top",
412 "100",
413 "--skip",
414 "100",
415 ]);
416 assert.strictEqual(checks.length, 101);
417 assert.strictEqual(checks[0]?.name, "Tests");
418 }),
419 );
420
421 it.effect.each([
422 { name: "cut off", result: { ...output("[]"), stdoutTruncated: true } },
423 { name: "unreadable", result: output(JSON.stringify([{ status: 7 }])) },
424 ])("fails rather than report a $name policy page as complete", ({ result }) =>
425 Effect.gen(function* () {
426 mockedExecute.mockReturnValueOnce(Effect.succeed(result));
427 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
428 const error = yield* Effect.flip(
429 cli.listPolicyChecks({ cwd: "/w", number: 42, isDraft: false }),
430 );
431 assert.strictEqual(error._tag, "AzureDevOpsPullRequestReadError");
432 }),
433 );
434
435 it.effect("sends a description that starts with a dash as one value, not as a flag", () =>
436 Effect.gen(function* () {
437 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
438 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
439
440 yield* cli.updatePullRequest({
441 cwd: "/w",
442 number: 42,
443 body: "- rewrote the page\n- kept the rest",
444 });
445
446 expect(argsOfCall(0)).toContain("--description=- rewrote the page\n- kept the rest");
447 }),
448 );
449
450 it.effect(
451 "sends a title or description that looks like `@path` as text, not as a file for az to read",
452 () =>
453 Effect.gen(function* () {
454 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
455 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
456
457 yield* cli.updatePullRequest({
458 cwd: "/w",
459 number: 42,
460 title: "@notes.txt",
461 body: "@notes.txt",
462 });
463
464 // az replaces an argument that starts with `@`, or whose text after the first `=` does, with that file's contents.
465 const fileReads = argsOfCall(0).flatMap((arg) => {
466 const value = arg.startsWith("@") ? arg : arg.slice(arg.indexOf("=") + 1);
467 return (arg.startsWith("@") || arg.includes("=")) && value.startsWith("@")
468 ? [value.slice(1)]
469 : [];
470 });
471 expect(fileReads).not.toContain("notes.txt");
472 // Each `@` value goes over stdin, which reaches az wherever it runs; one per call.
473 expect(mockedExecute.mock.calls.map(([call]) => call.stdin)).toEqual([
474 "@notes.txt",
475 "@notes.txt",
476 ]);
477 }),
478 );
479
480 it.effect("names the head's blob as what a cleared file was cleared at", () =>
481 Effect.gen(function* () {
482 mockedExecute
483 .mockReturnValueOnce(
484 Effect.succeed(
485 output(
486 JSON.stringify({
487 pullRequestId: 42,
488 title: "Add the page",
489 status: "active",
490 sourceRefName: "refs/heads/feat/page",
491 targetRefName: "refs/heads/main",
492 creationDate: "2026-07-01T00:00:00Z",
493 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
494 repository: { name: "web", project: { name: "platform" } },
495 }),
496 ),
497 ),
498 )
499 .mockReturnValueOnce(
500 Effect.succeed(
501 output(
502 JSON.stringify({
503 value: [
504 {
505 id: 1,
506 sourceRefCommit: { commitId: "a".repeat(40) },
507 commonRefCommit: { commitId: "b".repeat(40) },
508 },
509 {
510 id: 2,
511 sourceRefCommit: { commitId: "c".repeat(40) },
512 commonRefCommit: { commitId: "b".repeat(40) },
513 },
514 ],
515 }),
516 ),
517 ),
518 )
519 .mockReturnValueOnce(
520 Effect.succeed(
521 output(
522 JSON.stringify({
523 changeEntries: [
524 { changeType: "edit", item: { path: "/README.md", objectId: "8f80" } },
525 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
526 ],
527 }),
528 ),
529 ),
530 );
531 const provider = yield* AzureDevOpsPullRequestProvider.make;
532
533 assert.strictEqual(provider.capabilities.viewedFiles, "environment");
534 assert.isDefined(provider.getFileRevisions);
535 const answer = yield* provider.getFileRevisions({
536 cwd: "/w",
537 repository: "web",
538 host: "dev.azure.com",
539 number: 42,
540 paths: ["README.md"],
541 });
542
543 expect(argsOfCall(2)).toContain("iterationId=2");
544 expect([...answer.revisions]).toEqual([["README.md", "8f80"]]);
545 }),
546 );
547
548 it.effect(
549 "answers for a marked file the pull request no longer changes as the empty version",
550 () =>
551 Effect.gen(function* () {
552 mockedExecute
553 .mockReturnValueOnce(
554 Effect.succeed(
555 output(
556 json({
557 pullRequestId: 42,
558 title: "Add the page",
559 status: "active",
560 sourceRefName: "refs/heads/feat/page",
561 targetRefName: "refs/heads/main",
562 creationDate: "2026-07-01T00:00:00Z",
563 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
564 repository: { name: "web", project: { name: "platform" } },
565 }),
566 ),
567 ),
568 )
569 .mockReturnValueOnce(
570 Effect.succeed(
571 output(
572 json({
573 value: [
574 {
575 id: 1,
576 sourceRefCommit: { commitId: "a".repeat(40) },
577 commonRefCommit: { commitId: "b".repeat(40) },
578 },
579 ],
580 }),
581 ),
582 ),
583 )
584 .mockReturnValueOnce(Effect.succeed(output('{"changeEntries":[]}')));
585 const provider = yield* AzureDevOpsPullRequestProvider.make;
586 assert.isDefined(provider.getFileRevisions);
587
588 const answer = yield* provider.getFileRevisions({
589 cwd: "/w",
590 repository: "web",
591 host: "dev.azure.com",
592 number: 42,
593 paths: ["GONE.md"],
594 });
595
596 expect([...answer.revisions]).toEqual([["GONE.md", ""]]);
597 }),
598 );
599
600 it.effect("says nothing about the files past the end of a change it gave up following", () =>
601 Effect.gen(function* () {
602 const entries = (from: number, count: number) =>
603 Array.from({ length: count }, (_, index) => ({
604 changeType: "edit",
605 item: { path: `/src/f${from + index}.ts`, objectId: `blob-${from + index}` },
606 }));
607 mockedExecute
608 .mockReturnValueOnce(
609 Effect.succeed(
610 output(
611 json({
612 pullRequestId: 42,
613 title: "Add the page",
614 status: "active",
615 sourceRefName: "refs/heads/feat/page",
616 targetRefName: "refs/heads/main",
617 creationDate: "2026-07-01T00:00:00Z",
618 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
619 repository: { name: "web", project: { name: "platform" } },
620 }),
621 ),
622 ),
623 )
624 .mockReturnValueOnce(
625 Effect.succeed(
626 output(
627 json({
628 value: [
629 {
630 id: 1,
631 sourceRefCommit: { commitId: "a".repeat(40) },
632 commonRefCommit: { commitId: "b".repeat(40) },
633 },
634 ],
635 }),
636 ),
637 ),
638 )
639 .mockReturnValueOnce(
640 Effect.succeed(output(json({ changeEntries: entries(0, 5_000), nextSkip: 5_000 }))),
641 )
642 .mockReturnValueOnce(
643 Effect.succeed(output(json({ changeEntries: entries(5_000, 5_000), nextSkip: 10_000 }))),
644 );
645 const provider = yield* AzureDevOpsPullRequestProvider.make;
646 assert.isDefined(provider.getFileRevisions);
647
648 const answer = yield* provider.getFileRevisions({
649 cwd: "/w",
650 repository: "web",
651 host: "dev.azure.com",
652 number: 42,
653 paths: ["src/f1.ts", "src/f5001.ts", "src/past-the-cut.ts"],
654 });
655
656 expect(argsOfCall(3)).toContain("$skip=5000");
657 expect([...answer.revisions]).toEqual([
658 ["src/f1.ts", "blob-1"],
659 ["src/f5001.ts", "blob-5001"],
660 ]);
661 }),
662 );
663
664 it.effect("stops following pages by what Azure counts, not by what survives decoding", () =>
665 Effect.gen(function* () {
666 mockedExecute
667 .mockReturnValueOnce(
668 Effect.succeed(
669 output(
670 json({
671 pullRequestId: 42,
672 title: "Add the page",
673 status: "active",
674 sourceRefName: "refs/heads/feat/page",
675 targetRefName: "refs/heads/main",
676 creationDate: "2026-07-01T00:00:00Z",
677 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
678 repository: { name: "web", project: { name: "platform" } },
679 }),
680 ),
681 ),
682 )
683 .mockReturnValueOnce(
684 Effect.succeed(
685 output(
686 json({
687 value: [
688 {
689 id: 1,
690 sourceRefCommit: { commitId: "a".repeat(40) },
691 commonRefCommit: { commitId: "b".repeat(40) },
692 },
693 ],
694 }),
695 ),
696 ),
697 )
698 .mockImplementation((command) => {
699 const skip = command.args.find((arg) => arg.startsWith("$skip="));
700 const from = Number(skip?.slice("$skip=".length) ?? 0);
701 return Effect.succeed(
702 output(
703 json({
704 changeEntries: [{ changeType: "add", item: { path: "/src", isFolder: true } }],
705 nextSkip: from + 2_000,
706 }),
707 ),
708 );
709 });
710 const provider = yield* AzureDevOpsPullRequestProvider.make;
711 assert.isDefined(provider.getFileRevisions);
712
713 const answer = yield* provider.getFileRevisions({
714 cwd: "/w",
715 repository: "web",
716 host: "dev.azure.com",
717 number: 42,
718 paths: ["src/page.ts"],
719 });
720
721 assert.strictEqual(mockedExecute.mock.calls.length, 7);
722 assert.strictEqual(answer.revisions.size, 0);
723 }),
724 );
725
726 it.effect("leaves one file the host would not hand over listed without its hunks", () =>
727 Effect.gen(function* () {
728 mockedExecute
729 .mockReturnValueOnce(Effect.succeed(output(json(pullRequestRow))))
730 .mockReturnValueOnce(Effect.succeed(output(json(oneIteration))))
731 .mockReturnValueOnce(
732 Effect.succeed(
733 output(
734 json({
735 changeEntries: [
736 { changeType: "add", item: { path: "/huge.bin", objectId: "8f80" } },
737 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
738 ],
739 }),
740 ),
741 ),
742 )
743 .mockReturnValueOnce(
744 Effect.fail(
745 new AzureDevOpsCli.AzureDevOpsCommandFailedError({
746 operation: "execute",
747 command: "az",
748 cwd: "/w",
749 argumentCount: 1,
750 cause: "the blob is past what the route will carry",
751 }),
752 ),
753 )
754 .mockReturnValueOnce(Effect.succeed(output(json({ content: "hello\n" }))));
755 const provider = yield* AzureDevOpsPullRequestProvider.make;
756
757 const slice = yield* provider.getDiff({
758 cwd: "/w",
759 repository: "web",
760 host: "dev.azure.com",
761 number: 42,
762 });
763
764 assert.isTrue(slice.truncated);
765 expect(slice.patch).toContain("diff --git a/huge.bin b/huge.bin");
766 expect(slice.patch).toContain("+hello");
767 }),
768 );
769
770 it.effect("fails the whole read when it is the connection that would not answer", () =>
771 Effect.gen(function* () {
772 mockedExecute
773 .mockReturnValueOnce(Effect.succeed(output(json(pullRequestRow))))
774 .mockReturnValueOnce(Effect.succeed(output(json(oneIteration))))
775 .mockReturnValueOnce(
776 Effect.succeed(
777 output(
778 json({
779 changeEntries: [
780 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
781 ],
782 }),
783 ),
784 ),
785 )
786 .mockReturnValueOnce(
787 Effect.fail(
788 new AzureDevOpsCli.AzureDevOpsCliRateLimitError({
789 operation: "execute",
790 command: "az",
791 cwd: "/w",
792 argumentCount: 1,
793 cause: "429",
794 }),
795 ),
796 );
797 const provider = yield* AzureDevOpsPullRequestProvider.make;
798
799 const error = yield* Effect.flip(
800 provider.getDiff({ cwd: "/w", repository: "web", host: "dev.azure.com", number: 42 }),
801 );
802
803 assert.strictEqual(error.reason, "rate-limited");
804 }),
805 );
806
807 it.effect("takes Azure's own word on a file it will not spell out", () =>
808 Effect.gen(function* () {
809 mockedExecute
810 .mockReturnValueOnce(
811 Effect.succeed(
812 output(
813 json({
814 pullRequestId: 42,
815 title: "Add the page",
816 status: "active",
817 sourceRefName: "refs/heads/feat/page",
818 targetRefName: "refs/heads/main",
819 creationDate: "2026-07-01T00:00:00Z",
820 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
821 repository: { name: "web", project: { name: "platform" } },
822 }),
823 ),
824 ),
825 )
826 .mockReturnValueOnce(
827 Effect.succeed(
828 output(
829 json({
830 value: [
831 {
832 id: 1,
833 sourceRefCommit: { commitId: "a".repeat(40) },
834 commonRefCommit: { commitId: "b".repeat(40) },
835 },
836 ],
837 }),
838 ),
839 ),
840 )
841 .mockReturnValueOnce(
842 Effect.succeed(
843 output(
844 json({
845 changeEntries: [
846 { changeType: "add", item: { path: "/logo.png", objectId: "8f80" } },
847 ],
848 }),
849 ),
850 ),
851 )
852 .mockReturnValueOnce(
853 Effect.succeed(
854 output(json({ content: "iVBORw0KGgo=", contentMetadata: { isBinary: true } })),
855 ),
856 );
857 const provider = yield* AzureDevOpsPullRequestProvider.make;
858
859 const slice = yield* provider.getDiff({
860 cwd: "/w",
861 repository: "web",
862 host: "dev.azure.com",
863 number: 42,
864 });
865
866 expect(argsOfCall(3)).toContain("includeContentMetadata=true");
867 expect(slice.patch).toContain("Binary files a/logo.png and b/logo.png differ");
868 assert.isTrue(slice.truncated);
869 }),
870 );
871
872 it.effect("stops following pages when one of them does not move the cursor on", () =>
873 Effect.gen(function* () {
874 mockedExecute
875 .mockReturnValueOnce(
876 Effect.succeed(
877 output(
878 json({
879 pullRequestId: 42,
880 title: "Add the page",
881 status: "active",
882 sourceRefName: "refs/heads/feat/page",
883 targetRefName: "refs/heads/main",
884 creationDate: "2026-07-01T00:00:00Z",
885 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
886 repository: { name: "web", project: { name: "platform" } },
887 }),
888 ),
889 ),
890 )
891 .mockReturnValueOnce(
892 Effect.succeed(
893 output(
894 json({
895 value: [
896 {
897 id: 1,
898 sourceRefCommit: { commitId: "a".repeat(40) },
899 commonRefCommit: { commitId: "b".repeat(40) },
900 },
901 ],
902 }),
903 ),
904 ),
905 )
906 .mockReturnValueOnce(
907 Effect.succeed(
908 output(
909 json({
910 changeEntries: [{ changeType: "edit", item: { path: "/a.ts", objectId: "8f80" } }],
911 nextSkip: 2_000,
912 }),
913 ),
914 ),
915 )
916 .mockReturnValueOnce(
917 Effect.succeed(
918 output(
919 json({
920 changeEntries: [{ changeType: "edit", item: { path: "/b.ts", objectId: "0ca4" } }],
921 nextSkip: 2_000,
922 }),
923 ),
924 ),
925 );
926 const provider = yield* AzureDevOpsPullRequestProvider.make;
927 assert.isDefined(provider.getFileRevisions);
928
929 const answer = yield* provider.getFileRevisions({
930 cwd: "/w",
931 repository: "web",
932 host: "dev.azure.com",
933 number: 42,
934 paths: ["a.ts", "b.ts", "unlisted.ts"],
935 });
936
937 assert.strictEqual(mockedExecute.mock.calls.length, 4);
938 expect([...answer.revisions]).toEqual([
939 ["a.ts", "8f80"],
940 ["b.ts", "0ca4"],
941 ]);
942 }),
943 );
944
945 it.effect("reads a full page of change entries, which is past the default output limit", () =>
946 Effect.gen(function* () {
947 const response = json({ changeEntries: changeEntries(2_000) });
948 expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
949 mockedExecute.mockImplementationOnce((input) =>
950 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
951 );
952 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
953
954 const page = yield* cli.listIterationChanges({
955 cwd: "/w",
956 location: { project: "platform", repository: "web" },
957 number: 42,
958 iterationId: 1,
959 });
960
961 assert.strictEqual(page.changes.length, 2_000);
962 assert.isFalse(page.truncated);
963 }),
964 );
965
966 it.effect("reads a file whose JSON envelope is past the default output limit", () =>
967 Effect.gen(function* () {
968 const file = "const value = 1;\n".repeat(57_000);
969 const response = json({ content: file });
970 expect(Buffer.byteLength(file)).toBeLessThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
971 expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
972 mockedExecute.mockImplementationOnce((input) =>
973 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
974 );
975 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
976
977 const item = yield* cli.readItemContent({
978 cwd: "/w",
979 location: { project: "platform", repository: "web" },
980 path: "src/generated/schema.ts",
981 commit: "a".repeat(40),
982 });
983
984 assert.strictEqual(item.contents, file);
985 assert.isFalse(item.isBinary);
986 }),
987 );
988
989 it.effect(
990 "reads a batch of files from one blobs zip, keeping only what Azure's read would say",
991 () =>
992 Effect.gen(function* () {
993 const id = (digit: string) => digit.repeat(40);
994 const utf8 = (text: string) => new TextEncoder().encode(text);
995 let sent = "";
996 mockedExecute.mockImplementationOnce((input) =>
997 Effect.sync(() => {
998 const flag = (name: string) => input.args[input.args.indexOf(name) + 1] ?? "";
999 sent = NodeFS.readFileSync(flag("--in-file"), "utf8");
1000 NodeFS.writeFileSync(
1001 flag("--out-file"),
1002 streamedZip([
1003 { name: id("a"), data: utf8("plain text\n") },
1004 { name: id("b"), data: utf8("\uFEFFcafé ✓\n") },
1005 { name: id("c"), data: Uint8Array.of(0x89, 0x50, 0x00, 0x01) },
1006 // Windows-1252 "café" and UTF-16: Azure decodes these itself.
1007 { name: id("d"), data: Uint8Array.of(0x63, 0x61, 0x66, 0xe9) },
1008 { name: id("e"), data: Uint8Array.of(0xff, 0xfe, 0x68, 0x00) },
1009 { name: id("f"), data: utf8("stored\n"), stored: true },
1010 { name: id("9"), data: utf8("never asked for\n") },
1011 ]),
1012 );
1013 return output("");
1014 }),
1015 );
1016 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1017
1018 const blobs = yield* cli.readBlobs({
1019 cwd: "/w",
1020 location: { project: "platform", repository: "web" },
1021 objectIds: [id("A"), id("b"), id("C"), id("d"), id("e"), id("f"), id("a"), "../etc"],
1022 });
1023
1024 expect(JSON.parse(sent)).toEqual([id("A"), id("b"), id("C"), id("d"), id("e"), id("f")]);
1025 expect(argsOfCall(0)).toEqual(
1026 expect.arrayContaining(["blobs", "POST", "application/zip", "project=platform"]),
1027 );
1028 expect(Object.fromEntries(blobs)).toEqual({
1029 [id("a")]: { contents: "plain text\n", isBinary: false },
1030 [id("b")]: { contents: "café ✓\n", isBinary: false },
1031 [id("c")]: { contents: "", isBinary: true },
1032 [id("f")]: { contents: "stored\n", isBinary: false },
1033 });
1034 }),
1035 );
1036
1037 it.effect("leaves blobs past the batch's total size to per-file reads", () =>
1038 Effect.gen(function* () {
1039 const ids = ["1", "2", "3", "4", "5", "6"].map((digit) => digit.repeat(40));
1040 // Compresses to a few KiB each, so only the inflated total can bound memory.
1041 const blob = new Uint8Array(3 * 1024 * 1024).fill(0x61);
1042 mockedExecute.mockImplementationOnce((input) =>
1043 Effect.sync(() => {
1044 NodeFS.writeFileSync(
1045 input.args[input.args.indexOf("--out-file") + 1] ?? "",
1046 streamedZip(ids.map((name) => ({ name, data: blob }))),
1047 );
1048 return output("");
1049 }),
1050 );
1051 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1052
1053 const blobs = yield* cli.readBlobs({
1054 cwd: "/w",
1055 location: { project: "platform", repository: "web" },
1056 objectIds: ids,
1057 });
1058
1059 expect([...blobs.keys()]).toEqual(ids.slice(0, 5));
1060 }),
1061 );
1062
1063 it.effect("escapes characters in a file path that would cut the query string", () =>
1064 Effect.gen(function* () {
1065 mockedExecute.mockReturnValueOnce(Effect.succeed(output(json({ content: "x" }))));
1066 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1067
1068 yield* cli.readItemContent({
1069 cwd: "/w",
1070 location: { project: "platform", repository: "web" },
1071 path: "docs/C#/a&b.md",
1072 commit: "a".repeat(40),
1073 });
1074
1075 expect(mockedExecute.mock.calls.at(-1)?.[0].args).toContain("path=%2Fdocs%2FC%23%2Fa%26b.md");
1076 }),
1077 );
1078
1079 it.effect("reports a pull request it cannot place as its own outcome", () =>
1080 Effect.gen(function* () {
1081 mockedExecute.mockReturnValueOnce(
1082 Effect.succeed(
1083 output(
1084 JSON.stringify({
1085 pullRequestId: 42,
1086 title: "Add the page",
1087 sourceRefName: "refs/heads/feat/page",
1088 targetRefName: "refs/heads/main",
1089 creationDate: "2026-07-01T00:00:00Z",
1090 }),
1091 ),
1092 ),
1093 );
1094 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1095
1096 const error = yield* Effect.flip(cli.getPullRequest({ cwd: "/w", number: 42 }));
1097
1098 assert.strictEqual(error._tag, "AzureDevOpsPullRequestIncompleteError");
1099 }),
1100 );
1101
1102 it.effect("refuses a reviewer az would read as a flag, before running anything", () =>
1103 Effect.gen(function* () {
1104 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1105
1106 const error = yield* Effect.flip(
1107 cli.setPullRequestReviewers({
1108 cwd: "/w",
1109 number: 42,
1110 reviewers: ["--query"],
1111 requested: true,
1112 }),
1113 );
1114
1115 assert.strictEqual(error._tag, "AzureDevOpsReviewerNameError");
1116 assert.strictEqual(mockedExecute.mock.calls.length, 0);
1117 }),
1118 );
1119});