github-search-cli 0.8.0 → 0.8.1

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.
package/src/compare.ts CHANGED
@@ -1,46 +1,46 @@
1
- /**
2
- * Repo comparison — side-by-side table for 2+ repos.
3
- */
4
- import type { Repo } from "./types";
5
-
6
- interface CompareRow {
7
- label: string;
8
- values: string[];
9
- }
10
-
11
- /** Build a comparison table as an array of text rows. */
12
- export function buildComparisonTable(repos: Repo[]): string {
13
- if (repos.length < 2) return "Select at least 2 repos to compare (press c to add).";
14
-
15
- const rows: CompareRow[] = [];
16
- const names = repos.map((r) => r.fullName);
17
-
18
- rows.push({ label: "Stars", values: repos.map((r) => `★ ${r.stars.toLocaleString()}`) });
19
- rows.push({ label: "Forks", values: repos.map((r) => r.forks.toLocaleString()) });
20
- rows.push({ label: "Language", values: repos.map((r) => r.language ?? "—") });
21
- rows.push({ label: "Created", values: repos.map((r) => r.createdAt?.slice(0, 7) ?? "—") });
22
- rows.push({ label: "Updated", values: repos.map((r) => r.updatedAt?.slice(0, 10) ?? "—") });
23
- rows.push({ label: "Topics", values: repos.map((r) => (r.topics?.slice(0, 3).join(", ") ?? "—") || "—") });
24
-
25
- // Calculate the max width for each column
26
- const colW = Math.max(15, ...names.map((n) => n.length));
27
- const valW = Math.max(8, ...rows.flatMap((r) => r.values.map((v) => v.length)));
28
-
29
- // Header row
30
- const header = ["".padEnd(14), ...names.map((n) => n.padEnd(colW))];
31
- const sep = ["".padEnd(14, "─"), ...names.map(() => "".padEnd(colW, "─"))];
32
-
33
- const lines: string[] = [
34
- "┌" + sep.map((s) => "─" + s + "─").join("┬") + "┐",
35
- "│" + header.map((h) => ` ${h} `).join("│") + "│",
36
- "├" + sep.map((s) => "─" + s + "─").join("┼") + "┤",
37
- ];
38
-
39
- for (const row of rows) {
40
- const cells = [row.label.padEnd(14), ...row.values.map((v) => v.padEnd(colW))];
41
- lines.push("│" + cells.map((c) => ` ${c} `).join("│") + "│");
42
- }
43
-
44
- lines.push("└" + sep.map((s) => "─" + s + "─").join("┴") + "┘");
45
- return lines.join("\n");
46
- }
1
+ /**
2
+ * Repo comparison — side-by-side table for 2+ repos.
3
+ */
4
+ import type { Repo } from "./types";
5
+
6
+ interface CompareRow {
7
+ label: string;
8
+ values: string[];
9
+ }
10
+
11
+ /** Build a comparison table as an array of text rows. */
12
+ export function buildComparisonTable(repos: Repo[]): string {
13
+ if (repos.length < 2) return "Select at least 2 repos to compare (press c to add).";
14
+
15
+ const rows: CompareRow[] = [];
16
+ const names = repos.map((r) => r.fullName);
17
+
18
+ rows.push({ label: "Stars", values: repos.map((r) => `★ ${r.stars.toLocaleString()}`) });
19
+ rows.push({ label: "Forks", values: repos.map((r) => r.forks.toLocaleString()) });
20
+ rows.push({ label: "Language", values: repos.map((r) => r.language ?? "—") });
21
+ rows.push({ label: "Created", values: repos.map((r) => r.createdAt?.slice(0, 7) ?? "—") });
22
+ rows.push({ label: "Updated", values: repos.map((r) => r.updatedAt?.slice(0, 10) ?? "—") });
23
+ rows.push({ label: "Topics", values: repos.map((r) => (r.topics?.slice(0, 3).join(", ") ?? "—") || "—") });
24
+
25
+ // Calculate the max width for each column
26
+ const colW = Math.max(15, ...names.map((n) => n.length));
27
+ const valW = Math.max(8, ...rows.flatMap((r) => r.values.map((v) => v.length)));
28
+
29
+ // Header row
30
+ const header = ["".padEnd(14), ...names.map((n) => n.padEnd(colW))];
31
+ const sep = ["".padEnd(14, "─"), ...names.map(() => "".padEnd(colW, "─"))];
32
+
33
+ const lines: string[] = [
34
+ "┌" + sep.map((s) => "─" + s + "─").join("┬") + "┐",
35
+ "│" + header.map((h) => ` ${h} `).join("│") + "│",
36
+ "├" + sep.map((s) => "─" + s + "─").join("┼") + "┤",
37
+ ];
38
+
39
+ for (const row of rows) {
40
+ const cells = [row.label.padEnd(14), ...row.values.map((v) => v.padEnd(colW))];
41
+ lines.push("│" + cells.map((c) => ` ${c} `).join("│") + "│");
42
+ }
43
+
44
+ lines.push("└" + sep.map((s) => "─" + s + "─").join("┴") + "┘");
45
+ return lines.join("\n");
46
+ }
package/src/config.ts CHANGED
@@ -1,65 +1,65 @@
1
- /**
2
- * Config system: load/save config from XDG paths, merge with env vars.
3
- *
4
- * Lookup order:
5
- * 1. GHFIND_CONFIG env var
6
- * 2. $XDG_CONFIG_HOME/ghfind/config.json
7
- * 3. ~/.config/ghfind/config.json
8
- */
9
- import type { Config } from "./types";
10
- import { homedir } from "os";
11
- import { join } from "path";
12
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
13
-
14
- /** Directory for persistent state (history, bookmarks, session). */
15
- export function stateDir(): string {
16
- const xdg = process.env.XDG_STATE_HOME;
17
- const base = xdg ? join(xdg, "ghfind") : join(homedir(), ".local", "share", "ghfind");
18
- return base;
19
- }
20
-
21
- /** Directory for cache files. */
22
- export function cacheDir(): string {
23
- const xdg = process.env.XDG_CACHE_HOME;
24
- const base = xdg ? join(xdg, "ghfind") : join(homedir(), ".cache", "ghfind");
25
- return base;
26
- }
27
- const DEFAULTS: Config = {
28
- defaultSort: "best-match",
29
- defaultLimit: 50,
30
- theme: "tokyo-night",
31
- cacheTtlSeconds: 300,
32
- defaultTab: "search",
33
- };
34
-
35
- export function configPath(): string {
36
- const envPath = process.env.GHFIND_CONFIG;
37
- if (envPath) return envPath;
38
-
39
- const xdg = process.env.XDG_CONFIG_HOME;
40
- const base = xdg ? join(xdg, "ghfind") : join(homedir(), ".config", "ghfind");
41
- return join(base, "config.json");
42
- }
43
-
44
- export function loadConfig(): Config {
45
- const path = configPath();
46
- try {
47
- const raw = readFileSync(path, "utf-8");
48
- const parsed = JSON.parse(raw);
49
- return mergeWithEnv({ ...DEFAULTS, ...parsed });
50
- } catch {
51
- return mergeWithEnv({ ...DEFAULTS });
52
- }
53
- }
54
-
55
- export function saveConfig(config: Config): void {
56
- const path = configPath();
57
- const dir = path.slice(0, Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")));
58
- mkdirSync(dir, { recursive: true });
59
- writeFileSync(path, JSON.stringify(config, null, 2));
60
- }
61
-
62
- function mergeWithEnv(config: Config): Config {
63
- if (process.env.GITHUB_TOKEN) config.githubToken = process.env.GITHUB_TOKEN;
64
- return config;
65
- }
1
+ /**
2
+ * Config system: load/save config from XDG paths, merge with env vars.
3
+ *
4
+ * Lookup order:
5
+ * 1. GHFIND_CONFIG env var
6
+ * 2. $XDG_CONFIG_HOME/ghfind/config.json
7
+ * 3. ~/.config/ghfind/config.json
8
+ */
9
+ import type { Config } from "./types";
10
+ import { homedir } from "os";
11
+ import { join } from "path";
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
13
+
14
+ /** Directory for persistent state (history, bookmarks, session). */
15
+ export function stateDir(): string {
16
+ const xdg = process.env.XDG_STATE_HOME;
17
+ const base = xdg ? join(xdg, "ghfind") : join(homedir(), ".local", "share", "ghfind");
18
+ return base;
19
+ }
20
+
21
+ /** Directory for cache files. */
22
+ export function cacheDir(): string {
23
+ const xdg = process.env.XDG_CACHE_HOME;
24
+ const base = xdg ? join(xdg, "ghfind") : join(homedir(), ".cache", "ghfind");
25
+ return base;
26
+ }
27
+ const DEFAULTS: Config = {
28
+ defaultSort: "best-match",
29
+ defaultLimit: 50,
30
+ theme: "tokyo-night",
31
+ cacheTtlSeconds: 300,
32
+ defaultTab: "search",
33
+ };
34
+
35
+ export function configPath(): string {
36
+ const envPath = process.env.GHFIND_CONFIG;
37
+ if (envPath) return envPath;
38
+
39
+ const xdg = process.env.XDG_CONFIG_HOME;
40
+ const base = xdg ? join(xdg, "ghfind") : join(homedir(), ".config", "ghfind");
41
+ return join(base, "config.json");
42
+ }
43
+
44
+ export function loadConfig(): Config {
45
+ const path = configPath();
46
+ try {
47
+ const raw = readFileSync(path, "utf-8");
48
+ const parsed = JSON.parse(raw);
49
+ return mergeWithEnv({ ...DEFAULTS, ...parsed });
50
+ } catch {
51
+ return mergeWithEnv({ ...DEFAULTS });
52
+ }
53
+ }
54
+
55
+ export function saveConfig(config: Config): void {
56
+ const path = configPath();
57
+ const dir = path.slice(0, Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")));
58
+ mkdirSync(dir, { recursive: true });
59
+ writeFileSync(path, JSON.stringify(config, null, 2));
60
+ }
61
+
62
+ function mergeWithEnv(config: Config): Config {
63
+ if (process.env.GITHUB_TOKEN) config.githubToken = process.env.GITHUB_TOKEN;
64
+ return config;
65
+ }
package/src/deepdive.ts CHANGED
@@ -1,118 +1,118 @@
1
- /** Repo deep-dive — fetch and format rich repo details. */
2
- import type { Repo } from "./types";
3
- import { NetworkError } from "./errors";
4
-
5
- const USER_AGENT = "ghfind/1.0";
6
-
7
- /** Language breakdown: { [lang]: bytes } */
8
- type LanguageMap = Record<string, number>;
9
-
10
- /** Contributor summary */
11
- interface Contributor {
12
- login: string;
13
- contributions: number;
14
- }
15
-
16
- /** All deep-dive data for one repo. */
17
- export interface DeepDiveData {
18
- summary: string;
19
- languages: string;
20
- contributors: string;
21
- readme: string;
22
- }
23
-
24
- /** Fetch all deep-dive data for a repo. Returns formatted sections. */
25
- export async function fetchDeepDive(repo: Repo, token?: string): Promise<DeepDiveData> {
26
- const auth = token ? { Authorization: `Bearer ${token}` } : {};
27
- const headers = { "User-Agent": USER_AGENT, ...auth };
28
-
29
- const [languagesRes, contributorsRes] = await Promise.all([
30
- fetch(`https://api.github.com/repos/${repo.owner}/${repo.name}/languages`, { headers }),
31
- fetch(`https://api.github.com/repos/${repo.owner}/${repo.name}/contributors?per_page=5`, { headers }),
32
- ]);
33
-
34
- // README with branch fallback: main → master → README.rst
35
- let readmeText = "";
36
- for (const path of [`${repo.owner}/${repo.name}/main/README.md`, `${repo.owner}/${repo.name}/master/README.md`, `${repo.owner}/${repo.name}/main/README.rst`]) {
37
- const r = await fetch(`https://raw.githubusercontent.com/${path}`, { headers });
38
- if (r.ok) { readmeText = await r.text(); break; }
39
- }
40
-
41
- return {
42
- summary: formatSummary(repo),
43
- languages: formatLanguages(languagesRes.ok ? await languagesRes.json().catch(() => ({})) : {}),
44
- contributors: formatContributors(contributorsRes.ok ? await contributorsRes.json().catch(() => []) : []),
45
- readme: formatReadme(readmeText),
46
- };
47
- }
48
-
49
- function formatSummary(repo: Repo): string {
50
- const lines = [
51
- ` ${repo.fullName}`,
52
- ` ★ ${repo.stars.toLocaleString()} ◆ ${repo.forks.toLocaleString()} ${repo.language ?? "—"}`,
53
- repo.description ? ` ${repo.description}` : "",
54
- repo.topics.length ? ` topics: ${repo.topics.slice(0, 8).join(", ")}` : "",
55
- ` ${repo.url}`,
56
- ];
57
- return lines.filter(Boolean).join("\n");
58
- }
59
-
60
- function formatLanguages(langs: LanguageMap): string {
61
- const entries = Object.entries(langs);
62
- if (entries.length === 0) return " (no language data)";
63
- const total = entries.reduce((s, [, v]) => s + v, 0);
64
- const barW = 20;
65
- return entries
66
- .sort(([, a], [, b]) => b - a)
67
- .slice(0, 8)
68
- .map(([name, bytes]) => {
69
- const pct = ((bytes / total) * 100).toFixed(1);
70
- const filled = Math.round((bytes / total) * barW);
71
- const bar = "█".repeat(filled) + "░".repeat(barW - filled);
72
- return ` ${name.padEnd(16)} ${bar} ${pct}%`;
73
- })
74
- .join("\n");
75
- }
76
-
77
- function formatContributors(contributors: Contributor[]): string {
78
- if (contributors.length === 0) return " (no contributor data)";
79
- return contributors
80
- .slice(0, 5)
81
- .map((c) => ` ▲ ${c.login.padEnd(20)} ${c.contributions} commits`)
82
- .join("\n");
83
- }
84
-
85
- function formatReadme(readme: string): string {
86
- if (!readme) return " (no README)";
87
- // Strip markdown formatting for terminal display
88
- const stripped = readme
89
- .replace(/```[\s\S]*?```/g, "[code block]")
90
- .replace(/#{1,6}\s/g, "")
91
- .replace(/\*\*(.+?)\*\*/g, "$1")
92
- .replace(/\[(.+?)\]\(.+?\)/g, "$1")
93
- .replace(/`([^`]+)`/g, "$1")
94
- .split("\n")
95
- .map((l) => l.trim())
96
- .filter(Boolean);
97
-
98
- const lines = stripped.slice(0, 30);
99
- if (stripped.length > 30) lines.push("... (more lines, open in browser to read full)");
100
- return lines.map((l) => ` ${l}`).join("\n");
101
- }
102
-
103
- /** Build the full deep-dive display text from data. */
104
- export function buildDeepDiveText(data: DeepDiveData): string {
105
- return [
106
- "── Summary ──────────────────────────────────────",
107
- data.summary,
108
- "",
109
- "── Languages ────────────────────────────────────",
110
- data.languages,
111
- "",
112
- "── Top Contributors ─────────────────────────────",
113
- data.contributors,
114
- "",
115
- "── README ───────────────────────────────────────",
116
- data.readme,
117
- ].join("\n");
118
- }
1
+ /** Repo deep-dive — fetch and format rich repo details. */
2
+ import type { Repo } from "./types";
3
+ import { NetworkError } from "./errors";
4
+
5
+ const USER_AGENT = "ghfind/1.0";
6
+
7
+ /** Language breakdown: { [lang]: bytes } */
8
+ type LanguageMap = Record<string, number>;
9
+
10
+ /** Contributor summary */
11
+ interface Contributor {
12
+ login: string;
13
+ contributions: number;
14
+ }
15
+
16
+ /** All deep-dive data for one repo. */
17
+ export interface DeepDiveData {
18
+ summary: string;
19
+ languages: string;
20
+ contributors: string;
21
+ readme: string;
22
+ }
23
+
24
+ /** Fetch all deep-dive data for a repo. Returns formatted sections. */
25
+ export async function fetchDeepDive(repo: Repo, token?: string): Promise<DeepDiveData> {
26
+ const auth = token ? { Authorization: `Bearer ${token}` } : {};
27
+ const headers = { "User-Agent": USER_AGENT, ...auth };
28
+
29
+ const [languagesRes, contributorsRes] = await Promise.all([
30
+ fetch(`https://api.github.com/repos/${repo.owner}/${repo.name}/languages`, { headers }),
31
+ fetch(`https://api.github.com/repos/${repo.owner}/${repo.name}/contributors?per_page=5`, { headers }),
32
+ ]);
33
+
34
+ // README with branch fallback: main → master → README.rst
35
+ let readmeText = "";
36
+ for (const path of [`${repo.owner}/${repo.name}/main/README.md`, `${repo.owner}/${repo.name}/master/README.md`, `${repo.owner}/${repo.name}/main/README.rst`]) {
37
+ const r = await fetch(`https://raw.githubusercontent.com/${path}`, { headers });
38
+ if (r.ok) { readmeText = await r.text(); break; }
39
+ }
40
+
41
+ return {
42
+ summary: formatSummary(repo),
43
+ languages: formatLanguages(languagesRes.ok ? await languagesRes.json().catch(() => ({})) : {}),
44
+ contributors: formatContributors(contributorsRes.ok ? await contributorsRes.json().catch(() => []) : []),
45
+ readme: formatReadme(readmeText),
46
+ };
47
+ }
48
+
49
+ function formatSummary(repo: Repo): string {
50
+ const lines = [
51
+ ` ${repo.fullName}`,
52
+ ` ★ ${repo.stars.toLocaleString()} ◆ ${repo.forks.toLocaleString()} ${repo.language ?? "—"}`,
53
+ repo.description ? ` ${repo.description}` : "",
54
+ repo.topics.length ? ` topics: ${repo.topics.slice(0, 8).join(", ")}` : "",
55
+ ` ${repo.url}`,
56
+ ];
57
+ return lines.filter(Boolean).join("\n");
58
+ }
59
+
60
+ function formatLanguages(langs: LanguageMap): string {
61
+ const entries = Object.entries(langs);
62
+ if (entries.length === 0) return " (no language data)";
63
+ const total = entries.reduce((s, [, v]) => s + v, 0);
64
+ const barW = 20;
65
+ return entries
66
+ .sort(([, a], [, b]) => b - a)
67
+ .slice(0, 8)
68
+ .map(([name, bytes]) => {
69
+ const pct = ((bytes / total) * 100).toFixed(1);
70
+ const filled = Math.round((bytes / total) * barW);
71
+ const bar = "█".repeat(filled) + "░".repeat(barW - filled);
72
+ return ` ${name.padEnd(16)} ${bar} ${pct}%`;
73
+ })
74
+ .join("\n");
75
+ }
76
+
77
+ function formatContributors(contributors: Contributor[]): string {
78
+ if (contributors.length === 0) return " (no contributor data)";
79
+ return contributors
80
+ .slice(0, 5)
81
+ .map((c) => ` ▲ ${c.login.padEnd(20)} ${c.contributions} commits`)
82
+ .join("\n");
83
+ }
84
+
85
+ function formatReadme(readme: string): string {
86
+ if (!readme) return " (no README)";
87
+ // Strip markdown formatting for terminal display
88
+ const stripped = readme
89
+ .replace(/```[\s\S]*?```/g, "[code block]")
90
+ .replace(/#{1,6}\s/g, "")
91
+ .replace(/\*\*(.+?)\*\*/g, "$1")
92
+ .replace(/\[(.+?)\]\(.+?\)/g, "$1")
93
+ .replace(/`([^`]+)`/g, "$1")
94
+ .split("\n")
95
+ .map((l) => l.trim())
96
+ .filter(Boolean);
97
+
98
+ const lines = stripped.slice(0, 30);
99
+ if (stripped.length > 30) lines.push("... (more lines, open in browser to read full)");
100
+ return lines.map((l) => ` ${l}`).join("\n");
101
+ }
102
+
103
+ /** Build the full deep-dive display text from data. */
104
+ export function buildDeepDiveText(data: DeepDiveData): string {
105
+ return [
106
+ "── Summary ──────────────────────────────────────",
107
+ data.summary,
108
+ "",
109
+ "── Languages ────────────────────────────────────",
110
+ data.languages,
111
+ "",
112
+ "── Top Contributors ─────────────────────────────",
113
+ data.contributors,
114
+ "",
115
+ "── README ───────────────────────────────────────",
116
+ data.readme,
117
+ ].join("\n");
118
+ }
package/src/errors.ts CHANGED
@@ -1,59 +1,59 @@
1
- /** Structured error types with user-facing messages. */
2
-
3
- export class SearchCliError extends Error {
4
- constructor(
5
- message: string,
6
- public readonly userMessage: string,
7
- public readonly recoverable: boolean = true,
8
- ) {
9
- super(message);
10
- this.name = "SearchCliError";
11
- }
12
- }
13
-
14
- export class NetworkError extends SearchCliError {
15
- constructor() {
16
- super(
17
- "Network request failed",
18
- "⚠ Network error — check your connection. Retrying in 5s... [r]etry now",
19
- );
20
- this.name = "NetworkError";
21
- }
22
- }
23
-
24
- export class RateLimitError extends SearchCliError {
25
- constructor(public readonly hasToken: boolean, resetSeconds?: number) {
26
- const msg = hasToken
27
- ? `⚠ API rate limit exceeded (5,000/hr). Resets in ${resetSeconds ?? "?"}s. [r]etry [c]hange token`
28
- : "⚠ Rate limited (60/hr). Set GITHUB_TOKEN for 5,000/hr. [r]etry";
29
- super(msg, msg);
30
- this.name = "RateLimitError";
31
- }
32
- }
33
-
34
- export class BadQueryError extends SearchCliError {
35
- constructor(public readonly detail: string) {
36
- super(`Invalid query: ${detail}`, `⚠ Invalid query: ${detail}`);
37
- this.name = "BadQueryError";
38
- }
39
- }
40
-
41
- export class NoResultsError extends SearchCliError {
42
- constructor(public readonly query: string) {
43
- super(
44
- `No results for "${query}"`,
45
- `🔍 No results for "${query}". Tips: check spelling, try fewer qualifiers, or [b]rowse trending`,
46
- );
47
- this.name = "NoResultsError";
48
- }
49
- }
50
-
51
- export class ParseError extends SearchCliError {
52
- constructor(source: string, detail: string) {
53
- super(
54
- `Parse error from ${source}: ${detail}`,
55
- `⚠ Could not parse ${source}. GitHub may have changed the layout. [r]etry`,
56
- );
57
- this.name = "ParseError";
58
- }
59
- }
1
+ /** Structured error types with user-facing messages. */
2
+
3
+ export class SearchCliError extends Error {
4
+ constructor(
5
+ message: string,
6
+ public readonly userMessage: string,
7
+ public readonly recoverable: boolean = true,
8
+ ) {
9
+ super(message);
10
+ this.name = "SearchCliError";
11
+ }
12
+ }
13
+
14
+ export class NetworkError extends SearchCliError {
15
+ constructor() {
16
+ super(
17
+ "Network request failed",
18
+ "⚠ Network error — check your connection. Retrying in 5s... [r]etry now",
19
+ );
20
+ this.name = "NetworkError";
21
+ }
22
+ }
23
+
24
+ export class RateLimitError extends SearchCliError {
25
+ constructor(public readonly hasToken: boolean, resetSeconds?: number) {
26
+ const msg = hasToken
27
+ ? `⚠ API rate limit exceeded (5,000/hr). Resets in ${resetSeconds ?? "?"}s. [r]etry [c]hange token`
28
+ : "⚠ Rate limited (60/hr). Set GITHUB_TOKEN for 5,000/hr. [r]etry";
29
+ super(msg, msg);
30
+ this.name = "RateLimitError";
31
+ }
32
+ }
33
+
34
+ export class BadQueryError extends SearchCliError {
35
+ constructor(public readonly detail: string) {
36
+ super(`Invalid query: ${detail}`, `⚠ Invalid query: ${detail}`);
37
+ this.name = "BadQueryError";
38
+ }
39
+ }
40
+
41
+ export class NoResultsError extends SearchCliError {
42
+ constructor(public readonly query: string) {
43
+ super(
44
+ `No results for "${query}"`,
45
+ `🔍 No results for "${query}". Tips: check spelling, try fewer qualifiers, or [b]rowse trending`,
46
+ );
47
+ this.name = "NoResultsError";
48
+ }
49
+ }
50
+
51
+ export class ParseError extends SearchCliError {
52
+ constructor(source: string, detail: string) {
53
+ super(
54
+ `Parse error from ${source}: ${detail}`,
55
+ `⚠ Could not parse ${source}. GitHub may have changed the layout. [r]etry`,
56
+ );
57
+ this.name = "ParseError";
58
+ }
59
+ }
package/src/explore.ts CHANGED
@@ -1,29 +1,29 @@
1
- /**
2
- * Topic explorer — browse popular GitHub topics.
3
- *
4
- * Selecting a topic triggers a search.
5
- */
6
- export interface TopicItem {
7
- name: string;
8
- description: string;
9
- repoCount: number;
10
- }
11
-
12
- /** Fetch popular topics from GitHub search API.
13
- * Requires the `mercy-preview` media type for the /search/topics endpoint.
14
- */
15
- export async function fetchTopics(): Promise<TopicItem[]> {
16
- const res = await fetch("https://api.github.com/search/topics?q=popular&per_page=30", {
17
- headers: {
18
- Accept: "application/vnd.github.mercy-preview+json",
19
- "User-Agent": "search-cli",
20
- },
21
- });
22
- if (!res.ok) throw new Error(`Topics API: HTTP ${res.status}`);
23
- const data = await res.json() as { items?: Array<{ name: string; description?: string; score?: number }> };
24
- return (data.items ?? []).map((item) => ({
25
- name: item.name,
26
- description: item.description || "",
27
- repoCount: item.score || 0,
28
- }));
29
- }
1
+ /**
2
+ * Topic explorer — browse popular GitHub topics.
3
+ *
4
+ * Selecting a topic triggers a search.
5
+ */
6
+ export interface TopicItem {
7
+ name: string;
8
+ description: string;
9
+ repoCount: number;
10
+ }
11
+
12
+ /** Fetch popular topics from GitHub search API.
13
+ * Requires the `mercy-preview` media type for the /search/topics endpoint.
14
+ */
15
+ export async function fetchTopics(): Promise<TopicItem[]> {
16
+ const res = await fetch("https://api.github.com/search/topics?q=popular&per_page=30", {
17
+ headers: {
18
+ Accept: "application/vnd.github.mercy-preview+json",
19
+ "User-Agent": "search-cli",
20
+ },
21
+ });
22
+ if (!res.ok) throw new Error(`Topics API: HTTP ${res.status}`);
23
+ const data = await res.json() as { items?: Array<{ name: string; description?: string; score?: number }> };
24
+ return (data.items ?? []).map((item) => ({
25
+ name: item.name,
26
+ description: item.description || "",
27
+ repoCount: item.score || 0,
28
+ }));
29
+ }