@writedocs/generator 0.20.0 → 0.21.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/bin/writedocs.js +23 -7
- package/package.json +1 -1
- package/src/cli/convert.js +120 -15
- package/src/lib/readme-convert.js +437 -0
- package/src/lib/readme-fetch.js +488 -0
- package/src/lib/readme-html.js +263 -0
- package/src/lib/readme-mdx.js +706 -0
- package/src/lib/readme-recipes.js +135 -0
- package/src/pages/[...slug].astro +60 -1
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
// Reads a published ReadMe site (readme.io / a ReadMe custom domain) into
|
|
2
|
+
// one plain JSON "snapshot" - everything `writedocs convert --readme` needs,
|
|
3
|
+
// fetched once, so the conversion itself (lib/readme-convert.js) is a pure
|
|
4
|
+
// function of the snapshot and can be tested without the network.
|
|
5
|
+
//
|
|
6
|
+
// Where each piece comes from - all public, no browser and no ReadMe API key:
|
|
7
|
+
//
|
|
8
|
+
// - Every ReadMe page embeds its data as JSON in
|
|
9
|
+
// <script id="ssr-props" type="application/x-ssr-props">. The home page's
|
|
10
|
+
// holds the project's settings (context.projectStore.data: name, brand
|
|
11
|
+
// colors, logo, favicon, the landing page's HTML, the custom domain,
|
|
12
|
+
// redirects) and both sidebars (guideCategories, referenceCategories).
|
|
13
|
+
// - A guide or reference page's own ssr-props has its raw source
|
|
14
|
+
// (document.content.body - the author's MDX, with `doc:` links, not the
|
|
15
|
+
// rendered page), its excerpt and SEO metadata, and for an endpoint page
|
|
16
|
+
// the operation (document.api.method/path) and the API definition it
|
|
17
|
+
// belongs to (document.api.uri, oasPublicUrl).
|
|
18
|
+
// - A "link" page redirects to its target: its address is the redirect's
|
|
19
|
+
// Location.
|
|
20
|
+
// - Recipes have no ssr document: their list is in llms.txt and their
|
|
21
|
+
// content is the page's `.md` export (code blocks, then one `# Step`
|
|
22
|
+
// heading per step with `<!-- lang@from-to -->` line ranges).
|
|
23
|
+
// - The whole OpenAPI file of an API definition is served by ReadMe's API
|
|
24
|
+
// registry, https://dash.readme.com/api/v1/api-registry/<id>, the id
|
|
25
|
+
// being the part of oasPublicUrl after "#". When that fails, the
|
|
26
|
+
// conversion falls back to merging the one-operation specs every endpoint
|
|
27
|
+
// page embeds.
|
|
28
|
+
//
|
|
29
|
+
// `fetchImpl` is injectable for tests. Only the default version of the
|
|
30
|
+
// project is read.
|
|
31
|
+
|
|
32
|
+
export const SNAPSHOT_VERSION = 1;
|
|
33
|
+
|
|
34
|
+
const SSR_RE = /<script id="ssr-props" type="application\/x-ssr-props">([\s\S]*?)<\/script>/;
|
|
35
|
+
const REGISTRY = 'https://dash.readme.com/api/v1/api-registry/';
|
|
36
|
+
const USER_AGENT = 'Mozilla/5.0 (compatible; writedocs-convert)';
|
|
37
|
+
|
|
38
|
+
/** The JSON a ReadMe page embeds, or null when the HTML has none. */
|
|
39
|
+
export function parseSsrProps(html) {
|
|
40
|
+
const m = SSR_RE.exec(html);
|
|
41
|
+
if (!m) return null;
|
|
42
|
+
try {
|
|
43
|
+
return JSON.parse(m[1]);
|
|
44
|
+
} catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The site's root URL, without a trailing slash: "developer.example.com"
|
|
50
|
+
* and "https://developer.example.com/docs/intro" both give
|
|
51
|
+
* "https://developer.example.com". */
|
|
52
|
+
export function normalizeBaseUrl(input) {
|
|
53
|
+
const raw = String(input ?? '').trim();
|
|
54
|
+
if (!raw) throw new Error('No ReadMe site address given.');
|
|
55
|
+
const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`);
|
|
56
|
+
return url.origin;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The recipes listed in llms.txt: `- [Title](https://site/recipes/slug.md)`. */
|
|
60
|
+
export function recipesFromLlmsTxt(text, baseUrl) {
|
|
61
|
+
return sectionLinksFromLlmsTxt(text, baseUrl, 'recipes');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The pages of one section (`recipes`, `page` - custom pages - or
|
|
65
|
+
* `changelog`) that llms.txt lists, in its order: `[{ slug, title }]`.
|
|
66
|
+
* None of the three has a sidebar to read them from. */
|
|
67
|
+
export function sectionLinksFromLlmsTxt(text, baseUrl, section) {
|
|
68
|
+
const out = [];
|
|
69
|
+
const seen = new Set();
|
|
70
|
+
const re = /\[([^\]]+)\]\((\S+?)\)/g;
|
|
71
|
+
let m;
|
|
72
|
+
while ((m = re.exec(text))) {
|
|
73
|
+
let url;
|
|
74
|
+
try {
|
|
75
|
+
url = new URL(m[2], baseUrl);
|
|
76
|
+
} catch {
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (url.origin !== new URL(baseUrl).origin) continue;
|
|
80
|
+
const parts = url.pathname.replace(/\.md$/, '').split('/').filter(Boolean);
|
|
81
|
+
if (parts.length !== 2 || parts[0] !== section) continue;
|
|
82
|
+
const slug = decodeURIComponent(parts[1]);
|
|
83
|
+
if (seen.has(slug)) continue;
|
|
84
|
+
seen.add(slug);
|
|
85
|
+
out.push({ slug, title: m[1].trim() });
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const SCHEME_SECTIONS = { doc: 'docs', ref: 'reference', recipe: 'recipes', recipes: 'recipes', page: 'page', changelog: 'changelog' };
|
|
91
|
+
const SLUG_END = /[.,;:!]+$/;
|
|
92
|
+
|
|
93
|
+
/** The site's own pages a body links to, as ids ("docs/intro") - by ReadMe
|
|
94
|
+
* scheme (`doc:intro`), by path (`/docs/intro`, `/v4.1/docs/intro`), or by
|
|
95
|
+
* the site's full address - wherever they are: Markdown, HTML, the JSON of
|
|
96
|
+
* an old [block:html]. A path inside another site's URL doesn't count. */
|
|
97
|
+
export function internalLinkTargets(body, baseUrl, { fromRoot = false } = {}) {
|
|
98
|
+
const out = new Set();
|
|
99
|
+
const add = (section, raw) => {
|
|
100
|
+
let slug = String(raw).replace(/\.md$/, '').replace(SLUG_END, '');
|
|
101
|
+
try {
|
|
102
|
+
slug = decodeURIComponent(slug);
|
|
103
|
+
} catch {
|
|
104
|
+
// keep it as written
|
|
105
|
+
}
|
|
106
|
+
if (slug) out.add(`${section}/${slug}`);
|
|
107
|
+
};
|
|
108
|
+
const text = String(body ?? '');
|
|
109
|
+
for (const m of text.matchAll(/(?<![\w-])(doc|ref|recipes?|page|changelog):(?!\/\/)([^\s)"'#?\\<>\]/]+)/g)) add(SCHEME_SECTIONS[m[1]], m[2]);
|
|
110
|
+
const host = new URL(baseUrl).host.replace(/[.]/g, '\\.');
|
|
111
|
+
const re = new RegExp(`(?:https?:\\/\\/${host}|(?<![\\w.:/%-]))(?:\\/v\\d+(?:\\.\\d+)*)?\\/(docs|reference|recipes|page|changelog)\\/([^\\s)"'#?\\\\<>\\]/]+)`, 'g');
|
|
112
|
+
for (const m of text.matchAll(re)) add(m[1], m[2]);
|
|
113
|
+
// On a page at the site's root (the landing page), `href="docs/x"` is
|
|
114
|
+
// /docs/x too.
|
|
115
|
+
if (fromRoot) {
|
|
116
|
+
for (const m of text.matchAll(/\bhref=["'](?:\.\/)?(docs|reference|recipes|page|changelog)\/([^"'#?\s/]+)/g)) add(m[1], m[2]);
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Every page in a ReadMe sidebar (categories > pages > child pages), in order. */
|
|
122
|
+
export function flattenSidebar(categories) {
|
|
123
|
+
const out = [];
|
|
124
|
+
const walk = (pages) => {
|
|
125
|
+
for (const p of pages ?? []) {
|
|
126
|
+
out.push(p);
|
|
127
|
+
walk(p.pages);
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
for (const c of categories ?? []) walk(c.pages);
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The part of a sidebar entry the conversion uses. */
|
|
135
|
+
function sidebarPage(p) {
|
|
136
|
+
return {
|
|
137
|
+
slug: p.slug,
|
|
138
|
+
title: p.title,
|
|
139
|
+
type: p.type,
|
|
140
|
+
hidden: Boolean(p.hidden),
|
|
141
|
+
deprecated: Boolean(p.deprecated),
|
|
142
|
+
isBodyEmpty: Boolean(p.isBodyEmpty),
|
|
143
|
+
method: p.api_method ?? null,
|
|
144
|
+
pages: (p.pages ?? []).map(sidebarPage),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function sidebarCategories(categories) {
|
|
149
|
+
return (categories ?? []).map((c) => ({ title: c.title, pages: (c.pages ?? []).map(sidebarPage) }));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The settings of the project a snapshot keeps, from the home page's ssr-props. */
|
|
153
|
+
export function projectFromSsr(ssr) {
|
|
154
|
+
const d = ssr?.context?.projectStore?.data ?? {};
|
|
155
|
+
const a = d.appearance ?? {};
|
|
156
|
+
const brand = a.brand ?? {};
|
|
157
|
+
const logo = a.logo ?? {};
|
|
158
|
+
const links = a.navigation?.links ?? {};
|
|
159
|
+
const label = (key) => {
|
|
160
|
+
const l = links[key];
|
|
161
|
+
if (!l) return null;
|
|
162
|
+
return { label: l.alias || l.label || null, visible: l.visibility !== 'disabled' };
|
|
163
|
+
};
|
|
164
|
+
return {
|
|
165
|
+
name: d.name ?? ssr?.meta?.title ?? null,
|
|
166
|
+
description: d.description ?? null,
|
|
167
|
+
customDomain: d.custom_domain?.name ?? null,
|
|
168
|
+
colors: {
|
|
169
|
+
primary: brand.primary_color ?? a.colors?.main ?? null,
|
|
170
|
+
primaryDark: brand.primary_color_dark ?? null,
|
|
171
|
+
link: brand.link_color ?? null,
|
|
172
|
+
linkDark: brand.link_color_dark ?? null,
|
|
173
|
+
},
|
|
174
|
+
theme: brand.theme ?? null,
|
|
175
|
+
logo: { light: logo.main?.url ?? null, dark: logo.dark_mode?.url ?? null },
|
|
176
|
+
favicon: logo.favicon?.url ?? null,
|
|
177
|
+
sections: {
|
|
178
|
+
home: label('home'),
|
|
179
|
+
docs: label('guides'),
|
|
180
|
+
reference: label('reference'),
|
|
181
|
+
recipes: label('recipes'),
|
|
182
|
+
changelog: label('changelog'),
|
|
183
|
+
},
|
|
184
|
+
landingPage: (a.landing_page?.sections ?? []).map((s) => ({ type: s.type, title: s.title ?? null, text: s.text ?? null, html: s.html ?? null })),
|
|
185
|
+
customCss: a.custom_code?.css ?? null,
|
|
186
|
+
customJs: a.custom_code?.js ?? null,
|
|
187
|
+
redirects: Array.isArray(d.redirects) ? d.redirects : [],
|
|
188
|
+
// The custom page shown for an address that doesn't exist, by its slug.
|
|
189
|
+
notFoundPage: typeof d.pages?.not_found === 'string' ? d.pages.not_found.split('/').pop() : null,
|
|
190
|
+
glossary: Array.isArray(d.glossary) ? d.glossary.map((g) => ({ term: g.term, definition: g.definition })) : [],
|
|
191
|
+
variables: Array.isArray(d.variable_defaults) ? d.variable_defaults.filter((v) => v.source !== 'security').map((v) => ({ name: v.name, default: v.default ?? '' })) : [],
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The part of a page's ssr document the conversion uses. */
|
|
196
|
+
export function pageFromSsr(ssr) {
|
|
197
|
+
const doc = ssr?.document;
|
|
198
|
+
if (!doc) return null;
|
|
199
|
+
const api = doc.api && doc.api.path ? { method: doc.api.method, path: doc.api.path, uri: doc.api.uri ?? null } : null;
|
|
200
|
+
return {
|
|
201
|
+
slug: doc.slug ?? null,
|
|
202
|
+
title: doc.title,
|
|
203
|
+
type: doc.type,
|
|
204
|
+
body: doc.content?.body ?? '',
|
|
205
|
+
excerpt: doc.content?.excerpt ?? null,
|
|
206
|
+
metaTitle: doc.metadata?.title ?? null,
|
|
207
|
+
metaDescription: doc.metadata?.description ?? null,
|
|
208
|
+
keywords: doc.metadata?.keywords ?? null,
|
|
209
|
+
icon: doc.appearance?.icon?.name ?? null,
|
|
210
|
+
// A custom page's body is Markdown or HTML ("html"); a changelog entry
|
|
211
|
+
// has its date.
|
|
212
|
+
contentType: doc.content?.type ?? null,
|
|
213
|
+
createdAt: doc.created_at ?? null,
|
|
214
|
+
hidden: ssr?.meta?.hidden ?? false,
|
|
215
|
+
robots: ssr?.meta?.robots ?? null,
|
|
216
|
+
link: doc.content?.link?.url ? { url: doc.content.link.url, newTab: Boolean(doc.content.link.new_tab) } : null,
|
|
217
|
+
api,
|
|
218
|
+
// The one-operation spec ReadMe embeds in an endpoint page - the
|
|
219
|
+
// fallback when the registry can't be read.
|
|
220
|
+
embeddedSpec: doc.api?.schema ?? null,
|
|
221
|
+
// ReadMe's reusable content ("custom blocks") the page uses, with their
|
|
222
|
+
// source - `<Duvidas />` in the body is one of these.
|
|
223
|
+
customBlocks: (ssr?.customBlocks ?? [])
|
|
224
|
+
.filter((b) => typeof b?.tag === 'string' && typeof b?.source === 'string')
|
|
225
|
+
.map((b) => ({ tag: b.tag, source: b.source })),
|
|
226
|
+
registryId: typeof ssr?.oasPublicUrl === 'string' && ssr.oasPublicUrl.includes('#') ? ssr.oasPublicUrl.split('#').pop() : null,
|
|
227
|
+
apiDefinitions: (ssr?.apiDefinitions ?? []).map((d) => ({ filename: d.filename, uri: d.uri })),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function mapLimit(items, limit, fn) {
|
|
232
|
+
const out = new Array(items.length);
|
|
233
|
+
let next = 0;
|
|
234
|
+
const worker = async () => {
|
|
235
|
+
while (next < items.length) {
|
|
236
|
+
const i = next++;
|
|
237
|
+
out[i] = await fn(items[i], i);
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
241
|
+
return out;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Reads the site at `baseUrl` into a snapshot.
|
|
248
|
+
*
|
|
249
|
+
* @param {string} baseUrl any address on the site
|
|
250
|
+
* @param {object} [options]
|
|
251
|
+
* @param {typeof fetch} [options.fetchImpl]
|
|
252
|
+
* @param {number} [options.concurrency] pages fetched at once (default 4)
|
|
253
|
+
* @param {(event: {done: number, total: number}) => void} [options.onProgress]
|
|
254
|
+
* @param {number} [options.retryDelay] the first wait after a 429/503, in ms (default 1000)
|
|
255
|
+
*/
|
|
256
|
+
export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, concurrency = 4, onProgress, retryDelay = 1000 } = {}) {
|
|
257
|
+
const base = normalizeBaseUrl(baseUrl);
|
|
258
|
+
const headers = { 'user-agent': USER_AGENT };
|
|
259
|
+
const problems = [];
|
|
260
|
+
|
|
261
|
+
// ReadMe rate-limits (429) a few hundred requests in a row. A 429 or a
|
|
262
|
+
// 503 is waited out - its Retry-After, or 2, 4, ... 64 seconds - and not
|
|
263
|
+
// taken for a missing page. The wait pauses every request, not just the
|
|
264
|
+
// one that got it: workers that kept going would keep the limit from
|
|
265
|
+
// clearing.
|
|
266
|
+
let pausedUntil = 0;
|
|
267
|
+
const get = async (url, { redirect = 'follow' } = {}) => {
|
|
268
|
+
for (let attempt = 0; ; attempt++) {
|
|
269
|
+
while (Date.now() < pausedUntil) await sleep(pausedUntil - Date.now());
|
|
270
|
+
const res = await fetchImpl(url, { headers, redirect });
|
|
271
|
+
if ((res.status !== 429 && res.status !== 503) || attempt >= 6) return res;
|
|
272
|
+
const after = Number(res.headers?.get?.('retry-after'));
|
|
273
|
+
const wait = Number.isFinite(after) && after > 0 ? Math.min(after, 120) * 1000 : retryDelay * 2 ** (attempt + 1);
|
|
274
|
+
pausedUntil = Math.max(pausedUntil, Date.now() + wait);
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
const getText = async (url) => {
|
|
278
|
+
const res = await get(url);
|
|
279
|
+
if (!res.ok) throw new Error(`${url} answered ${res.status}`);
|
|
280
|
+
return res.text();
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
// The home page: the project, and on some sites both sidebars.
|
|
284
|
+
const homeHtml = await getText(`${base}/`);
|
|
285
|
+
const home = parseSsrProps(homeHtml);
|
|
286
|
+
if (!home?.context?.projectStore?.data) {
|
|
287
|
+
throw new Error(`${base} doesn't look like a ReadMe site - its home page has no ReadMe page data.`);
|
|
288
|
+
}
|
|
289
|
+
const project = projectFromSsr(home);
|
|
290
|
+
// Where the home page doesn't carry a section's sidebar, the section's
|
|
291
|
+
// own address (/docs, /reference - ReadMe opens its first page) does, as
|
|
292
|
+
// `sidebar`. A section that's switched off, or answers with no sidebar,
|
|
293
|
+
// is empty.
|
|
294
|
+
const sectionSidebar = async (section, fromHome) => {
|
|
295
|
+
if (Array.isArray(fromHome)) return sidebarCategories(fromHome);
|
|
296
|
+
try {
|
|
297
|
+
const res = await get(`${base}/${section}`);
|
|
298
|
+
if (!res.ok) return [];
|
|
299
|
+
const ssr = parseSsrProps(await res.text());
|
|
300
|
+
return sidebarCategories(Array.isArray(ssr?.sidebar) ? ssr.sidebar : []);
|
|
301
|
+
} catch (err) {
|
|
302
|
+
problems.push({ where: section, message: `Couldn't read the ${section} sidebar: ${err.message}` });
|
|
303
|
+
return [];
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
const sidebars = {
|
|
307
|
+
docs: project.sections.docs?.visible === false ? [] : await sectionSidebar('docs', home.guideCategories),
|
|
308
|
+
reference: project.sections.reference?.visible === false ? [] : await sectionSidebar('reference', home.referenceCategories),
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
// Every guide and reference page, from its own ssr-props.
|
|
312
|
+
const jobs = [];
|
|
313
|
+
for (const section of ['docs', 'reference']) {
|
|
314
|
+
for (const p of flattenSidebar(sidebars[section])) jobs.push({ section, slug: p.slug, type: p.type });
|
|
315
|
+
}
|
|
316
|
+
const recipesIndex = [];
|
|
317
|
+
const customPages = [];
|
|
318
|
+
const changelog = [];
|
|
319
|
+
let llmsTxt = null;
|
|
320
|
+
try {
|
|
321
|
+
llmsTxt = await getText(`${base}/llms.txt`);
|
|
322
|
+
if (project.sections.recipes?.visible !== false) recipesIndex.push(...recipesFromLlmsTxt(llmsTxt, base));
|
|
323
|
+
// Custom pages (/page/...) and changelog entries are read like guides,
|
|
324
|
+
// from their own ssr-props; llms.txt is what lists them.
|
|
325
|
+
customPages.push(...sectionLinksFromLlmsTxt(llmsTxt, base, 'page'));
|
|
326
|
+
if (project.sections.changelog?.visible !== false) changelog.push(...sectionLinksFromLlmsTxt(llmsTxt, base, 'changelog'));
|
|
327
|
+
} catch (err) {
|
|
328
|
+
problems.push({ where: 'llms.txt', message: `Couldn't read llms.txt (${err.message}), so no recipes, custom pages or changelog entries were found.` });
|
|
329
|
+
}
|
|
330
|
+
for (const p of customPages) jobs.push({ section: 'page', slug: p.slug, type: 'basic' });
|
|
331
|
+
for (const p of changelog) jobs.push({ section: 'changelog', slug: p.slug, type: 'basic' });
|
|
332
|
+
if (!jobs.length && !recipesIndex.length) {
|
|
333
|
+
throw new Error(`no pages found on ${base} - neither its home page nor /docs and /reference list any.`);
|
|
334
|
+
}
|
|
335
|
+
const total = jobs.length + recipesIndex.length;
|
|
336
|
+
let done = 0;
|
|
337
|
+
const tick = () => onProgress?.({ done: ++done, total });
|
|
338
|
+
|
|
339
|
+
const pages = {};
|
|
340
|
+
await mapLimit(jobs, concurrency, async ({ section, slug, type }) => {
|
|
341
|
+
const id = `${section}/${slug}`;
|
|
342
|
+
const url = `${base}/${section}/${encodeURIComponent(slug)}`;
|
|
343
|
+
try {
|
|
344
|
+
if (type === 'link') {
|
|
345
|
+
// A link page answers with a redirect to its target.
|
|
346
|
+
const res = await get(url, { redirect: 'manual' });
|
|
347
|
+
const location = res.headers.get('location');
|
|
348
|
+
if (location && new URL(location, base).origin !== base) {
|
|
349
|
+
pages[id] = { title: null, type: 'link', body: '', link: { url: new URL(location, base).href, newTab: true } };
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
const html = await getText(url);
|
|
354
|
+
const page = pageFromSsr(parseSsrProps(html));
|
|
355
|
+
if (!page) throw new Error('the page has no ReadMe page data');
|
|
356
|
+
// A page with no content of its own - an API tag's page above its
|
|
357
|
+
// endpoints - answers with a redirect to its first child, whose page
|
|
358
|
+
// data then comes back. Keep only where it leads.
|
|
359
|
+
if (page.slug && page.slug.normalize() !== slug.normalize()) {
|
|
360
|
+
pages[id] = { slug, title: null, type: 'basic', body: '', redirectsTo: `${section}/${page.slug}` };
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
pages[id] = page;
|
|
364
|
+
} catch (err) {
|
|
365
|
+
problems.push({ where: id, message: `Couldn't read ${url}: ${err.message}` });
|
|
366
|
+
} finally {
|
|
367
|
+
tick();
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
const recipes = [];
|
|
372
|
+
await mapLimit(recipesIndex, concurrency, async (r) => {
|
|
373
|
+
const url = `${base}/recipes/${encodeURIComponent(r.slug)}.md`;
|
|
374
|
+
try {
|
|
375
|
+
recipes.push({ ...r, markdown: await getText(url) });
|
|
376
|
+
} catch (err) {
|
|
377
|
+
problems.push({ where: `recipes/${r.slug}`, message: `Couldn't read ${url}: ${err.message}` });
|
|
378
|
+
} finally {
|
|
379
|
+
tick();
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
// Back in llms.txt's order - mapLimit finishes them in any order.
|
|
383
|
+
recipes.sort((a, b) => recipesIndex.findIndex((r) => r.slug === a.slug) - recipesIndex.findIndex((r) => r.slug === b.slug));
|
|
384
|
+
|
|
385
|
+
// Pages the sidebars don't list, found by following links. A hidden page
|
|
386
|
+
// isn't in the sidebar data ReadMe gives a visitor, but its address works
|
|
387
|
+
// - and pages link to it. A renamed page's old address redirects to the
|
|
388
|
+
// new one. Each round follows the links of the pages the last one found.
|
|
389
|
+
const discovered = []; // { id, title, type } - kept as hidden pages
|
|
390
|
+
const linkRedirects = []; // { source, destination } - ReadMe's own redirects
|
|
391
|
+
const tried = new Set();
|
|
392
|
+
const known = () => new Set([...Object.keys(pages), ...recipes.map((r) => `recipes/${r.slug}`)]);
|
|
393
|
+
const linksOf = (page) => [page.body, ...(page.customBlocks ?? []).map((b) => b.source)].join('\n');
|
|
394
|
+
for (let round = 0; round < 5; round++) {
|
|
395
|
+
const have = known();
|
|
396
|
+
const frontier = new Set();
|
|
397
|
+
// The pages, and the landing page's HTML - often the only link to a page.
|
|
398
|
+
const sources = [
|
|
399
|
+
...Object.values(pages).map((page) => [linksOf(page), false]),
|
|
400
|
+
...project.landingPage.map((s) => [[s.html, s.text].filter(Boolean).join('\n'), true]),
|
|
401
|
+
];
|
|
402
|
+
for (const [source, fromRoot] of sources) {
|
|
403
|
+
for (const id of internalLinkTargets(source, base, { fromRoot })) if (!have.has(id) && !tried.has(id) && !id.startsWith('recipes/')) frontier.add(id);
|
|
404
|
+
}
|
|
405
|
+
if (!frontier.size) break;
|
|
406
|
+
await mapLimit([...frontier], concurrency, async (id) => {
|
|
407
|
+
tried.add(id);
|
|
408
|
+
const [section, ...rest] = id.split('/');
|
|
409
|
+
const url = `${base}/${section}/${encodeURIComponent(rest.join('/'))}`;
|
|
410
|
+
try {
|
|
411
|
+
const res = await get(url);
|
|
412
|
+
if (res.status === 429 || res.status === 503) {
|
|
413
|
+
problems.push({ where: id, message: `${url} kept answering ${res.status} (too many requests), so a page there may be missing - convert again later.` });
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
if (!res.ok) return; // broken on ReadMe too - broken-links lists it
|
|
417
|
+
let finalId = id;
|
|
418
|
+
if (res.url) {
|
|
419
|
+
const final = new URL(res.url);
|
|
420
|
+
if (final.origin !== base) {
|
|
421
|
+
linkRedirects.push({ source: `/${id}`, destination: final.href });
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
const parts = decodeURIComponent(final.pathname).replace(/^\/v\d+(?:\.\d+)*(?=\/)/, '').split('/').filter(Boolean);
|
|
425
|
+
if (parts.length === 2) finalId = parts.join('/');
|
|
426
|
+
}
|
|
427
|
+
const page = pageFromSsr(parseSsrProps(await res.text()));
|
|
428
|
+
if (!page) return;
|
|
429
|
+
if (page.slug && finalId === id && page.slug.normalize() !== rest.join('/').normalize()) finalId = `${section}/${page.slug}`;
|
|
430
|
+
if (finalId.normalize() !== id.normalize()) {
|
|
431
|
+
linkRedirects.push({ source: `/${id}`, destination: `/${finalId}` });
|
|
432
|
+
if (known().has(finalId)) return;
|
|
433
|
+
}
|
|
434
|
+
pages[finalId] = { ...page, hidden: true };
|
|
435
|
+
discovered.push({ id: finalId, title: page.title, type: page.api ? 'endpoint' : 'basic' });
|
|
436
|
+
} catch {
|
|
437
|
+
// unreachable - left for broken-links to report
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// The API definitions: one OpenAPI file each, from the registry.
|
|
443
|
+
const definitions = new Map(); // uri -> { filename, registryId }
|
|
444
|
+
for (const page of Object.values(pages)) {
|
|
445
|
+
if (!page.api?.uri) continue;
|
|
446
|
+
if (!definitions.has(page.api.uri)) {
|
|
447
|
+
const def = page.apiDefinitions?.find((d) => d.uri === page.api.uri);
|
|
448
|
+
const filename = def?.filename ?? page.api.uri.split('/').pop();
|
|
449
|
+
definitions.set(page.api.uri, { filename, registryId: page.registryId });
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
const openapi = [];
|
|
453
|
+
for (const [uri, def] of definitions) {
|
|
454
|
+
let spec = null;
|
|
455
|
+
if (def.registryId) {
|
|
456
|
+
try {
|
|
457
|
+
const res = await get(`${REGISTRY}${encodeURIComponent(def.registryId)}`);
|
|
458
|
+
if (res.ok) spec = await res.json();
|
|
459
|
+
} catch {
|
|
460
|
+
spec = null;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (!spec?.paths) {
|
|
464
|
+
problems.push({
|
|
465
|
+
where: def.filename,
|
|
466
|
+
message: `Couldn't download ${def.filename} from ReadMe's API registry - it's rebuilt from the operations the endpoint pages show, so operations without a page are missing.`,
|
|
467
|
+
});
|
|
468
|
+
spec = null;
|
|
469
|
+
}
|
|
470
|
+
openapi.push({ uri, filename: def.filename, spec });
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
return {
|
|
474
|
+
version: SNAPSHOT_VERSION,
|
|
475
|
+
baseUrl: base,
|
|
476
|
+
fetchedAt: new Date().toISOString(),
|
|
477
|
+
project,
|
|
478
|
+
sidebars,
|
|
479
|
+
pages,
|
|
480
|
+
recipes,
|
|
481
|
+
customPages,
|
|
482
|
+
changelog,
|
|
483
|
+
discovered,
|
|
484
|
+
linkRedirects,
|
|
485
|
+
openapi,
|
|
486
|
+
problems,
|
|
487
|
+
};
|
|
488
|
+
}
|