-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathdocs.ts
More file actions
228 lines (192 loc) · 6.51 KB
/
docs.ts
File metadata and controls
228 lines (192 loc) · 6.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import { Command } from "commander";
import pc from "picocolors";
import ora from "ora";
import { resolveLibrary, getLibraryContext } from "../utils/api.js";
import { log } from "../utils/logger.js";
import { trackEvent } from "../utils/tracking.js";
import { loadTokens, isTokenExpired } from "../utils/auth.js";
import type { LibrarySearchResult, ContextResponse } from "../types.js";
const isTTY = process.stdout.isTTY;
function getAccessToken(): string | undefined {
const tokens = loadTokens();
if (!tokens || isTokenExpired(tokens)) return undefined;
return tokens.access_token;
}
function formatLibraryResult(lib: LibrarySearchResult, index: number): string {
const lines: string[] = [];
lines.push(`${pc.dim(`${index + 1}.`)} ${pc.bold(lib.title)} ${pc.cyan(lib.id)}`);
if (lib.description) {
lines.push(` ${pc.dim(lib.description)}`);
}
const meta: string[] = [];
if (lib.totalSnippets) {
meta.push(`${lib.totalSnippets} snippets`);
}
if (lib.stars && lib.stars > 0) {
meta.push(`${lib.stars.toLocaleString()} stars`);
}
if (lib.trustScore !== undefined) {
meta.push(`trust: ${lib.trustScore}/10`);
}
if (lib.benchmarkScore !== undefined && lib.benchmarkScore > 0) {
meta.push(`benchmark: ${lib.benchmarkScore}`);
}
if (meta.length > 0) {
lines.push(` ${pc.dim(meta.join(" · "))}`);
}
if (lib.versions && lib.versions.length > 0) {
lines.push(` ${pc.dim(`versions: ${lib.versions.join(", ")}`)}`);
}
return lines.join("\n");
}
async function resolveCommand(
library: string,
query: string | undefined,
options: { json?: boolean }
): Promise<void> {
trackEvent("command", { name: "library" });
const spinner = isTTY ? ora(`Searching for "${library}"...`).start() : null;
const accessToken = getAccessToken();
let data;
try {
data = await resolveLibrary(library, query, accessToken);
} catch (err) {
spinner?.fail(`Error: ${err instanceof Error ? err.message : String(err)}`);
if (!spinner) log.error(err instanceof Error ? err.message : String(err));
process.exitCode = 1;
return;
}
if (data.error) {
spinner?.fail(data.message || data.error);
if (!spinner) log.error(data.message || data.error);
process.exitCode = 1;
return;
}
if (!data.results || data.results.length === 0) {
spinner?.warn(`No libraries found matching "${library}"`);
if (!spinner) log.warn(`No libraries found matching "${library}"`);
return;
}
const results = data.results;
spinner?.stop();
if (options.json) {
console.log(JSON.stringify(results, null, 2));
return;
}
log.blank();
if (data.searchFilterApplied) {
log.warn(
"Your results only include libraries matching your access settings. To search across all public libraries, update your settings at https://context7.com/dashboard?tab=libraries"
);
log.blank();
}
for (let i = 0; i < results.length; i++) {
log.plain(formatLibraryResult(results[i], i));
log.blank();
}
if (isTTY && results.length > 0) {
const best = results[0];
log.plain(
`${pc.bold("Quick command:")}\n` + ` ${pc.cyan(`ctx7 docs "${best.id}" "<your question>"`)}`
);
log.blank();
}
}
async function queryCommand(
libraryId: string,
query: string,
options: { json?: boolean }
): Promise<void> {
trackEvent("command", { name: "docs" });
if (!libraryId.startsWith("/")) {
log.error(`Invalid library ID: ${libraryId}`);
log.info(`Library IDs start with "/" (e.g., /facebook/react)`);
log.info(`Run "ctx7 library <name>" to find the correct ID`);
process.exitCode = 1;
return;
}
const spinner = isTTY ? ora(`Fetching docs for "${libraryId}"...`).start() : null;
const accessToken = getAccessToken();
const outputType = options.json ? "json" : "txt";
let result;
try {
result = await getLibraryContext(libraryId, query, { type: outputType }, accessToken);
} catch (err) {
spinner?.fail(`Error: ${err instanceof Error ? err.message : String(err)}`);
if (!spinner) log.error(err instanceof Error ? err.message : String(err));
process.exitCode = 1;
return;
}
if (typeof result === "string") {
spinner?.stop();
console.log(result);
return;
}
const ctx = result as ContextResponse;
if (ctx.error) {
if (ctx.redirectUrl) {
spinner?.warn("Library has been redirected");
if (!spinner) log.warn("Library has been redirected");
log.info(`New ID: ${pc.cyan(ctx.redirectUrl)}`);
log.info(`Run: ${pc.cyan(`ctx7 docs "${ctx.redirectUrl}" "${query}"`)}`);
process.exitCode = 1;
return;
}
spinner?.fail(ctx.message || ctx.error);
if (!spinner) log.error(ctx.message || ctx.error);
process.exitCode = 1;
return;
}
const total = (ctx.codeSnippets?.length || 0) + (ctx.infoSnippets?.length || 0);
if (total === 0) {
spinner?.warn(`No documentation found for: "${query}"`);
if (!spinner) log.warn(`No documentation found for: "${query}"`);
return;
}
spinner?.stop();
if (options.json) {
console.log(JSON.stringify(ctx, null, 2));
return;
}
log.blank();
if (ctx.codeSnippets) {
for (const snippet of ctx.codeSnippets) {
log.plain(pc.bold(snippet.codeTitle));
if (snippet.codeDescription) log.dim(snippet.codeDescription);
log.blank();
for (const code of snippet.codeList) {
log.plain("```" + code.language);
log.plain(code.code);
log.plain("```");
log.blank();
}
}
}
if (ctx.infoSnippets) {
for (const snippet of ctx.infoSnippets) {
if (snippet.breadcrumb) log.plain(pc.bold(snippet.breadcrumb));
log.plain(snippet.content);
log.blank();
}
}
}
export function registerDocsCommands(program: Command): void {
program
.command("library")
.argument("<name>", "Library name to search for")
.argument("[query]", "Question or task for relevance ranking")
.option("--json", "Output as JSON")
.description("Resolve a library name to a Context7 library ID")
.action(async (name: string, query: string | undefined, options: { json?: boolean }) => {
await resolveCommand(name, query, options);
});
program
.command("docs")
.argument("<libraryId>", "Context7 library ID (e.g., /facebook/react)")
.argument("<query>", "Question or task to get docs for")
.option("--json", "Output as JSON")
.description("Query documentation for a library")
.action(async (libraryId: string, query: string, options: { json?: boolean }) => {
await queryCommand(libraryId, query, options);
});
}