@juicesharp/rpiv-web-tools 1.20.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,933 +0,0 @@
1
- /**
2
- * Unit tests for providers/interceptors/github.ts
3
- *
4
- * Covers all pure/sync logic and null-return paths that don't require real
5
- * execFile/gh CLI calls:
6
- * - parseGitHubUrl (all branches)
7
- * - resolveGitHubOptions (resolution matrix)
8
- * - GitHubInterceptor.intercept null-return paths (disabled, NON_CODE_SEGMENTS,
9
- * aborted, SHA, clone fails)
10
- * - generateCloneContent (root/tree/blob/binary via temp dir + _seedCache)
11
- * - fetchViaApi paths via mocked gh
12
- *
13
- * execFile is mocked so no real network or gh CLI calls occur.
14
- */
15
-
16
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
17
- import { tmpdir } from "node:os";
18
- import { join } from "node:path";
19
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
20
-
21
- // ---------------------------------------------------------------------------
22
- // Mock node:child_process — controls checkGhAvailable + all gh/git calls
23
- // ---------------------------------------------------------------------------
24
-
25
- const mockExecFile = vi.fn();
26
-
27
- vi.mock("node:child_process", () => ({
28
- execFile: (...args: unknown[]) => mockExecFile(...args),
29
- }));
30
-
31
- function makeGhUnavailable() {
32
- mockExecFile.mockImplementation((...args: unknown[]) => {
33
- const cb = args[args.length - 1] as (err: Error | null) => void;
34
- cb(new Error("gh: not found"));
35
- });
36
- }
37
-
38
- function makeGhAvailableApisFail() {
39
- mockExecFile.mockImplementation((...args: unknown[]) => {
40
- const cmdArgs = args[1] as string[];
41
- const cb = args[args.length - 1] as (err: Error | null, stdout?: string) => void;
42
- if (cmdArgs[0] === "--version") {
43
- cb(null, "gh version 2.0.0");
44
- } else {
45
- cb(new Error("not found"), "");
46
- }
47
- });
48
- }
49
-
50
- // ---------------------------------------------------------------------------
51
- // Module under test — imported after vi.mock is registered
52
- // ---------------------------------------------------------------------------
53
-
54
- const { parseGitHubUrl, resolveGitHubOptions, GitHubInterceptor, GITHUB_TOKEN_ENV_VAR, DEFAULTS } = await import(
55
- "./github.js"
56
- );
57
-
58
- // Default factory: returns a fresh enabled interceptor with default thresholds.
59
- // Tests construct their own seeded cache when they need to inject clone results.
60
- function make(
61
- opts: { enabled?: boolean; maxRepoSizeMB?: number; cloneTimeoutSeconds?: number; clonePath?: string } = {},
62
- ): InstanceType<typeof GitHubInterceptor> {
63
- return new GitHubInterceptor({ enabled: true, ...opts });
64
- }
65
-
66
- // ---------------------------------------------------------------------------
67
- // parseGitHubUrl
68
- // ---------------------------------------------------------------------------
69
-
70
- describe("parseGitHubUrl", () => {
71
- it("returns null for non-GitHub URLs", () => {
72
- expect(parseGitHubUrl("https://example.com/foo")).toBeNull();
73
- expect(parseGitHubUrl("https://gitlab.com/owner/repo")).toBeNull();
74
- });
75
-
76
- it("returns null for invalid URLs", () => {
77
- expect(parseGitHubUrl("not a url")).toBeNull();
78
- expect(parseGitHubUrl("")).toBeNull();
79
- });
80
-
81
- it("returns null when path has fewer than 2 segments", () => {
82
- expect(parseGitHubUrl("https://github.com/")).toBeNull();
83
- expect(parseGitHubUrl("https://github.com/owner")).toBeNull();
84
- });
85
-
86
- it("parses a root repo URL", () => {
87
- const info = parseGitHubUrl("https://github.com/owner/repo");
88
- expect(info).toEqual({ owner: "owner", repo: "repo", refIsFullSha: false, type: "root" });
89
- });
90
-
91
- it("strips .git suffix from repo name", () => {
92
- expect(parseGitHubUrl("https://github.com/owner/repo.git")?.repo).toBe("repo");
93
- });
94
-
95
- it("handles www.github.com hostname", () => {
96
- expect(parseGitHubUrl("https://www.github.com/owner/repo")?.type).toBe("root");
97
- });
98
-
99
- it.each([
100
- "issues",
101
- "pull",
102
- "pulls",
103
- "discussions",
104
- "releases",
105
- "wiki",
106
- "actions",
107
- "settings",
108
- "security",
109
- "commits",
110
- "tags",
111
- "branches",
112
- ])("returns null for NON_CODE_SEGMENT: %s", (segment) => {
113
- expect(parseGitHubUrl(`https://github.com/owner/repo/${segment}`)).toBeNull();
114
- });
115
-
116
- it("returns null when action is not blob or tree", () => {
117
- expect(parseGitHubUrl("https://github.com/owner/repo/compare/main...feat")).toBeNull();
118
- });
119
-
120
- it("returns null when blob/tree has no ref segment", () => {
121
- expect(parseGitHubUrl("https://github.com/owner/repo/blob")).toBeNull();
122
- });
123
-
124
- it("parses a blob URL", () => {
125
- const info = parseGitHubUrl("https://github.com/owner/repo/blob/main/src/file.ts");
126
- expect(info).toMatchObject({
127
- owner: "owner",
128
- repo: "repo",
129
- ref: "main",
130
- type: "blob",
131
- path: "src/file.ts",
132
- refIsFullSha: false,
133
- });
134
- });
135
-
136
- it("detects full-SHA ref", () => {
137
- const sha = "a".repeat(40);
138
- const info = parseGitHubUrl(`https://github.com/owner/repo/blob/${sha}/file.ts`);
139
- expect(info?.refIsFullSha).toBe(true);
140
- expect(info?.ref).toBe(sha);
141
- });
142
-
143
- it("parses a tree URL with path", () => {
144
- const info = parseGitHubUrl("https://github.com/owner/repo/tree/main/src");
145
- expect(info).toMatchObject({ type: "tree", ref: "main", path: "src" });
146
- });
147
-
148
- it("parses a tree URL with empty path (repo root tree)", () => {
149
- const info = parseGitHubUrl("https://github.com/owner/repo/tree/main");
150
- expect(info?.path).toBe("");
151
- expect(info?.type).toBe("tree");
152
- });
153
-
154
- it("decodes percent-encoded path segments", () => {
155
- const info = parseGitHubUrl("https://github.com/owner/repo/blob/main/path%20with%20spaces/file.ts");
156
- expect(info?.path).toBe("path with spaces/file.ts");
157
- });
158
- });
159
-
160
- // ---------------------------------------------------------------------------
161
- // resolveGitHubOptions — opt-in resolution matrix
162
- // ---------------------------------------------------------------------------
163
-
164
- describe("resolveGitHubOptions", () => {
165
- it("absent user config + no consumer default → disabled", () => {
166
- expect(resolveGitHubOptions(undefined, undefined)).toEqual(DEFAULTS);
167
- });
168
-
169
- it("absent user config + consumer:true → enabled with defaults", () => {
170
- expect(resolveGitHubOptions(undefined, true)).toEqual({ ...DEFAULTS, enabled: true });
171
- });
172
-
173
- it("absent user config + consumer:false → disabled", () => {
174
- expect(resolveGitHubOptions(undefined, false)).toEqual(DEFAULTS);
175
- });
176
-
177
- it("user:false beats consumer:true → disabled (explicit user override wins)", () => {
178
- expect(resolveGitHubOptions(false, true)).toEqual({ ...DEFAULTS, enabled: false });
179
- });
180
-
181
- it("user:true beats consumer:false → enabled", () => {
182
- expect(resolveGitHubOptions(true, false)).toEqual({ ...DEFAULTS, enabled: true });
183
- });
184
-
185
- it("user object form implies opt-in regardless of consumer default", () => {
186
- const r = resolveGitHubOptions({ maxRepoSizeMB: 1000 }, false);
187
- expect(r.enabled).toBe(true);
188
- expect(r.maxRepoSizeMB).toBe(1000);
189
- expect(r.cloneTimeoutSeconds).toBe(DEFAULTS.cloneTimeoutSeconds);
190
- expect(r.clonePath).toBe(DEFAULTS.clonePath);
191
- });
192
-
193
- it('user object with explicit "enabled": false honors it', () => {
194
- const r = resolveGitHubOptions({ enabled: false, maxRepoSizeMB: 1000 }, true);
195
- expect(r.enabled).toBe(false);
196
- expect(r.maxRepoSizeMB).toBe(1000);
197
- });
198
-
199
- it("user object overrides every default field", () => {
200
- const r = resolveGitHubOptions({ maxRepoSizeMB: 1, cloneTimeoutSeconds: 2, clonePath: "/x" }, undefined);
201
- expect(r).toEqual({ enabled: true, maxRepoSizeMB: 1, cloneTimeoutSeconds: 2, clonePath: "/x" });
202
- });
203
- });
204
-
205
- // ---------------------------------------------------------------------------
206
- // GITHUB_TOKEN_ENV_VAR
207
- // ---------------------------------------------------------------------------
208
-
209
- describe("GITHUB_TOKEN_ENV_VAR", () => {
210
- it("is GITHUB_TOKEN", () => {
211
- expect(GITHUB_TOKEN_ENV_VAR).toBe("GITHUB_TOKEN");
212
- });
213
- });
214
-
215
- // ---------------------------------------------------------------------------
216
- // intercept — fast null-return paths
217
- // ---------------------------------------------------------------------------
218
-
219
- describe("intercept — fast null returns", () => {
220
- beforeEach(makeGhUnavailable);
221
-
222
- it("returns null for non-GitHub URL", async () => {
223
- expect(await make().intercept("https://example.com", { raw: false })).toBeNull();
224
- });
225
-
226
- it("returns null for NON_CODE_SEGMENTS URLs", async () => {
227
- const i = make();
228
- expect(await i.intercept("https://github.com/owner/repo/issues", { raw: false })).toBeNull();
229
- expect(await i.intercept("https://github.com/owner/repo/pulls", { raw: false })).toBeNull();
230
- expect(await i.intercept("https://github.com/owner/repo/actions", { raw: false })).toBeNull();
231
- });
232
-
233
- it("returns null when signal is already aborted", async () => {
234
- const ctrl = new AbortController();
235
- ctrl.abort();
236
- expect(await make().intercept("https://github.com/owner/repo", { raw: false, signal: ctrl.signal })).toBeNull();
237
- });
238
-
239
- it("returns null when interceptor.enabled is false", async () => {
240
- const i = new GitHubInterceptor({ enabled: false });
241
- expect(await i.intercept("https://github.com/owner/repo", { raw: false })).toBeNull();
242
- });
243
-
244
- it("returns null for full-SHA ref (gh unavailable → API path → getDefaultBranch null)", async () => {
245
- const sha = "a".repeat(40);
246
- expect(await make().intercept(`https://github.com/owner/repo/blob/${sha}/file.ts`, { raw: false })).toBeNull();
247
- });
248
-
249
- it("returns null for root URL when gh unavailable and git clone fails", async () => {
250
- expect(await make().intercept("https://github.com/owner/repo", { raw: false })).toBeNull();
251
- });
252
-
253
- it("returns null for blob URL when no gh and no clone", async () => {
254
- expect(await make().intercept("https://github.com/owner/repo/blob/main/file.ts", { raw: false })).toBeNull();
255
- });
256
- });
257
-
258
- // ---------------------------------------------------------------------------
259
- // intercept — with gh available but all API calls fail
260
- // ---------------------------------------------------------------------------
261
-
262
- describe("intercept — gh available, API returns null", () => {
263
- beforeEach(makeGhAvailableApisFail);
264
-
265
- it("returns null for root URL (size=null, clone fails, API=null)", async () => {
266
- expect(await make().intercept("https://github.com/owner/repo", { raw: false })).toBeNull();
267
- });
268
-
269
- it("returns null for blob URL (clone fails, API=null)", async () => {
270
- expect(await make().intercept("https://github.com/owner/repo/blob/main/file.ts", { raw: false })).toBeNull();
271
- });
272
- });
273
-
274
- // ---------------------------------------------------------------------------
275
- // reset() — clears cache + ghAvailable
276
- // ---------------------------------------------------------------------------
277
-
278
- describe("reset()", () => {
279
- it("can be called on an empty cache without throwing", () => {
280
- const i = make();
281
- expect(() => i.reset()).not.toThrow();
282
- expect(() => i.reset()).not.toThrow();
283
- });
284
-
285
- it("resets ghAvailable so checkGhAvailable re-probes on next call", async () => {
286
- const i = make();
287
- makeGhUnavailable();
288
- await i.intercept("https://github.com/owner/repo/issues", { raw: false });
289
- i.reset();
290
- makeGhAvailableApisFail();
291
- await i.intercept("https://github.com/owner/repo/issues", { raw: false });
292
- // No assertion on return value — verifying no throw and that the re-probe path is hit.
293
- });
294
- });
295
-
296
- // ---------------------------------------------------------------------------
297
- // generateCloneContent — via _seedCache + temp directory fixtures
298
- // ---------------------------------------------------------------------------
299
-
300
- describe("generateCloneContent — via clone cache injection", () => {
301
- let tempDir: string;
302
-
303
- beforeEach(() => {
304
- makeGhUnavailable();
305
- tempDir = mkdtempSync(join(tmpdir(), "rpiv-gh-test-"));
306
- });
307
-
308
- afterEach(() => {
309
- rmSync(tempDir, { recursive: true, force: true });
310
- });
311
-
312
- it("root: returns file tree + README", async () => {
313
- writeFileSync(join(tempDir, "README.md"), "# My Repo\nHello world.");
314
- writeFileSync(join(tempDir, "index.ts"), "export const x = 1;");
315
- mkdirSync(join(tempDir, "src"));
316
- writeFileSync(join(tempDir, "src", "main.ts"), "");
317
-
318
- const i = make();
319
- i._seedCache("owner/repo", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
320
-
321
- const r = await i.intercept("https://github.com/owner/repo", { raw: false });
322
- expect(r).not.toBeNull();
323
- expect(r!.text).toContain("Repository cloned to:");
324
- expect(r!.text).toContain("## Structure");
325
- expect(r!.text).toContain("index.ts");
326
- expect(r!.text).toContain("src/");
327
- expect(r!.text).toContain("## README.md");
328
- expect(r!.text).toContain("My Repo");
329
- expect(r!.title).toBe("owner/repo");
330
- expect(r!.contentType).toBe("text/plain");
331
- });
332
-
333
- it("root: works without a README", async () => {
334
- writeFileSync(join(tempDir, "index.ts"), "");
335
- const i = make();
336
- i._seedCache("owner/repo", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
337
-
338
- const r = await i.intercept("https://github.com/owner/repo", { raw: false });
339
- expect(r).not.toBeNull();
340
- expect(r!.text).toContain("## Structure");
341
- expect(r!.text).not.toContain("## README.md");
342
- });
343
-
344
- it("root: truncates README at 8K chars", async () => {
345
- writeFileSync(join(tempDir, "README.md"), "x".repeat(9000));
346
- const i = make();
347
- i._seedCache("owner/repo", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
348
-
349
- const r = await i.intercept("https://github.com/owner/repo", { raw: false });
350
- expect(r!.text).toContain("[README truncated at 8K chars]");
351
- });
352
-
353
- it("blob: handles unreadable file (readFileSync catch path) via chmod 000", async () => {
354
- const { chmodSync } = await import("node:fs");
355
- writeFileSync(join(tempDir, "unreadable.ts"), "const x = 1;");
356
- chmodSync(join(tempDir, "unreadable.ts"), 0o000);
357
- const i = make();
358
- i._seedCache("owner/repo@main", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
359
- try {
360
- const r = await i.intercept("https://github.com/owner/repo/blob/main/unreadable.ts", { raw: false });
361
- expect(r).not.toBeNull();
362
- expect(typeof r!.text).toBe("string");
363
- } finally {
364
- try {
365
- chmodSync(join(tempDir, "unreadable.ts"), 0o644);
366
- } catch {
367
- /* ignore */
368
- }
369
- }
370
- });
371
-
372
- it("buildTree truncation at MAX_TREE_ENTRIES (>200 files)", async () => {
373
- for (let i = 0; i < 201; i++) {
374
- writeFileSync(join(tempDir, `file${i.toString().padStart(3, "0")}.ts`), "");
375
- }
376
- const interceptor = make();
377
- interceptor._seedCache("owner/repo", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
378
- const r = await interceptor.intercept("https://github.com/owner/repo", { raw: false });
379
- expect(r!.text).toContain("truncated at 200 entries");
380
- });
381
-
382
- it("root: formatFileSize shows bytes for tiny files and KB for medium files", async () => {
383
- mkdirSync(join(tempDir, "subdir"));
384
- writeFileSync(join(tempDir, "subdir", "tiny.ts"), "x");
385
- writeFileSync(join(tempDir, "subdir", "medium.ts"), "x".repeat(2048));
386
- writeFileSync(join(tempDir, "subdir", "large.ts"), "x".repeat(1_100_000));
387
- const i = make();
388
- i._seedCache("owner/repo@v", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
389
-
390
- const r = await i.intercept("https://github.com/owner/repo/tree/v/subdir", { raw: false });
391
- expect(r).not.toBeNull();
392
- expect(r!.text).toMatch(/\d+ B|\d+\.\d+ KB|\d+\.\d+ MB/);
393
- });
394
-
395
- it("root: buildTree marks outside-repo symlink as skipped", async () => {
396
- const { symlinkSync } = await import("node:fs");
397
- writeFileSync(join(tempDir, "normal.ts"), "");
398
- try {
399
- symlinkSync("/tmp", join(tempDir, "escape-link"));
400
- } catch {
401
- /* skip if symlink creation fails */
402
- }
403
- const i = make();
404
- i._seedCache("owner/repo", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
405
- const r = await i.intercept("https://github.com/owner/repo", { raw: false });
406
- expect(r).not.toBeNull();
407
- expect(r!.text).toContain("normal.ts");
408
- expect(r!.text).toContain("outside repo skipped");
409
- });
410
-
411
- it("root: skips NOISE_DIRS in tree output", async () => {
412
- mkdirSync(join(tempDir, "node_modules"));
413
- writeFileSync(join(tempDir, "node_modules", "pkg.js"), "");
414
- writeFileSync(join(tempDir, "index.ts"), "");
415
- const i = make();
416
- i._seedCache("owner/repo", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
417
-
418
- const r = await i.intercept("https://github.com/owner/repo", { raw: false });
419
- expect(r!.text).toContain("node_modules/ [skipped]");
420
- expect(r!.text).not.toContain("pkg.js");
421
- });
422
-
423
- it("blob: returns file content", async () => {
424
- writeFileSync(join(tempDir, "file.ts"), "export const answer = 42;");
425
- const i = make();
426
- i._seedCache("owner/repo@main", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
427
-
428
- const r = await i.intercept("https://github.com/owner/repo/blob/main/file.ts", { raw: false });
429
- expect(r).not.toBeNull();
430
- expect(r!.text).toContain("## file.ts");
431
- expect(r!.text).toContain("export const answer = 42;");
432
- expect(r!.title).toBe("owner/repo - file.ts");
433
- });
434
-
435
- it("blob: returns binary message for known binary extension (.png)", async () => {
436
- writeFileSync(join(tempDir, "image.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47]));
437
- const i = make();
438
- i._seedCache("owner/repo@main", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
439
-
440
- const r = await i.intercept("https://github.com/owner/repo/blob/main/image.png", { raw: false });
441
- expect(r!.text).toContain("Binary file");
442
- expect(r!.text).toContain("png");
443
- });
444
-
445
- it("blob: returns binary message for file with null bytes", async () => {
446
- writeFileSync(join(tempDir, "data.bin"), Buffer.alloc(16));
447
- const i = make();
448
- i._seedCache("owner/repo@main", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
449
-
450
- const r = await i.intercept("https://github.com/owner/repo/blob/main/data.bin", { raw: false });
451
- expect(r!.text).toContain("Binary file");
452
- });
453
-
454
- it("blob: falls back to repo root when file not found in clone", async () => {
455
- writeFileSync(join(tempDir, "README.md"), "# Repo");
456
- const i = make();
457
- i._seedCache("owner/repo@main", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
458
-
459
- const r = await i.intercept("https://github.com/owner/repo/blob/main/missing.ts", { raw: false });
460
- expect(r!.text).toContain("not found in clone");
461
- expect(r!.text).toContain("## Structure");
462
- });
463
-
464
- it("blob: shows dir listing when path points to a directory", async () => {
465
- mkdirSync(join(tempDir, "mydir"));
466
- writeFileSync(join(tempDir, "mydir", "file.ts"), "");
467
- const i = make();
468
- i._seedCache("owner/repo@main", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
469
-
470
- const r = await i.intercept("https://github.com/owner/repo/blob/main/mydir", { raw: false });
471
- expect(r!.text).toContain("file.ts");
472
- });
473
-
474
- it("blob: truncates large files at 100K chars", async () => {
475
- writeFileSync(join(tempDir, "big.ts"), "x".repeat(110_000));
476
- const i = make();
477
- i._seedCache("owner/repo@main", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
478
-
479
- const r = await i.intercept("https://github.com/owner/repo/blob/main/big.ts", { raw: false });
480
- expect(r!.text).toContain("[File truncated at 100K chars");
481
- });
482
-
483
- it("tree: returns directory listing for existing subdir", async () => {
484
- mkdirSync(join(tempDir, "src"));
485
- writeFileSync(join(tempDir, "src", "a.ts"), "");
486
- writeFileSync(join(tempDir, "src", "b.ts"), "");
487
- const i = make();
488
- i._seedCache("owner/repo@main", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
489
-
490
- const r = await i.intercept("https://github.com/owner/repo/tree/main/src", { raw: false });
491
- expect(r!.text).toContain("## src");
492
- expect(r!.text).toContain("a.ts");
493
- expect(r!.text).toContain("b.ts");
494
- });
495
-
496
- it("tree: falls back to repo root when subdir not found", async () => {
497
- writeFileSync(join(tempDir, "index.ts"), "");
498
- const i = make();
499
- i._seedCache("owner/repo@main", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
500
-
501
- const r = await i.intercept("https://github.com/owner/repo/tree/main/missing-dir", { raw: false });
502
- expect(r!.text).toContain("not found in clone");
503
- expect(r!.text).toContain("## Structure");
504
- });
505
-
506
- it("tree: handles empty path (root tree URL)", async () => {
507
- writeFileSync(join(tempDir, "index.ts"), "");
508
- const i = make();
509
- i._seedCache("owner/repo@main", { localPath: tempDir, clonePromise: Promise.resolve(tempDir) });
510
-
511
- const r = await i.intercept("https://github.com/owner/repo/tree/main", { raw: false });
512
- expect(r).not.toBeNull();
513
- expect(r!.text).toContain("index.ts");
514
- });
515
-
516
- it("falls back to fetchViaApi when clonePromise resolves null (gh unavailable → null)", async () => {
517
- const i = make();
518
- i._seedCache("owner/repo", { localPath: tempDir, clonePromise: Promise.resolve(null) });
519
- const r = await i.intercept("https://github.com/owner/repo", { raw: false });
520
- expect(r).toBeNull();
521
- });
522
- });
523
-
524
- // ---------------------------------------------------------------------------
525
- // fetchViaApi paths — via gh mock returning real API responses
526
- // ---------------------------------------------------------------------------
527
-
528
- describe("fetchViaApi paths (gh mocked to return API responses)", () => {
529
- function makeGhApiMock(responses: Record<string, string>) {
530
- mockExecFile.mockImplementation((...args: unknown[]) => {
531
- const cmdArgs = args[1] as string[];
532
- const cb = args[args.length - 1] as (err: Error | null, stdout?: string) => void;
533
- if (cmdArgs[0] === "--version") {
534
- cb(null, "gh version 2.0.0");
535
- return;
536
- }
537
- if (cmdArgs[0] !== "api") {
538
- cb(new Error("unexpected command"), "");
539
- return;
540
- }
541
- const apiPath = cmdArgs[1] as string;
542
- const jqFilter = cmdArgs[3] as string | undefined;
543
- const routeKey = `${apiPath}|${jqFilter ?? ""}`;
544
- const key = Object.keys(responses).find((k) => routeKey.includes(k));
545
- if (key) {
546
- cb(null, responses[key]);
547
- } else {
548
- cb(new Error("not found"), "");
549
- }
550
- });
551
- }
552
-
553
- it("fetches a blob file via API (getDefaultBranch + fetchFileViaApi)", async () => {
554
- const fileContentB64 = Buffer.from("export const x = 1;\n").toString("base64");
555
- makeGhApiMock({ ".default_branch": "main", ".content": fileContentB64 });
556
-
557
- const r = await make().intercept("https://github.com/owner/repo/blob/main/src/file.ts", { raw: false });
558
- expect(r).not.toBeNull();
559
- expect(r!.text).toContain("export const x = 1;");
560
- expect(r!.title).toBe("owner/repo - src/file.ts");
561
- });
562
-
563
- it("fetches repo root via API (getDefaultBranch + fetchTreeViaApi + fetchReadmeViaApi)", async () => {
564
- const readmeB64 = Buffer.from("# Hello World").toString("base64");
565
- makeGhApiMock({
566
- ".default_branch": "main",
567
- ".tree[].path": "src/index.ts\nREADME.md",
568
- "repos/owner/repo/readme": readmeB64,
569
- });
570
-
571
- const r = await make().intercept("https://github.com/owner/repo", { raw: false });
572
- expect(r).not.toBeNull();
573
- expect(r!.text).toContain("## Structure");
574
- expect(r!.text).toContain("src/index.ts");
575
- expect(r!.text).toContain("## README.md");
576
- expect(r!.text).toContain("Hello World");
577
- });
578
-
579
- it("returns tree-only view when readme API call fails", async () => {
580
- makeGhApiMock({
581
- ".default_branch": "main",
582
- ".tree[].path": "index.ts\nlib.ts",
583
- });
584
-
585
- const r = await make().intercept("https://github.com/owner/repo", { raw: false });
586
- expect(r).not.toBeNull();
587
- expect(r!.text).toContain("## Structure");
588
- expect(r!.text).not.toContain("## README.md");
589
- });
590
-
591
- it("returns null when tree and readme both fail (no content)", async () => {
592
- makeGhApiMock({ ".default_branch": "main" });
593
-
594
- const r = await make().intercept("https://github.com/owner/repo", { raw: false });
595
- expect(r).toBeNull();
596
- });
597
-
598
- it("returns null when file content API fails", async () => {
599
- makeGhApiMock({ ".default_branch": "main" });
600
-
601
- const r = await make().intercept("https://github.com/owner/repo/blob/main/file.ts", { raw: false });
602
- expect(r).toBeNull();
603
- });
604
-
605
- it("truncates file content at 100K chars via API", async () => {
606
- const fileContentB64 = Buffer.from("x".repeat(110_000)).toString("base64");
607
- makeGhApiMock({ ".default_branch": "main", ".content": fileContentB64 });
608
-
609
- const r = await make().intercept("https://github.com/owner/repo/blob/main/big.ts", { raw: false });
610
- expect(r).not.toBeNull();
611
- expect(r!.text).toContain("[File truncated at 100K chars]");
612
- });
613
-
614
- it("uses sizeNote when repo is oversized (API-only fallback)", async () => {
615
- const readmeB64 = Buffer.from("# Big Repo").toString("base64");
616
- makeGhApiMock({
617
- ".size": "400000",
618
- ".default_branch": "main",
619
- ".tree[].path": "file.ts",
620
- "repos/owner/repo/readme": readmeB64,
621
- });
622
-
623
- const r = await make().intercept("https://github.com/owner/repo", { raw: false });
624
- expect(r).not.toBeNull();
625
- expect(r!.text).toContain("Repository is");
626
- expect(r!.text).toContain("threshold");
627
- });
628
-
629
- it("uses provided ref instead of fetching default branch (blob with explicit ref)", async () => {
630
- const fileContentB64 = Buffer.from("const v = 2;").toString("base64");
631
- makeGhApiMock({ ".content": fileContentB64 });
632
-
633
- const r = await make().intercept("https://github.com/owner/repo/blob/feature-branch/file.ts", { raw: false });
634
- expect(r).not.toBeNull();
635
- expect(r!.text).toContain("const v = 2;");
636
- });
637
-
638
- it("clones repo via gh when gh available and size below threshold", async () => {
639
- const cloneTarget = mkdtempSync(join(tmpdir(), "rpiv-gh-clone-"));
640
- try {
641
- writeFileSync(join(cloneTarget, "README.md"), "# Cloned!");
642
- mockExecFile.mockImplementation((...args: unknown[]) => {
643
- const cmdArgs = args[1] as string[];
644
- const cb = args[args.length - 1] as (err: Error | null, stdout?: string) => void;
645
- if (cmdArgs[0] === "--version") {
646
- cb(null, "gh 2.0.0");
647
- return;
648
- }
649
- if (cmdArgs[0] === "api") {
650
- const jq = cmdArgs[3] as string | undefined;
651
- if (jq === ".size") {
652
- cb(null, "100");
653
- return;
654
- }
655
- if (jq === ".default_branch") {
656
- cb(null, "main");
657
- return;
658
- }
659
- cb(new Error("unexpected api"), "");
660
- return;
661
- }
662
- if (cmdArgs[0] === "repo" && cmdArgs[1] === "clone") {
663
- const targetPath = cmdArgs[3] as string;
664
- try {
665
- mkdirSync(targetPath, { recursive: true });
666
- writeFileSync(join(targetPath, "README.md"), "# Cloned!");
667
- } catch {
668
- /* ignore */
669
- }
670
- cb(null, "");
671
- return;
672
- }
673
- cb(new Error("unexpected"), "");
674
- });
675
-
676
- const r = await make().intercept("https://github.com/owner/repo", { raw: false });
677
- expect(r).not.toBeNull();
678
- expect(r!.text).toContain("Repository cloned to:");
679
- expect(r!.text).toContain("README.md");
680
- } finally {
681
- rmSync(cloneTarget, { recursive: true, force: true });
682
- }
683
- });
684
-
685
- it("git fallback clone when gh unavailable (showGhHint + git clone path)", async () => {
686
- mockExecFile.mockImplementation((...args: unknown[]) => {
687
- const cmdArgs = args[1] as string[];
688
- const cb = args[args.length - 1] as (err: Error | null, stdout?: string) => void;
689
- if (cmdArgs[0] === "--version") {
690
- cb(new Error("not found"));
691
- return;
692
- }
693
- if (cmdArgs[0] === "clone") {
694
- const targetPath = cmdArgs[cmdArgs.length - 1] as string;
695
- try {
696
- mkdirSync(targetPath, { recursive: true });
697
- writeFileSync(join(targetPath, "index.ts"), "export default 1;");
698
- } catch {
699
- /* ignore */
700
- }
701
- cb(null, "");
702
- return;
703
- }
704
- cb(new Error("unexpected"), "");
705
- });
706
-
707
- const r = await make().intercept("https://github.com/owner/repo", { raw: false });
708
- expect(r).not.toBeNull();
709
- expect(r!.text).toContain("Repository cloned to:");
710
- });
711
-
712
- it("checkRepoSize: returns null when gh unavailable", async () => {
713
- makeGhUnavailable();
714
- const size = await make().checkRepoSize("owner", "repo");
715
- expect(size).toBeNull();
716
- });
717
-
718
- it("checkRepoSize: returns null on gh api error", async () => {
719
- makeGhAvailableApisFail();
720
- const size = await make().checkRepoSize("owner", "repo");
721
- expect(size).toBeNull();
722
- });
723
-
724
- it("checkRepoSize: returns numeric KB value", async () => {
725
- makeGhApiMock({ ".size": "12345" });
726
- const size = await make().checkRepoSize("owner", "repo");
727
- expect(size).toBe(12345);
728
- });
729
-
730
- it("checkRepoSize: returns null for non-numeric output", async () => {
731
- makeGhApiMock({ ".size": "not-a-number" });
732
- const size = await make().checkRepoSize("owner", "repo");
733
- expect(size).toBeNull();
734
- });
735
-
736
- it("checkGhAvailable: returns false when execFile fails", async () => {
737
- makeGhUnavailable();
738
- const result = await make().checkGhAvailable();
739
- expect(result).toBe(false);
740
- });
741
-
742
- it("checkGhAvailable: returns true when execFile succeeds", async () => {
743
- makeGhAvailableApisFail();
744
- const result = await make().checkGhAvailable();
745
- expect(result).toBe(true);
746
- });
747
-
748
- it("checkGhAvailable: caches the result (second call returns same value)", async () => {
749
- makeGhAvailableApisFail();
750
- const i = make();
751
- await i.checkGhAvailable();
752
- makeGhUnavailable();
753
- const second = await i.checkGhAvailable();
754
- expect(second).toBe(true);
755
- });
756
-
757
- it("signal abort between size check and clone start returns null", async () => {
758
- const controller = new AbortController();
759
- let sizeCheckDone = false;
760
- mockExecFile.mockImplementation((...args: unknown[]) => {
761
- const cmdArgs = args[1] as string[];
762
- const cb = args[args.length - 1] as (err: Error | null, stdout?: string) => void;
763
- if (cmdArgs[0] === "--version") {
764
- cb(null, "gh 2.0.0");
765
- return;
766
- }
767
- if (cmdArgs[0] === "api") {
768
- const jq = cmdArgs[3] as string | undefined;
769
- if (jq === ".size") {
770
- controller.abort();
771
- sizeCheckDone = true;
772
- cb(null, "100");
773
- return;
774
- }
775
- }
776
- cb(new Error("unexpected"), "");
777
- });
778
- const r = await make().intercept("https://github.com/owner/repo", { raw: false, signal: controller.signal });
779
- expect(r).toBeNull();
780
- expect(sizeCheckDone).toBe(true);
781
- });
782
-
783
- it("forceClone=true skips size check and attempts clone directly", async () => {
784
- makeGhAvailableApisFail();
785
- const r = await make().intercept("https://github.com/owner/repo", { raw: false, forceClone: true });
786
- expect(r).toBeNull();
787
- });
788
-
789
- it("signal abort after size check returns null", async () => {
790
- const controller = new AbortController();
791
- let sizeCallCount = 0;
792
- mockExecFile.mockImplementation((...args: unknown[]) => {
793
- const cmdArgs = args[1] as string[];
794
- const cb = args[args.length - 1] as (err: Error | null, stdout?: string) => void;
795
- if (cmdArgs[0] === "--version") {
796
- cb(null, "gh 2.0.0");
797
- return;
798
- }
799
- if (cmdArgs[0] === "api") {
800
- const jq = cmdArgs[3] as string | undefined;
801
- if (jq === ".size") {
802
- sizeCallCount++;
803
- controller.abort();
804
- cb(null, "100");
805
- return;
806
- }
807
- }
808
- cb(new Error("unexpected"), "");
809
- });
810
- const r = await make().intercept("https://github.com/owner/repo", { raw: false, signal: controller.signal });
811
- expect(r).toBeNull();
812
- expect(sizeCallCount).toBe(1);
813
- });
814
-
815
- it("readReadme falls back through candidate list (README without .md)", async () => {
816
- const tmpDir = mkdtempSync(join(tmpdir(), "rpiv-readme-"));
817
- try {
818
- writeFileSync(join(tmpDir, "README"), "Bare README content");
819
- const i = make();
820
- i._seedCache("owner/repo", { localPath: tmpDir, clonePromise: Promise.resolve(tmpDir) });
821
- const r = await i.intercept("https://github.com/owner/repo", { raw: false });
822
- expect(r!.text).toContain("Bare README content");
823
- } finally {
824
- rmSync(tmpDir, { recursive: true, force: true });
825
- }
826
- });
827
-
828
- it("buildDirListing: handles outside-repo symlink gracefully", async () => {
829
- const { symlinkSync } = await import("node:fs");
830
- const tmpDir = mkdtempSync(join(tmpdir(), "rpiv-dir-"));
831
- try {
832
- writeFileSync(join(tmpDir, "normal.ts"), "");
833
- try {
834
- symlinkSync("/tmp", join(tmpDir, "escape-link"));
835
- } catch {
836
- /* skip if fails */
837
- }
838
- const i = make();
839
- i._seedCache("owner/repo@main", { localPath: tmpDir, clonePromise: Promise.resolve(tmpDir) });
840
- const r = await i.intercept("https://github.com/owner/repo/tree/main", { raw: false });
841
- expect(r).not.toBeNull();
842
- expect(r!.text).toContain("normal.ts");
843
- } finally {
844
- rmSync(tmpDir, { recursive: true, force: true });
845
- }
846
- });
847
-
848
- it("abort after successful clone returns null and removes cache entry", async () => {
849
- const controller = new AbortController();
850
- let cloneCallCount = 0;
851
- mockExecFile.mockImplementation((...args: unknown[]) => {
852
- const cmdArgs = args[1] as string[];
853
- const cb = args[args.length - 1] as (err: Error | null, stdout?: string) => void;
854
- if (cmdArgs[0] === "--version") {
855
- cb(null, "gh 2.0.0");
856
- return;
857
- }
858
- if (cmdArgs[0] === "api" && cmdArgs[3] === ".size") {
859
- cb(new Error("size unavailable"), "");
860
- return;
861
- }
862
- if (cmdArgs[0] === "repo" && cmdArgs[1] === "clone") {
863
- cloneCallCount++;
864
- const targetPath = cmdArgs[3] as string;
865
- try {
866
- mkdirSync(targetPath, { recursive: true });
867
- } catch {
868
- /* ignore */
869
- }
870
- controller.abort();
871
- cb(null, "");
872
- return;
873
- }
874
- cb(new Error("unexpected"), "");
875
- });
876
- const r = await make().intercept("https://github.com/owner/repo", { raw: false, signal: controller.signal });
877
- expect(r).toBeNull();
878
- expect(cloneCallCount).toBe(1);
879
- });
880
-
881
- it("awaitCachedClone: signal aborted before clone promise resolves returns null", async () => {
882
- const tmpDir = mkdtempSync(join(tmpdir(), "rpiv-abort-"));
883
- try {
884
- writeFileSync(join(tmpDir, "index.ts"), "");
885
- const controller = new AbortController();
886
- controller.abort();
887
- const i = make();
888
- i._seedCache("owner/repo", { localPath: tmpDir, clonePromise: Promise.resolve(tmpDir) });
889
- const r = await i.intercept("https://github.com/owner/repo", { raw: false, signal: controller.signal });
890
- expect(r).toBeNull();
891
- } finally {
892
- rmSync(tmpDir, { recursive: true, force: true });
893
- }
894
- });
895
-
896
- it("concurrent clone: second intercept call reuses existing cache entry", async () => {
897
- const tmpDir = mkdtempSync(join(tmpdir(), "rpiv-concurrent-"));
898
- try {
899
- writeFileSync(join(tmpDir, "index.ts"), "const x = 1;");
900
- const i = make();
901
- i._seedCache("owner/repo", { localPath: tmpDir, clonePromise: Promise.resolve(tmpDir) });
902
- const r = await i.intercept("https://github.com/owner/repo", { raw: false });
903
- expect(r).not.toBeNull();
904
- expect(r!.text).toContain("index.ts");
905
- } finally {
906
- rmSync(tmpDir, { recursive: true, force: true });
907
- }
908
- });
909
-
910
- it("SHA URL with sizeNote: proceeds to fetchViaApi with commit SHA note", async () => {
911
- const sha = "b".repeat(40);
912
- const fileContentB64 = Buffer.from("const sha = true;").toString("base64");
913
- makeGhApiMock({ ".default_branch": "main", ".content": fileContentB64 });
914
- const r = await make().intercept(`https://github.com/owner/repo/blob/${sha}/file.ts`, { raw: false });
915
- expect(r).not.toBeNull();
916
- expect(r!.text).toContain("Note: Commit SHA URLs use the GitHub API");
917
- expect(r!.text).toContain("const sha = true;");
918
- });
919
-
920
- it("maxRepoSizeMB override threshold is honored", async () => {
921
- // Override threshold to 50MB; with size=400MB, hits oversized path.
922
- const readmeB64 = Buffer.from("# Big Repo").toString("base64");
923
- makeGhApiMock({
924
- ".size": "400000",
925
- ".default_branch": "main",
926
- ".tree[].path": "file.ts",
927
- "repos/owner/repo/readme": readmeB64,
928
- });
929
- const r = await make({ maxRepoSizeMB: 50 }).intercept("https://github.com/owner/repo", { raw: false });
930
- expect(r).not.toBeNull();
931
- expect(r!.text).toMatch(/threshold: 50/);
932
- });
933
- });