Repository navigation
Expand file tree
/
Copy pathdiscover.ts
More file actions
537 lines (484 loc) · 17.8 KB
/
Copy pathdiscover.ts
File metadata and controls
537 lines (484 loc) · 17.8 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import type { RunConfig, DiscoveryResult, DiscoveryMethod } from "./types.ts";
const DISCOVERY_TIMEOUT = 5000;
const NON_EN_LANG_SEGMENTS = [
"fr", "de", "ja", "zh", "ko", "es", "pt", "it", "ru", "nl", "pl", "sv",
"tr", "ar", "th", "vi", "cs", "ro", "hu", "uk", "el", "he", "id", "ms",
"da", "fi", "no", "sk", "bg", "hr", "sr", "sl", "lt", "lv", "et",
];
function log(msg: string): void {
process.stderr.write(`[discover] ${msg}\n`);
}
async function timedFetch(url: string, init?: RequestInit): Promise<Response> {
return fetch(url, { ...init, signal: AbortSignal.timeout(DISCOVERY_TIMEOUT) });
}
function filterUrls(urls: string[], baseUrl: string, config: RunConfig): string[] {
const base = new URL(baseUrl);
const domain = base.hostname;
let filtered = urls
.map((u) => {
try {
const parsed = new URL(u, baseUrl);
parsed.hash = "";
return parsed.href;
} catch {
return null;
}
})
.filter((u): u is string => u !== null)
.filter((u) => {
try {
return new URL(u).hostname === domain;
} catch {
return false;
}
});
const lang = config.lang || "en";
const excludeLangs = NON_EN_LANG_SEGMENTS.filter((l) => l !== lang);
if (excludeLangs.length > 0) {
filtered = filtered.filter((u) => {
const pathSegments = new URL(u).pathname.split("/").filter(Boolean);
return !pathSegments.some((seg) => excludeLangs.includes(seg.toLowerCase()));
});
}
if (config.excludePaths.length > 0) {
filtered = filtered.filter((u) => {
const pathSegments = new URL(u).pathname.split("/").filter(Boolean);
return !config.excludePaths.some((exclude) => pathSegments.includes(exclude));
});
}
filtered = Array.from(new Set(filtered));
if (config.maxPages) {
filtered = filtered.slice(0, config.maxPages);
}
return filtered;
}
/**
* Is this "full content" actually just an index of links?
*
* Some sites publish an llms.txt-shaped link list AT the llms-full.txt path.
* Measured case: elevenlabs.io/docs/llms-full.txt is 189 KB of
* `- [Title](url): description` lines — 13,433 words, so it sails past a
* word-count gate, but contains no documentation at all. Accepting it produced
* a corpus with 9 headings and zero code blocks that looked like a successful
* run. That is the worst failure shape available here: silent, and committed.
*
* The discriminator is line shape, not size. Real full content is prose and
* code in paragraphs; an index is one link per line.
*/
function looksLikeLinkIndex(text: string): { isIndex: boolean; ratio: number } {
const lines = text.split("\n").map((l) => l.trim()).filter(Boolean);
if (lines.length === 0) return { isIndex: false, ratio: 0 };
const linkLines = lines.filter((l) => /^[-*]\s*\[[^\]]*\]\([^)]*\)/.test(l)).length;
const ratio = linkLines / lines.length;
return { isIndex: ratio > 0.5, ratio };
}
async function probeLlmsFull(url: string): Promise<string | null> {
try {
const res = await timedFetch(url);
if (!res.ok) return null;
const text = await res.text();
if (text.length <= 500 || !looksLikeMarkdown(text)) return null;
// Require substantive content — reject stub landing pages
const h2PlusCount = (text.match(/^#{2,6}\s/gm) || []).length;
const wordCount = text.split(/\s+/).length;
if (h2PlusCount < 3 || wordCount < 1000) {
log(`${url} too thin (${h2PlusCount} headings, ${wordCount} words) — skipping`);
return null;
}
const { isIndex, ratio } = looksLikeLinkIndex(text);
if (isIndex) {
log(`${url} is a link index (${(ratio * 100).toFixed(0)}% link lines), not full content — skipping`);
return null;
}
log(`Found ${url} (${text.length} chars, ${h2PlusCount} headings, ${wordCount} words)`);
return text;
} catch {
return null;
}
}
async function tryLlmsFullTxt(baseUrl: string): Promise<{ fullContent: string } | null> {
log("Trying /llms-full.txt...");
// Probe BOTH the given path and the origin root. Neither alone is right:
// measured, bun.sh publishes at /docs/llms-full.txt (and nothing at the
// root), while hono.dev and vitest.dev publish at the root and 404 under
// their docs path. Probing only path-relative made vitest link-crawl 195
// pages over 213 seconds instead of taking one free GET.
const trimmed = baseUrl.replace(/\/$/, "");
const candidates = [`${trimmed}/llms-full.txt`];
try {
const originCandidate = `${new URL(baseUrl).origin}/llms-full.txt`;
if (!candidates.includes(originCandidate)) candidates.push(originCandidate);
} catch {
// Unparseable base URL — the path-relative candidate is all we have.
}
for (const candidate of candidates) {
const found = await probeLlmsFull(candidate);
if (found) return { fullContent: found };
}
return null;
}
function looksLikeMarkdown(text: string): boolean {
const indicators = [/^#{1,6}\s/m, /\[.*?\]\(.*?\)/, /^[-*]\s/m, /```/, /^\|.*\|/m];
const matches = indicators.filter((r) => r.test(text)).length;
return matches >= 2;
}
async function tryLlmsTxt(baseUrl: string, config: RunConfig): Promise<string[]> {
const url = `${baseUrl.replace(/\/$/, "")}/llms.txt`;
log("Trying /llms.txt...");
try {
const res = await timedFetch(url);
if (!res.ok) return [];
const text = await res.text();
const urls: string[] = [];
for (const line of text.split("\n")) {
const linkMatch = line.match(/^-\s*\[.*?\]\((.*?)\)/);
if (linkMatch) {
urls.push(linkMatch[1]);
continue;
}
const urlMatch = line.match(/https?:\/\/\S+/);
if (urlMatch) {
urls.push(urlMatch[0]);
}
}
const filtered = filterUrls(urls, baseUrl, config);
log(`Found ${filtered.length} URLs from llms.txt`);
return filtered;
} catch {
return [];
}
}
async function trySitemap(baseUrl: string, config: RunConfig): Promise<string[]> {
const base = baseUrl.replace(/\/$/, "");
// `sitemap-index.xml` (hyphen) is not a typo duplicate of `sitemap_index.xml`
// (underscore) — both spellings are in the wild and a site publishing only the
// hyphenated form was invisible to discovery. Measured: docs.astro.build
// 404s on sitemap.xml and sitemap_index.xml, 200s on sitemap-index.xml, which
// made the whole source fail with "no compiled output".
// Probe the origin root as well as the source path. Sitemaps are conventionally
// published at the origin root, so a source given as a subpath — the normal way
// to point at a docs section — never reaches them path-relatively. Measured:
// docs.astro.build/en/ 404s on all three path-relative spellings and 200s on
// docs.astro.build/sitemap-index.xml, so the source discovered zero URLs and
// produced no output at all.
const roots = [base];
try {
const origin = new URL(baseUrl).origin;
if (origin !== base) roots.push(origin);
} catch {
// Non-absolute base; path-relative probing is all that is available.
}
const candidates = roots.flatMap((root) => [
`${root}/sitemap.xml`,
`${root}/sitemap_index.xml`,
`${root}/sitemap-index.xml`,
]);
log("Trying sitemap.xml...");
for (const sitemapUrl of candidates) {
try {
const res = await timedFetch(sitemapUrl);
if (!res.ok) continue;
const xml = await res.text();
const urls = await parseSitemapXml(xml, base, config);
if (urls.length > 0) {
const filtered = filterUrls(urls, baseUrl, config);
log(`Found ${filtered.length} URLs via sitemap`);
return filtered;
}
} catch {
continue;
}
}
return [];
}
async function parseSitemapXml(
xml: string,
_base: string,
_config: RunConfig,
): Promise<string[]> {
const urls: string[] = [];
// Check if this is a sitemap index
if (xml.includes("<sitemapindex")) {
const childLocs = Array.from(xml.matchAll(/<loc>\s*(.*?)\s*<\/loc>/g)).map((m) => m[1]);
for (const childUrl of childLocs) {
try {
const res = await timedFetch(childUrl);
if (!res.ok) continue;
const childXml = await res.text();
const childUrls = Array.from(childXml.matchAll(/<loc>\s*(.*?)\s*<\/loc>/g)).map((m) => m[1]);
urls.push(...childUrls);
} catch {
continue;
}
}
} else {
const locs = Array.from(xml.matchAll(/<loc>\s*(.*?)\s*<\/loc>/g)).map((m) => m[1]);
urls.push(...locs);
}
return urls;
}
/** Depth-1 crawl fan-out cap. Links past it are kept, but never opened for their own links. */
export const LINK_CRAWL_FRONTIER_CAP = 50;
/**
* Split root links into the ones we open for their own links and the ones we
* merely keep. Everything below an unfollowed link is invisible to the run, so
* a non-empty `unfollowed` is what makes a link-crawl result partial.
*/
export function splitFrontier(
filtered: string[],
cap: number = LINK_CRAWL_FRONTIER_CAP,
): { toFollow: string[]; unfollowed: string[] } {
return { toFollow: filtered.slice(0, cap), unfollowed: filtered.slice(cap) };
}
export interface LinkCrawlResult {
urls: string[];
/** Root links retained in `urls` but never opened — their subtrees are undiscovered. */
unfollowed: string[];
}
async function tryLinkCrawl(baseUrl: string, config: RunConfig): Promise<LinkCrawlResult> {
log("Trying link crawl from root...");
try {
const res = await timedFetch(baseUrl);
if (!res.ok) return { urls: [], unfollowed: [] };
const html = await res.text();
const rootLinks = extractLinks(html, baseUrl);
const filtered = filterUrls(rootLinks, baseUrl, config);
// Follow one level deep
const deepLinks: string[] = [...filtered];
const { toFollow, unfollowed } = splitFrontier(filtered);
const results = await Promise.allSettled(
toFollow.map(async (link) => {
try {
const r = await timedFetch(link);
if (!r.ok) return [];
const h = await r.text();
return extractLinks(h, baseUrl);
} catch {
return [];
}
}),
);
for (const result of results) {
if (result.status === "fulfilled") {
deepLinks.push(...result.value);
}
}
const allFiltered = filterUrls(deepLinks, baseUrl, config);
if (unfollowed.length > 0) {
log(
`Found ${allFiltered.length} URLs via link crawl — frontier cap of ${LINK_CRAWL_FRONTIER_CAP} bit: ${unfollowed.length} root links kept but never opened, so their subtrees are undiscovered`,
);
} else {
log(`Found ${allFiltered.length} URLs via link crawl`);
}
return { urls: allFiltered, unfollowed };
} catch {
return { urls: [], unfollowed: [] };
}
}
function extractLinks(html: string, baseUrl: string): string[] {
const hrefs = Array.from(html.matchAll(/<a\s[^>]*href=["']([^"']+)["']/gi)).map((m) => m[1]);
return hrefs
.filter((h) => !h.startsWith("#") && !h.startsWith("mailto:") && !h.startsWith("javascript:"))
.map((h) => {
try {
return new URL(h, baseUrl).href;
} catch {
return null;
}
})
.filter((u): u is string => u !== null);
}
async function tryFirecrawlMap(baseUrl: string, config: RunConfig): Promise<string[]> {
if (!config.firecrawlApiKey) return [];
log("Trying Firecrawl /map...");
try {
const res = await fetch("https://api.firecrawl.dev/v1/map", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${config.firecrawlApiKey}`,
},
body: JSON.stringify({ url: baseUrl }),
signal: AbortSignal.timeout(30_000),
});
if (!res.ok) {
log(`Firecrawl /map returned ${res.status}`);
return [];
}
const data = (await res.json()) as { success?: boolean; links?: string[] };
if (!data.success || !data.links) return [];
const filtered = filterUrls(data.links, baseUrl, config);
log(`Found ${filtered.length} URLs via Firecrawl /map`);
return filtered;
} catch {
return [];
}
}
async function tryFirecrawlSearch(
baseUrl: string,
query: string,
config: RunConfig,
): Promise<string[]> {
if (!config.firecrawlApiKey) return [];
try {
const res = await timedFetch("https://api.firecrawl.dev/v1/search", {
method: "POST",
headers: {
Authorization: `Bearer ${config.firecrawlApiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
query,
limit: config.maxPages ?? 50,
scrapeOptions: { formats: ["markdown"] },
}),
});
if (!res.ok) return [];
const data = (await res.json()) as { success?: boolean; data?: Array<{ url?: string }> };
if (!data.success || !data.data) return [];
const urls = data.data.map((d) => d.url).filter(Boolean) as string[];
const filtered = filterUrls(urls, baseUrl, config);
log(`Found ${filtered.length} URLs via Firecrawl search for "${query}"`);
return filtered;
} catch {
return [];
}
}
const SUFFICIENCY_THRESHOLD = 5;
export async function discover(baseUrl: string, config: RunConfig): Promise<DiscoveryResult> {
// --filter: use Firecrawl search as alternative discovery
if (config.filter) {
if (!config.firecrawlApiKey) {
log("Warning: --filter requires FIRECRAWL_API_KEY. Ignoring filter, using normal discovery.");
} else {
const searchUrls = await tryFirecrawlSearch(baseUrl, config.filter, config);
if (searchUrls.length > 0) {
return {
urls: searchUrls,
method: "firecrawl-map",
metadata: { method: "firecrawl-search", query: config.filter },
};
}
log("Firecrawl search returned no results. Falling back to normal discovery.");
}
}
let stagesAttempted = 0;
// Stage 1: /llms-full.txt
stagesAttempted++;
const fullTxt = await tryLlmsFullTxt(baseUrl);
if (fullTxt) {
// Cross-reference: probe sitemap even though stage 1 won
let sitemapCrossRef: string[] | undefined;
try {
const probed = await trySitemap(baseUrl, config);
if (probed.length > 0) sitemapCrossRef = probed;
} catch { /* fail-open */ }
return {
urls: [],
method: "llms-full-txt",
fullContent: fullTxt.fullContent,
sitemapUrls: sitemapCrossRef,
metadata: { stagesAttempted: String(stagesAttempted), method: "llms-full-txt" },
};
}
// Stage 2: /llms.txt
stagesAttempted++;
const llmsUrls = await tryLlmsTxt(baseUrl, config);
if (llmsUrls.length >= SUFFICIENCY_THRESHOLD) {
// Cross-reference: probe sitemap even though stage 2 won
let sitemapCrossRef: string[] | undefined;
try {
const probed = await trySitemap(baseUrl, config);
if (probed.length > 0) sitemapCrossRef = probed;
} catch { /* fail-open */ }
return {
urls: llmsUrls,
method: "llms-txt",
sitemapUrls: sitemapCrossRef,
metadata: { stagesAttempted: String(stagesAttempted), method: "llms-txt", curated: "true", curatedCount: String(llmsUrls.length) },
};
}
// Stage 3: sitemap.xml
stagesAttempted++;
const sitemapUrls = await trySitemap(baseUrl, config);
if (sitemapUrls.length >= SUFFICIENCY_THRESHOLD) {
// Sitemap was the winning stage — pass its URLs as sitemapUrls too
return {
urls: sitemapUrls,
method: "sitemap",
sitemapUrls: sitemapUrls,
metadata: { stagesAttempted: String(stagesAttempted), method: "sitemap" },
};
}
// Stage 4: link crawl
stagesAttempted++;
const crawl = await tryLinkCrawl(baseUrl, config);
const crawlUrls = crawl.urls;
// The frontier cap is a cap that actually bit. `partial` used to be set only
// on cascade fall-through, so a link crawl that *succeeded* while silently
// abandoning every subtree past link 50 reported itself complete (issue #1).
const frontierCapped = crawl.unfollowed.length > 0;
if (crawlUrls.length >= SUFFICIENCY_THRESHOLD) {
// Cross-reference: sitemap was already probed at stage 3, reuse if non-empty
return {
urls: crawlUrls,
method: "link-crawl",
sitemapUrls: sitemapUrls.length > 0 ? sitemapUrls : undefined,
partial: frontierCapped ? true : undefined,
unfollowedUrls: frontierCapped ? crawl.unfollowed : undefined,
metadata: {
stagesAttempted: String(stagesAttempted),
method: "link-crawl",
...(frontierCapped
? {
partial: "true",
partialReason: "link-crawl-frontier-cap",
frontierCap: String(LINK_CRAWL_FRONTIER_CAP),
unfollowed: String(crawl.unfollowed.length),
}
: {}),
},
};
}
// Stage 5: Firecrawl /map — only if explicitly forced or all free methods fell short
if (config.firecrawlApiKey) {
stagesAttempted++;
const firecrawlUrls = await tryFirecrawlMap(baseUrl, config);
if (firecrawlUrls.length > 0) {
return {
urls: firecrawlUrls,
method: "firecrawl-map",
sitemapUrls: sitemapUrls.length > 0 ? sitemapUrls : undefined,
metadata: { stagesAttempted: String(stagesAttempted), method: "firecrawl-map" },
};
}
}
// Fall through: return best partial result from earlier stages
const bestUrls = crawlUrls.length > 0
? crawlUrls
: sitemapUrls.length > 0
? sitemapUrls
: llmsUrls;
const bestMethod: DiscoveryMethod = crawlUrls.length > 0
? "link-crawl"
: sitemapUrls.length > 0
? "sitemap"
: "llms-txt";
log(`All stages exhausted. Best result: ${bestUrls.length} URLs via ${bestMethod}`);
return {
urls: bestUrls,
method: bestMethod,
partial: true,
sitemapUrls: sitemapUrls.length > 0 ? sitemapUrls : undefined,
unfollowedUrls: frontierCapped && bestMethod === "link-crawl" ? crawl.unfollowed : undefined,
metadata: {
stagesAttempted: String(stagesAttempted),
method: bestMethod,
partial: "true",
partialReason: frontierCapped && bestMethod === "link-crawl"
? "cascade-exhausted+link-crawl-frontier-cap"
: "cascade-exhausted",
},
};
}