@writedocs/generator 0.19.0 → 0.21.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.
@@ -0,0 +1,325 @@
1
+ // Turns a ReadMe site, read by lib/readme-fetch.js into a snapshot, into a
2
+ // writedocs project: the pages, the OpenAPI files, writedocs.json, and the
3
+ // images to download - `writedocs convert --readme <site>`
4
+ // (src/cli/convert.js). A pure function of the snapshot: nothing here
5
+ // touches the network or the disk.
6
+ //
7
+ // The project keeps ReadMe's addresses, so links and search results that
8
+ // point at the old site keep working on the new one:
9
+ //
10
+ // /docs/<slug> guides -> docs/<slug>.mdx
11
+ // /reference/<slug> reference -> reference/<slug>.mdx
12
+ // /recipes/<slug> recipes -> recipes/<slug>.mdx
13
+ // / landing page -> index.mdx (mode: custom)
14
+ //
15
+ // Navigation: each ReadMe section (Guides, API Reference, Recipes) is a
16
+ // tab, named as the site names it; each sidebar category is a group; a page
17
+ // with child pages is a group whose label opens that page (or a plain group
18
+ // when the page is empty - ReadMe's API tag pages). A "link" page is an
19
+ // external link in the sidebar. Hidden pages stay in the navigation with
20
+ // `hidden: true`, which keeps them out of the sidebar but builds them.
21
+ //
22
+ // API reference: an endpoint page is a page with `openapi: "<file> METHOD
23
+ // /path"` frontmatter, so it keeps its own address, title and place in the
24
+ // sidebar. The OpenAPI file is ReadMe's API definition, written to
25
+ // openapi/<its file name>.
26
+
27
+ import { convertReadmeBody, makeLinkRewriter, wrapHtml, README_HTML_CLASS, README_HTML_CSS } from './readme-mdx.js';
28
+ import { convertRecipe } from './readme-recipes.js';
29
+ import { htmlToMdx } from './readme-html.js';
30
+ import { Notes } from './mintlify-convert.js';
31
+ import { parseHex, contrastRatio } from './color.js';
32
+
33
+ // writedocs' dark background when `styles.background` doesn't set one.
34
+ const DARK_BACKGROUND = '#0b1120';
35
+
36
+ /** A version of `hex` readable as link text on the dark background - mixed
37
+ * toward white until it has 4.5:1 contrast - or null when `hex` already
38
+ * does (or isn't a hex color). ReadMe sites are often light-only, with a
39
+ * dark brand color no one ever saw on a dark page. */
40
+ export function darkModePrimary(hex) {
41
+ const rgb = parseHex(hex);
42
+ if (!rgb || (contrastRatio(hex, DARK_BACKGROUND) ?? 0) >= 4.5) return null;
43
+ const toHex = (c) => `#${c.map((v) => Math.round(v).toString(16).padStart(2, '0')).join('')}`;
44
+ const [r, g, b] = Array.isArray(rgb) ? rgb : [rgb.r, rgb.g, rgb.b];
45
+ for (let t = 0.05; t <= 1; t += 0.05) {
46
+ const mixed = toHex([r, g, b].map((v) => v + (255 - v) * t));
47
+ if (contrastRatio(mixed, DARK_BACKGROUND) >= 4.5) return mixed;
48
+ }
49
+ return '#ffffff';
50
+ }
51
+
52
+ const README_FILES = /(^|\.)readme\.io$/i;
53
+
54
+ /** YAML frontmatter from an object; strings JSON-quoted (valid YAML). */
55
+ export function frontmatter(fields) {
56
+ const lines = ['---'];
57
+ for (const [key, value] of Object.entries(fields)) {
58
+ if (value === undefined || value === null || value === false || value === '') continue;
59
+ lines.push(`${key}: ${typeof value === 'string' ? JSON.stringify(value) : JSON.stringify(value)}`);
60
+ }
61
+ lines.push('---');
62
+ return lines.join('\n');
63
+ }
64
+
65
+ /** A file name for a downloaded image: the URL's path, made safe. */
66
+ export function imageFileName(url) {
67
+ const u = new URL(url);
68
+ let name = u.pathname
69
+ .split('/')
70
+ .filter(Boolean)
71
+ .map((part) => {
72
+ try {
73
+ return decodeURIComponent(part);
74
+ } catch {
75
+ return part;
76
+ }
77
+ })
78
+ .join('-');
79
+ name = name.replace(/[^\w.-]+/g, '-').replace(/-{2,}/g, '-').replace(/^[-.]+/, '');
80
+ return name || 'image';
81
+ }
82
+
83
+ /** Rebuilds an OpenAPI file from the one-operation specs endpoint pages
84
+ * embed - when the registry couldn't be read. */
85
+ export function mergeEmbeddedSpecs(specs) {
86
+ let merged = null;
87
+ for (const spec of specs) {
88
+ if (!spec?.paths) continue;
89
+ if (!merged) {
90
+ merged = { ...spec, paths: {}, components: { ...(spec.components ?? {}) } };
91
+ for (const k of Object.keys(merged.components)) merged.components[k] = { ...merged.components[k] };
92
+ }
93
+ for (const [p, ops] of Object.entries(spec.paths)) merged.paths[p] = { ...(merged.paths[p] ?? {}), ...ops };
94
+ for (const [k, group] of Object.entries(spec.components ?? {})) {
95
+ merged.components[k] = { ...(merged.components[k] ?? {}), ...group };
96
+ }
97
+ }
98
+ return merged;
99
+ }
100
+
101
+ function operation(spec, method, path) {
102
+ return spec?.paths?.[path]?.[String(method).toLowerCase()] ?? null;
103
+ }
104
+
105
+ /**
106
+ * @param {object} snapshot from fetchReadmeSite()
107
+ * @returns {{
108
+ * config: object,
109
+ * files: { path: string, content: string }[],
110
+ * assets: { url: string, path: string }[],
111
+ * notes: ReturnType<Notes['list']>,
112
+ * counts: { pages: number, endpoints: number, recipes: number, images: number },
113
+ * }}
114
+ */
115
+ export function convertReadmeSnapshot(snapshot) {
116
+ const notes = new Notes();
117
+ const files = [];
118
+ const assets = new Map(); // url -> path
119
+ const project = snapshot.project ?? {};
120
+ const counts = { pages: 0, endpoints: 0, recipes: 0, images: 0 };
121
+
122
+ const rewriteLink = makeLinkRewriter({ baseUrl: snapshot.baseUrl, subdomain: project.subdomain });
123
+ const localImage = (url) => {
124
+ let u;
125
+ try {
126
+ u = new URL(url);
127
+ } catch {
128
+ return url;
129
+ }
130
+ if (!README_FILES.test(u.hostname)) return rewriteLink(url);
131
+ if (!assets.has(u.href)) {
132
+ let path = `images/${imageFileName(u.href)}`;
133
+ const taken = new Set(assets.values());
134
+ for (let n = 2; taken.has(path); n++) path = path.replace(/(\.[^.]+)?$/, (ext) => `-${n}${ext}`);
135
+ assets.set(u.href, path);
136
+ }
137
+ return `/${assets.get(u.href)}`;
138
+ };
139
+ const glossary = new Map((project.glossary ?? []).map((g) => [String(g.term).toLowerCase(), g.definition]));
140
+ const recipeSlugs = new Set((snapshot.recipes ?? []).map((r) => r.slug));
141
+ const ctxFor = (where) => ({
142
+ rewriteLink: (url) => rewriteLink(url, where),
143
+ localImage,
144
+ glossary,
145
+ recipes: recipeSlugs,
146
+ note: (key, message) => notes.add(key, [where], message),
147
+ });
148
+
149
+ // The OpenAPI files, by ReadMe's definition uri.
150
+ const specs = new Map();
151
+ for (const def of snapshot.openapi ?? []) {
152
+ let spec = def.spec;
153
+ if (!spec) {
154
+ spec = mergeEmbeddedSpecs(Object.values(snapshot.pages ?? {}).filter((p) => p.api?.uri === def.uri).map((p) => p.embeddedSpec));
155
+ }
156
+ if (!spec) continue;
157
+ const path = `openapi/${def.filename.replace(/[^\w.-]+/g, '-')}`;
158
+ specs.set(def.uri, { path, spec });
159
+ files.push({ path, content: `${JSON.stringify(spec, null, 2)}\n` });
160
+ }
161
+
162
+ const writePage = (id, fields, body) => {
163
+ files.push({ path: `${id}.mdx`, content: `${frontmatter(fields)}\n${body ? `\n${body}\n` : ''}` });
164
+ counts.pages++;
165
+ };
166
+
167
+ const pageRedirects = [];
168
+
169
+ // One sidebar entry -> a navigation item (and its page file).
170
+ const navItem = (section, entry) => {
171
+ const id = `${section}/${entry.slug}`;
172
+ const page = snapshot.pages?.[id];
173
+ const children = (entry.pages ?? []).map((child) => navItem(section, child)).filter(Boolean);
174
+ if (!page) {
175
+ notes.add('unreadable-page', [id], "This page couldn't be read from the site, so it's not in the project.");
176
+ return children.length ? { group: entry.title, pages: children } : null;
177
+ }
178
+ if (page.redirectsTo) {
179
+ // No content of its own (an API tag's page): a plain group, and its
180
+ // old address goes where ReadMe sent it.
181
+ pageRedirects.push({ source: `/${id}`, destination: `/${page.redirectsTo}` });
182
+ return children.length ? { group: entry.title, pages: children } : null;
183
+ }
184
+ if (entry.type === 'link' || page.type === 'link') {
185
+ if (!page.link?.url) {
186
+ notes.add('link-without-url', [id], 'A sidebar link with no address - left out.');
187
+ return null;
188
+ }
189
+ return { label: entry.title, href: rewriteLink(page.link.url) };
190
+ }
191
+
192
+ const fields = { title: page.title ?? entry.title };
193
+ let body = page.body?.trim() ? convertReadmeBody(page.body, ctxFor(id)) : '';
194
+ if (page.api && entry.type === 'endpoint') {
195
+ const spec = specs.get(page.api.uri);
196
+ const op = spec && operation(spec.spec, page.api.method, page.api.path);
197
+ if (!op) {
198
+ notes.add('missing-operation', [id], `${page.api.method.toUpperCase()} ${page.api.path} isn't in the API definition - the page shows only its text.`);
199
+ } else {
200
+ fields.openapi = `${spec.path} ${page.api.method.toUpperCase()} ${page.api.path}`;
201
+ counts.endpoints++;
202
+ }
203
+ // The operation's description is shown on the page already.
204
+ const excerpt = page.excerpt?.trim();
205
+ if (excerpt && excerpt !== op?.description?.trim() && excerpt !== op?.summary?.trim()) fields.description = excerpt;
206
+ } else {
207
+ const description = page.excerpt?.trim() || page.metaDescription?.trim();
208
+ if (description) fields.description = description;
209
+ }
210
+ if (page.hidden || entry.hidden) fields.hidden = true;
211
+ if (entry.deprecated) fields.deprecated = true;
212
+ if (page.robots && /noindex/i.test(page.robots)) fields.noindex = true;
213
+ if (page.metaTitle && page.metaTitle !== fields.title) {
214
+ notes.add('meta-title', [id], `The SEO title "${page.metaTitle}" isn't carried over - the page's <title> is its title.`);
215
+ }
216
+
217
+ // An empty page with children is a heading in ReadMe's sidebar (an API
218
+ // tag's page): a plain group here.
219
+ const empty = !body && !fields.openapi && !fields.description;
220
+ if (children.length && empty && entry.isBodyEmpty !== false) return { group: fields.title, pages: children };
221
+ writePage(id, fields, body);
222
+ return children.length ? { group: fields.title, page: id, pages: children } : id;
223
+ };
224
+
225
+ const sectionNav = (section) => {
226
+ const out = [];
227
+ for (const category of snapshot.sidebars?.[section] ?? []) {
228
+ const pages = category.pages.map((entry) => navItem(section, entry)).filter(Boolean);
229
+ if (pages.length) out.push({ group: category.title, pages });
230
+ }
231
+ return out;
232
+ };
233
+
234
+ const tabs = [];
235
+ const label = (key, fallback) => project.sections?.[key]?.label || fallback;
236
+ const docsNav = sectionNav('docs');
237
+ if (docsNav.length) tabs.push({ tab: label('docs', 'Guides'), pages: docsNav });
238
+ const recipesNav = [];
239
+ for (const recipe of snapshot.recipes ?? []) {
240
+ const id = `recipes/${recipe.slug}`;
241
+ const { title, body } = convertRecipe(recipe.markdown, ctxFor(id));
242
+ writePage(id, { title: title ?? recipe.title }, body);
243
+ counts.recipes++;
244
+ recipesNav.push(id);
245
+ }
246
+ if (recipesNav.length) tabs.push({ tab: label('recipes', 'Recipes'), pages: recipesNav });
247
+ const referenceNav = sectionNav('reference');
248
+ if (referenceNav.length) tabs.push({ tab: label('reference', 'API Reference'), pages: referenceNav });
249
+
250
+ // The landing page.
251
+ const landing = (project.landingPage ?? []).filter((s) => s.html || s.title || s.text);
252
+ if (landing.length) {
253
+ const parts = [];
254
+ for (const section of landing) {
255
+ if (section.type === 'html' && section.html) {
256
+ parts.push(wrapHtml(htmlToMdx(section.html, { rewriteUrl: (url, name) => (name === 'src' ? localImage(url) : rewriteLink(url, 'index')) })));
257
+ } else {
258
+ if (section.title) parts.push(`## ${section.title}`);
259
+ if (section.text) parts.push(convertReadmeBody(section.text, ctxFor('index')));
260
+ notes.add('landing-section', ['index'], `A "${section.type}" section of the landing page was carried over as its title and text only - lay it out again with components.`);
261
+ }
262
+ }
263
+ writePage('index', { title: project.name ?? 'Home', mode: 'custom' }, parts.join('\n\n'));
264
+ }
265
+
266
+ if (files.some((f) => f.path.endsWith('.mdx') && f.content.includes(`className="${README_HTML_CLASS}"`))) {
267
+ files.push({ path: 'readme-html.css', content: README_HTML_CSS });
268
+ }
269
+
270
+ if (project.sections?.changelog?.visible) {
271
+ notes.add('changelog', ['changelog'], "The site's changelog isn't converted - add its entries as pages (the Update component suits them).");
272
+ }
273
+ if (project.customCss) notes.add('custom-css', ['appearance'], 'The project has custom CSS - not carried over; ReadMe class names mostly have no equivalent. See "Custom CSS and scripts".');
274
+ if (project.customJs) notes.add('custom-js', ['appearance'], 'The project has custom JavaScript - not carried over.');
275
+
276
+ // writedocs.json.
277
+ const config = { name: project.name || new URL(snapshot.baseUrl).hostname };
278
+ if (project.description) config.description = project.description;
279
+ if (project.customDomain) config.domain = project.customDomain;
280
+ const styles = {};
281
+ if (project.colors?.primary) {
282
+ styles.colors = { primary: project.colors.primary };
283
+ const dark = project.colors.primaryDark || darkModePrimary(project.colors.primary);
284
+ if (dark) styles.colors.dark = { primary: dark };
285
+ if (dark && !project.colors.primaryDark) {
286
+ notes.add('dark-primary', ['styles.colors.dark.primary'], `The brand color ${project.colors.primary} is too dark to read on a dark page, and ReadMe had no dark-mode color - set to ${dark}, a lighter version of it. Change it if the brand has its own.`);
287
+ }
288
+ }
289
+ const logoLight = project.logo?.light ? localImage(project.logo.light) : null;
290
+ const logoDark = project.logo?.dark ? localImage(project.logo.dark) : null;
291
+ if (logoLight && logoDark && logoLight !== logoDark) styles.logo = { light: logoLight, dark: logoDark };
292
+ else if (logoLight || logoDark) styles.logo = logoLight || logoDark;
293
+ if (project.favicon) styles.favicon = localImage(project.favicon);
294
+ if (project.theme === 'light' || project.theme === 'dark') styles.appearance = { default: project.theme };
295
+ if (Object.keys(styles).length) config.styles = styles;
296
+ // index.mdx is the home page whether or not the navigation lists it.
297
+ config.navigation = tabs.length > 1 ? { tabs } : tabs[0]?.pages ?? [];
298
+
299
+ const redirects = [...pageRedirects];
300
+ for (const r of project.redirects ?? []) {
301
+ const source = r.source ?? r.from;
302
+ const destination = r.destination ?? r.to;
303
+ if (typeof source !== 'string' || typeof destination !== 'string') continue;
304
+ if (/[*:]/.test(source)) {
305
+ notes.add('pattern-redirect', ['redirects'], `The redirect from ${source} uses a pattern - writedocs redirects match one exact path, so it's left out.`);
306
+ continue;
307
+ }
308
+ redirects.push({ source: rewriteLink(source), destination: rewriteLink(destination) });
309
+ }
310
+ if (redirects.length) config.redirects = redirects;
311
+ if (project.variables?.length) {
312
+ config.variables = Object.fromEntries(project.variables.map((v) => [v.name, String(v.default ?? v.name)]));
313
+ }
314
+
315
+ for (const problem of snapshot.problems ?? []) notes.add(`fetch:${problem.message}`, [problem.where], problem.message);
316
+
317
+ counts.images = assets.size;
318
+ return {
319
+ config,
320
+ files,
321
+ assets: [...assets].map(([url, path]) => ({ url, path })),
322
+ notes: notes.list(),
323
+ counts,
324
+ };
325
+ }
@@ -0,0 +1,336 @@
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
+ const out = [];
62
+ const seen = new Set();
63
+ const re = /\[([^\]]+)\]\((\S+?)\)/g;
64
+ let m;
65
+ while ((m = re.exec(text))) {
66
+ let url;
67
+ try {
68
+ url = new URL(m[2], baseUrl);
69
+ } catch {
70
+ continue;
71
+ }
72
+ if (url.origin !== new URL(baseUrl).origin) continue;
73
+ const parts = url.pathname.replace(/\.md$/, '').split('/').filter(Boolean);
74
+ if (parts.length !== 2 || parts[0] !== 'recipes') continue;
75
+ const slug = decodeURIComponent(parts[1]);
76
+ if (seen.has(slug)) continue;
77
+ seen.add(slug);
78
+ out.push({ slug, title: m[1].trim() });
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /** Every page in a ReadMe sidebar (categories > pages > child pages), in order. */
84
+ export function flattenSidebar(categories) {
85
+ const out = [];
86
+ const walk = (pages) => {
87
+ for (const p of pages ?? []) {
88
+ out.push(p);
89
+ walk(p.pages);
90
+ }
91
+ };
92
+ for (const c of categories ?? []) walk(c.pages);
93
+ return out;
94
+ }
95
+
96
+ /** The part of a sidebar entry the conversion uses. */
97
+ function sidebarPage(p) {
98
+ return {
99
+ slug: p.slug,
100
+ title: p.title,
101
+ type: p.type,
102
+ hidden: Boolean(p.hidden),
103
+ deprecated: Boolean(p.deprecated),
104
+ isBodyEmpty: Boolean(p.isBodyEmpty),
105
+ method: p.api_method ?? null,
106
+ pages: (p.pages ?? []).map(sidebarPage),
107
+ };
108
+ }
109
+
110
+ function sidebarCategories(categories) {
111
+ return (categories ?? []).map((c) => ({ title: c.title, pages: (c.pages ?? []).map(sidebarPage) }));
112
+ }
113
+
114
+ /** The settings of the project a snapshot keeps, from the home page's ssr-props. */
115
+ export function projectFromSsr(ssr) {
116
+ const d = ssr?.context?.projectStore?.data ?? {};
117
+ const a = d.appearance ?? {};
118
+ const brand = a.brand ?? {};
119
+ const logo = a.logo ?? {};
120
+ const links = a.navigation?.links ?? {};
121
+ const label = (key) => {
122
+ const l = links[key];
123
+ if (!l) return null;
124
+ return { label: l.alias || l.label || null, visible: l.visibility !== 'disabled' };
125
+ };
126
+ return {
127
+ name: d.name ?? ssr?.meta?.title ?? null,
128
+ description: d.description ?? null,
129
+ customDomain: d.custom_domain?.name ?? null,
130
+ colors: {
131
+ primary: brand.primary_color ?? a.colors?.main ?? null,
132
+ primaryDark: brand.primary_color_dark ?? null,
133
+ link: brand.link_color ?? null,
134
+ linkDark: brand.link_color_dark ?? null,
135
+ },
136
+ theme: brand.theme ?? null,
137
+ logo: { light: logo.main?.url ?? null, dark: logo.dark_mode?.url ?? null },
138
+ favicon: logo.favicon?.url ?? null,
139
+ sections: {
140
+ home: label('home'),
141
+ docs: label('guides'),
142
+ reference: label('reference'),
143
+ recipes: label('recipes'),
144
+ changelog: label('changelog'),
145
+ },
146
+ landingPage: (a.landing_page?.sections ?? []).map((s) => ({ type: s.type, title: s.title ?? null, text: s.text ?? null, html: s.html ?? null })),
147
+ customCss: a.custom_code?.css ?? null,
148
+ customJs: a.custom_code?.js ?? null,
149
+ redirects: Array.isArray(d.redirects) ? d.redirects : [],
150
+ glossary: Array.isArray(d.glossary) ? d.glossary.map((g) => ({ term: g.term, definition: g.definition })) : [],
151
+ variables: Array.isArray(d.variable_defaults) ? d.variable_defaults.filter((v) => v.source !== 'security').map((v) => ({ name: v.name, default: v.default ?? '' })) : [],
152
+ };
153
+ }
154
+
155
+ /** The part of a page's ssr document the conversion uses. */
156
+ export function pageFromSsr(ssr) {
157
+ const doc = ssr?.document;
158
+ if (!doc) return null;
159
+ const api = doc.api && doc.api.path ? { method: doc.api.method, path: doc.api.path, uri: doc.api.uri ?? null } : null;
160
+ return {
161
+ slug: doc.slug ?? null,
162
+ title: doc.title,
163
+ type: doc.type,
164
+ body: doc.content?.body ?? '',
165
+ excerpt: doc.content?.excerpt ?? null,
166
+ metaTitle: doc.metadata?.title ?? null,
167
+ metaDescription: doc.metadata?.description ?? null,
168
+ keywords: doc.metadata?.keywords ?? null,
169
+ icon: doc.appearance?.icon?.name ?? null,
170
+ hidden: ssr?.meta?.hidden ?? false,
171
+ robots: ssr?.meta?.robots ?? null,
172
+ link: doc.content?.link?.url ? { url: doc.content.link.url, newTab: Boolean(doc.content.link.new_tab) } : null,
173
+ api,
174
+ // The one-operation spec ReadMe embeds in an endpoint page - the
175
+ // fallback when the registry can't be read.
176
+ embeddedSpec: doc.api?.schema ?? null,
177
+ registryId: typeof ssr?.oasPublicUrl === 'string' && ssr.oasPublicUrl.includes('#') ? ssr.oasPublicUrl.split('#').pop() : null,
178
+ apiDefinitions: (ssr?.apiDefinitions ?? []).map((d) => ({ filename: d.filename, uri: d.uri })),
179
+ };
180
+ }
181
+
182
+ async function mapLimit(items, limit, fn) {
183
+ const out = new Array(items.length);
184
+ let next = 0;
185
+ const worker = async () => {
186
+ while (next < items.length) {
187
+ const i = next++;
188
+ out[i] = await fn(items[i], i);
189
+ }
190
+ };
191
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
192
+ return out;
193
+ }
194
+
195
+ /**
196
+ * Reads the site at `baseUrl` into a snapshot.
197
+ *
198
+ * @param {string} baseUrl any address on the site
199
+ * @param {object} [options]
200
+ * @param {typeof fetch} [options.fetchImpl]
201
+ * @param {number} [options.concurrency] pages fetched at once (default 4)
202
+ * @param {(event: {done: number, total: number}) => void} [options.onProgress]
203
+ */
204
+ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, concurrency = 4, onProgress } = {}) {
205
+ const base = normalizeBaseUrl(baseUrl);
206
+ const headers = { 'user-agent': USER_AGENT };
207
+ const problems = [];
208
+
209
+ const get = async (url, { redirect = 'follow' } = {}) => {
210
+ const res = await fetchImpl(url, { headers, redirect });
211
+ return res;
212
+ };
213
+ const getText = async (url) => {
214
+ const res = await get(url);
215
+ if (!res.ok) throw new Error(`${url} answered ${res.status}`);
216
+ return res.text();
217
+ };
218
+
219
+ // The home page: the project and both sidebars.
220
+ const homeHtml = await getText(`${base}/`);
221
+ const home = parseSsrProps(homeHtml);
222
+ if (!home?.context?.projectStore?.data) {
223
+ throw new Error(`${base} doesn't look like a ReadMe site - its home page has no ReadMe page data.`);
224
+ }
225
+ const project = projectFromSsr(home);
226
+ const sidebars = {
227
+ docs: sidebarCategories(home.guideCategories),
228
+ reference: sidebarCategories(home.referenceCategories),
229
+ };
230
+
231
+ // Every guide and reference page, from its own ssr-props.
232
+ const jobs = [];
233
+ for (const section of ['docs', 'reference']) {
234
+ for (const p of flattenSidebar(sidebars[section])) jobs.push({ section, slug: p.slug, type: p.type });
235
+ }
236
+ const recipesIndex = [];
237
+ let llmsTxt = null;
238
+ try {
239
+ llmsTxt = await getText(`${base}/llms.txt`);
240
+ recipesIndex.push(...recipesFromLlmsTxt(llmsTxt, base));
241
+ } catch (err) {
242
+ problems.push({ where: 'llms.txt', message: `Couldn't read llms.txt (${err.message}), so no recipes were found.` });
243
+ }
244
+ const total = jobs.length + recipesIndex.length;
245
+ let done = 0;
246
+ const tick = () => onProgress?.({ done: ++done, total });
247
+
248
+ const pages = {};
249
+ await mapLimit(jobs, concurrency, async ({ section, slug, type }) => {
250
+ const id = `${section}/${slug}`;
251
+ const url = `${base}/${section}/${encodeURIComponent(slug)}`;
252
+ try {
253
+ if (type === 'link') {
254
+ // A link page answers with a redirect to its target.
255
+ const res = await get(url, { redirect: 'manual' });
256
+ const location = res.headers.get('location');
257
+ if (location && new URL(location, base).origin !== base) {
258
+ pages[id] = { title: null, type: 'link', body: '', link: { url: new URL(location, base).href, newTab: true } };
259
+ return;
260
+ }
261
+ }
262
+ const html = await getText(url);
263
+ const page = pageFromSsr(parseSsrProps(html));
264
+ if (!page) throw new Error('the page has no ReadMe page data');
265
+ // A page with no content of its own - an API tag's page above its
266
+ // endpoints - answers with a redirect to its first child, whose page
267
+ // data then comes back. Keep only where it leads.
268
+ if (page.slug && page.slug !== slug) {
269
+ pages[id] = { slug, title: null, type: 'basic', body: '', redirectsTo: `${section}/${page.slug}` };
270
+ return;
271
+ }
272
+ pages[id] = page;
273
+ } catch (err) {
274
+ problems.push({ where: id, message: `Couldn't read ${url}: ${err.message}` });
275
+ } finally {
276
+ tick();
277
+ }
278
+ });
279
+
280
+ const recipes = [];
281
+ await mapLimit(recipesIndex, concurrency, async (r) => {
282
+ const url = `${base}/recipes/${encodeURIComponent(r.slug)}.md`;
283
+ try {
284
+ recipes.push({ ...r, markdown: await getText(url) });
285
+ } catch (err) {
286
+ problems.push({ where: `recipes/${r.slug}`, message: `Couldn't read ${url}: ${err.message}` });
287
+ } finally {
288
+ tick();
289
+ }
290
+ });
291
+ // Back in llms.txt's order - mapLimit finishes them in any order.
292
+ recipes.sort((a, b) => recipesIndex.findIndex((r) => r.slug === a.slug) - recipesIndex.findIndex((r) => r.slug === b.slug));
293
+
294
+ // The API definitions: one OpenAPI file each, from the registry.
295
+ const definitions = new Map(); // uri -> { filename, registryId }
296
+ for (const page of Object.values(pages)) {
297
+ if (!page.api?.uri) continue;
298
+ if (!definitions.has(page.api.uri)) {
299
+ const def = page.apiDefinitions?.find((d) => d.uri === page.api.uri);
300
+ const filename = def?.filename ?? page.api.uri.split('/').pop();
301
+ definitions.set(page.api.uri, { filename, registryId: page.registryId });
302
+ }
303
+ }
304
+ const openapi = [];
305
+ for (const [uri, def] of definitions) {
306
+ let spec = null;
307
+ if (def.registryId) {
308
+ try {
309
+ const res = await get(`${REGISTRY}${encodeURIComponent(def.registryId)}`);
310
+ if (res.ok) spec = await res.json();
311
+ } catch {
312
+ spec = null;
313
+ }
314
+ }
315
+ if (!spec?.paths) {
316
+ problems.push({
317
+ where: def.filename,
318
+ 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.`,
319
+ });
320
+ spec = null;
321
+ }
322
+ openapi.push({ uri, filename: def.filename, spec });
323
+ }
324
+
325
+ return {
326
+ version: SNAPSHOT_VERSION,
327
+ baseUrl: base,
328
+ fetchedAt: new Date().toISOString(),
329
+ project,
330
+ sidebars,
331
+ pages,
332
+ recipes,
333
+ openapi,
334
+ problems,
335
+ };
336
+ }