@writedocs/generator 0.21.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/package.json +1 -1
- package/src/lib/readme-convert.js +127 -15
- package/src/lib/readme-fetch.js +162 -10
- package/src/lib/readme-html.js +62 -0
- package/src/lib/readme-mdx.js +165 -28
- package/src/lib/readme-recipes.js +1 -1
package/package.json
CHANGED
|
@@ -26,9 +26,10 @@
|
|
|
26
26
|
|
|
27
27
|
import { convertReadmeBody, makeLinkRewriter, wrapHtml, README_HTML_CLASS, README_HTML_CSS } from './readme-mdx.js';
|
|
28
28
|
import { convertRecipe } from './readme-recipes.js';
|
|
29
|
-
import { htmlToMdx } from './readme-html.js';
|
|
29
|
+
import { htmlToMdx, scopeCustomCss } from './readme-html.js';
|
|
30
30
|
import { Notes } from './mintlify-convert.js';
|
|
31
31
|
import { parseHex, contrastRatio } from './color.js';
|
|
32
|
+
import { posix } from 'node:path';
|
|
32
33
|
|
|
33
34
|
// writedocs' dark background when `styles.background` doesn't set one.
|
|
34
35
|
const DARK_BACKGROUND = '#0b1120';
|
|
@@ -138,28 +139,56 @@ export function convertReadmeSnapshot(snapshot) {
|
|
|
138
139
|
};
|
|
139
140
|
const glossary = new Map((project.glossary ?? []).map((g) => [String(g.term).toLowerCase(), g.definition]));
|
|
140
141
|
const recipeSlugs = new Set((snapshot.recipes ?? []).map((r) => r.slug));
|
|
142
|
+
// ReadMe's reusable content ("custom blocks", used as `<Duvidas />`): one
|
|
143
|
+
// snippet each, imported by every page that uses it.
|
|
144
|
+
const blocks = new Map();
|
|
145
|
+
for (const page of Object.values(snapshot.pages ?? {})) {
|
|
146
|
+
for (const b of page.customBlocks ?? []) if (/^[A-Z][A-Za-z0-9]*$/.test(b.tag) && !blocks.has(b.tag)) blocks.set(b.tag, b.source);
|
|
147
|
+
}
|
|
148
|
+
const usedBlocks = new Set();
|
|
141
149
|
const ctxFor = (where) => ({
|
|
142
150
|
rewriteLink: (url) => rewriteLink(url, where),
|
|
143
151
|
localImage,
|
|
144
152
|
glossary,
|
|
145
153
|
recipes: recipeSlugs,
|
|
154
|
+
components: new Set(blocks.keys()),
|
|
146
155
|
note: (key, message) => notes.add(key, [where], message),
|
|
147
156
|
});
|
|
157
|
+
/** The import lines for the custom blocks `body` uses, from page `id`. */
|
|
158
|
+
const blockImports = (id, body) => {
|
|
159
|
+
const lines = [];
|
|
160
|
+
for (const tag of blocks.keys()) {
|
|
161
|
+
if (!new RegExp(`<${tag}[\\s/>]`).test(body)) continue;
|
|
162
|
+
usedBlocks.add(tag);
|
|
163
|
+
let rel = posix.relative(posix.dirname(id), `snippets/${tag}.mdx`);
|
|
164
|
+
if (!rel.startsWith('.')) rel = `./${rel}`;
|
|
165
|
+
lines.push(`import ${tag} from '${rel}';`);
|
|
166
|
+
}
|
|
167
|
+
return lines.join('\n');
|
|
168
|
+
};
|
|
148
169
|
|
|
149
170
|
// The OpenAPI files, by ReadMe's definition uri.
|
|
150
171
|
const specs = new Map();
|
|
151
172
|
for (const def of snapshot.openapi ?? []) {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
173
|
+
// The registry's file, with every operation an endpoint page shows that
|
|
174
|
+
// it lacks taken from that page's own embedded spec: the registry can
|
|
175
|
+
// be unreachable, and for an API written page by page in ReadMe's editor
|
|
176
|
+
// it serves the file with no operations at all ("x-readme-fauxas").
|
|
177
|
+
const pages = Object.values(snapshot.pages ?? {}).filter((p) => p.api?.uri === def.uri && p.embeddedSpec);
|
|
178
|
+
const missing = pages.filter((p) => !operation(def.spec, p.api.method, p.api.path));
|
|
179
|
+
const spec = missing.length ? mergeEmbeddedSpecs([def.spec, ...missing.map((p) => p.embeddedSpec)].filter(Boolean)) : def.spec;
|
|
156
180
|
if (!spec) continue;
|
|
181
|
+
if (def.spec && missing.length) {
|
|
182
|
+
notes.add(`spec-filled:${def.uri}`, [def.filename], `${missing.length} of the operations the pages show weren't in the API definition ReadMe serves - they're taken from the endpoint pages.`);
|
|
183
|
+
}
|
|
157
184
|
const path = `openapi/${def.filename.replace(/[^\w.-]+/g, '-')}`;
|
|
158
185
|
specs.set(def.uri, { path, spec });
|
|
159
186
|
files.push({ path, content: `${JSON.stringify(spec, null, 2)}\n` });
|
|
160
187
|
}
|
|
161
188
|
|
|
162
189
|
const writePage = (id, fields, body) => {
|
|
190
|
+
const imports = body ? blockImports(id, body) : '';
|
|
191
|
+
if (imports) body = `${imports}\n\n${body}`;
|
|
163
192
|
files.push({ path: `${id}.mdx`, content: `${frontmatter(fields)}\n${body ? `\n${body}\n` : ''}` });
|
|
164
193
|
counts.pages++;
|
|
165
194
|
};
|
|
@@ -232,9 +261,11 @@ export function convertReadmeSnapshot(snapshot) {
|
|
|
232
261
|
};
|
|
233
262
|
|
|
234
263
|
const tabs = [];
|
|
264
|
+
const tabFor = {}; // section -> its tab
|
|
265
|
+
let notFound = null;
|
|
235
266
|
const label = (key, fallback) => project.sections?.[key]?.label || fallback;
|
|
236
267
|
const docsNav = sectionNav('docs');
|
|
237
|
-
if (docsNav.length) tabs.push({ tab: label('docs', 'Guides'), pages: docsNav });
|
|
268
|
+
if (docsNav.length) tabs.push((tabFor.docs = { tab: label('docs', 'Guides'), pages: docsNav }));
|
|
238
269
|
const recipesNav = [];
|
|
239
270
|
for (const recipe of snapshot.recipes ?? []) {
|
|
240
271
|
const id = `recipes/${recipe.slug}`;
|
|
@@ -243,9 +274,73 @@ export function convertReadmeSnapshot(snapshot) {
|
|
|
243
274
|
counts.recipes++;
|
|
244
275
|
recipesNav.push(id);
|
|
245
276
|
}
|
|
246
|
-
if (recipesNav.length) tabs.push({ tab: label('recipes', 'Recipes'), pages: recipesNav });
|
|
277
|
+
if (recipesNav.length) tabs.push((tabFor.recipes = { tab: label('recipes', 'Recipes'), pages: recipesNav }));
|
|
247
278
|
const referenceNav = sectionNav('reference');
|
|
248
|
-
if (referenceNav.length) tabs.push({ tab: label('reference', 'API Reference'), pages: referenceNav });
|
|
279
|
+
if (referenceNav.length) tabs.push((tabFor.reference = { tab: label('reference', 'API Reference'), pages: referenceNav }));
|
|
280
|
+
|
|
281
|
+
// A page read from its ssr-props outside the sidebars: a custom page or a
|
|
282
|
+
// changelog entry. Its body is Markdown, or HTML for an HTML custom page.
|
|
283
|
+
const standalonePage = (id, fallbackTitle, extra = {}) => {
|
|
284
|
+
const page = snapshot.pages?.[id];
|
|
285
|
+
if (!page) {
|
|
286
|
+
notes.add('unreadable-page', [id], "This page couldn't be read from the site, so it's not in the project.");
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
const fields = { title: page.title ?? fallbackTitle };
|
|
290
|
+
const description = page.excerpt?.trim() || page.metaDescription?.trim();
|
|
291
|
+
if (description) fields.description = description;
|
|
292
|
+
Object.assign(fields, extra);
|
|
293
|
+
const body = !page.body?.trim()
|
|
294
|
+
? ''
|
|
295
|
+
: page.contentType === 'html'
|
|
296
|
+
? wrapHtml(htmlToMdx(page.body, { rewriteUrl: (url, name) => (name === 'src' ? localImage(url) : rewriteLink(url, id)) }))
|
|
297
|
+
: convertReadmeBody(page.body, ctxFor(id));
|
|
298
|
+
writePage(id, fields, body);
|
|
299
|
+
return id;
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
// The changelog: a tab of its own, newest first, as llms.txt lists it.
|
|
303
|
+
const changelogNav = (snapshot.changelog ?? []).map((c) => standalonePage(`changelog/${c.slug}`, c.title)).filter(Boolean);
|
|
304
|
+
if (changelogNav.length) tabs.push((tabFor.changelog = { tab: label('changelog', 'Changelog'), pages: changelogNav }));
|
|
305
|
+
|
|
306
|
+
// Custom pages (/page/...): in no sidebar on ReadMe - linked from the
|
|
307
|
+
// landing page or the header. Hidden pages here, so they're built at the
|
|
308
|
+
// same address without showing up in a sidebar. The one ReadMe shows for
|
|
309
|
+
// a missing address is the 404 page instead.
|
|
310
|
+
const customNav = [];
|
|
311
|
+
for (const c of snapshot.customPages ?? []) {
|
|
312
|
+
if (c.slug === project.notFoundPage) {
|
|
313
|
+
const page = snapshot.pages?.[`page/${c.slug}`];
|
|
314
|
+
notFound = { title: page?.title ?? c.title };
|
|
315
|
+
notes.add('not-found-page', [`page/${c.slug}`], "This custom page was the site's \"page not found\" page: its title is notFound.title. Its content isn't carried over - writedocs' page has a title and a description.");
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
const id = standalonePage(`page/${c.slug}`, c.title, { hidden: true });
|
|
319
|
+
if (id) customNav.push(id);
|
|
320
|
+
}
|
|
321
|
+
if (customNav.length) {
|
|
322
|
+
if (tabs.length) tabs[0].pages.push(...customNav);
|
|
323
|
+
else tabs.push({ tab: label('docs', 'Guides'), pages: customNav });
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// Pages found by following links (lib/readme-fetch.js): hidden on ReadMe,
|
|
327
|
+
// so hidden here, in their section's tab - built at the same address,
|
|
328
|
+
// out of the sidebar.
|
|
329
|
+
for (const d of snapshot.discovered ?? []) {
|
|
330
|
+
const [section, ...rest] = d.id.split('/');
|
|
331
|
+
const item =
|
|
332
|
+
section === 'docs' || section === 'reference'
|
|
333
|
+
? navItem(section, { slug: rest.join('/'), title: d.title, type: d.type, hidden: true, pages: [] })
|
|
334
|
+
: standalonePage(d.id, d.title, { hidden: true });
|
|
335
|
+
if (typeof item !== 'string') continue;
|
|
336
|
+
const tab = tabFor[section] ?? tabs[0];
|
|
337
|
+
if (tab) tab.pages.push(item);
|
|
338
|
+
else tabs.push((tabFor[section] = { tab: label(section, 'Guides'), pages: [item] }));
|
|
339
|
+
}
|
|
340
|
+
if (snapshot.discovered?.length) {
|
|
341
|
+
notes.add('discovered', ['navigation'], `${snapshot.discovered.length} hidden pages - out of ReadMe's sidebars, but linked to from other pages - were found and kept as hidden pages.`);
|
|
342
|
+
}
|
|
343
|
+
for (const r of snapshot.linkRedirects ?? []) pageRedirects.push(r);
|
|
249
344
|
|
|
250
345
|
// The landing page.
|
|
251
346
|
const landing = (project.landingPage ?? []).filter((s) => s.html || s.title || s.text);
|
|
@@ -253,7 +348,7 @@ export function convertReadmeSnapshot(snapshot) {
|
|
|
253
348
|
const parts = [];
|
|
254
349
|
for (const section of landing) {
|
|
255
350
|
if (section.type === 'html' && section.html) {
|
|
256
|
-
parts.push(wrapHtml(htmlToMdx(section.html, { rewriteUrl: (url, name) => (name === 'src' ? localImage(url) : rewriteLink(url, 'index')) })));
|
|
351
|
+
parts.push(wrapHtml(htmlToMdx(section.html, { rewriteUrl: (url, name) => (name === 'src' ? localImage(url) : rewriteLink(url, 'index')) }), 'rm-LandingPage'));
|
|
257
352
|
} else {
|
|
258
353
|
if (section.title) parts.push(`## ${section.title}`);
|
|
259
354
|
if (section.text) parts.push(convertReadmeBody(section.text, ctxFor('index')));
|
|
@@ -263,14 +358,26 @@ export function convertReadmeSnapshot(snapshot) {
|
|
|
263
358
|
writePage('index', { title: project.name ?? 'Home', mode: 'custom' }, parts.join('\n\n'));
|
|
264
359
|
}
|
|
265
360
|
|
|
266
|
-
|
|
267
|
-
files.push({ path:
|
|
361
|
+
for (const tag of usedBlocks) {
|
|
362
|
+
files.push({ path: `snippets/${tag}.mdx`, content: `${convertReadmeBody(blocks.get(tag), ctxFor(`snippets/${tag}`))}\n` });
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const hasHtml = files.some((f) => f.path.endsWith('.mdx') && f.content.includes(`className="${README_HTML_CLASS}`));
|
|
366
|
+
if (hasHtml) files.push({ path: 'readme-html.css', content: README_HTML_CSS });
|
|
367
|
+
// The project's custom CSS, for its hand-written HTML: scoped to it, so
|
|
368
|
+
// the rules for ReadMe's own page can't reach writedocs'.
|
|
369
|
+
if (project.customCss?.trim() && hasHtml) {
|
|
370
|
+
files.push({
|
|
371
|
+
path: 'readme-custom.css',
|
|
372
|
+
content: `/* Written by writedocs convert --readme: the ReadMe project's custom CSS,\n applied only inside the HTML converted from ReadMe (.${README_HTML_CLASS}). */\n${scopeCustomCss(project.customCss, `.${README_HTML_CLASS}`)}`,
|
|
373
|
+
});
|
|
374
|
+
notes.add('custom-css', ['readme-custom.css'], "The project's custom CSS is in readme-custom.css, applied only inside the HTML converted from ReadMe (the landing page and HTML blocks) - its rules for ReadMe's own header and sidebar don't apply. Review it, and remove what isn't needed.");
|
|
268
375
|
}
|
|
269
376
|
|
|
270
|
-
if (project.sections?.changelog?.visible) {
|
|
271
|
-
notes.add('changelog', ['changelog'], "The site's changelog
|
|
377
|
+
if (project.sections?.changelog?.visible && !changelogNav.length) {
|
|
378
|
+
notes.add('changelog', ['changelog'], "The site's changelog couldn't be read (llms.txt lists no entries) - add its entries as pages (the Update component suits them).");
|
|
272
379
|
}
|
|
273
|
-
if (project.customCss) notes.add('custom-css', ['appearance'], 'The project has custom CSS - not carried over
|
|
380
|
+
if (project.customCss?.trim() && !hasHtml) notes.add('custom-css', ['appearance'], 'The project has custom CSS - not carried over: it styles ReadMe\'s own page, and no HTML was converted for it to style. See "Custom CSS and scripts".');
|
|
274
381
|
if (project.customJs) notes.add('custom-js', ['appearance'], 'The project has custom JavaScript - not carried over.');
|
|
275
382
|
|
|
276
383
|
// writedocs.json.
|
|
@@ -295,6 +402,7 @@ export function convertReadmeSnapshot(snapshot) {
|
|
|
295
402
|
if (Object.keys(styles).length) config.styles = styles;
|
|
296
403
|
// index.mdx is the home page whether or not the navigation lists it.
|
|
297
404
|
config.navigation = tabs.length > 1 ? { tabs } : tabs[0]?.pages ?? [];
|
|
405
|
+
if (notFound) config.notFound = notFound;
|
|
298
406
|
|
|
299
407
|
const redirects = [...pageRedirects];
|
|
300
408
|
for (const r of project.redirects ?? []) {
|
|
@@ -307,7 +415,11 @@ export function convertReadmeSnapshot(snapshot) {
|
|
|
307
415
|
}
|
|
308
416
|
redirects.push({ source: rewriteLink(source), destination: rewriteLink(destination) });
|
|
309
417
|
}
|
|
310
|
-
|
|
418
|
+
// One redirect per address, and none away from a page the project has.
|
|
419
|
+
const pageAddresses = new Set(files.filter((f) => f.path.endsWith('.mdx')).map((f) => `/${f.path.replace(/\.mdx$/, '')}`));
|
|
420
|
+
const bySource = new Map();
|
|
421
|
+
for (const r of redirects) if (!bySource.has(r.source) && !pageAddresses.has(r.source)) bySource.set(r.source, r);
|
|
422
|
+
if (bySource.size) config.redirects = [...bySource.values()];
|
|
311
423
|
if (project.variables?.length) {
|
|
312
424
|
config.variables = Object.fromEntries(project.variables.map((v) => [v.name, String(v.default ?? v.name)]));
|
|
313
425
|
}
|
package/src/lib/readme-fetch.js
CHANGED
|
@@ -58,6 +58,13 @@ export function normalizeBaseUrl(input) {
|
|
|
58
58
|
|
|
59
59
|
/** The recipes listed in llms.txt: `- [Title](https://site/recipes/slug.md)`. */
|
|
60
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) {
|
|
61
68
|
const out = [];
|
|
62
69
|
const seen = new Set();
|
|
63
70
|
const re = /\[([^\]]+)\]\((\S+?)\)/g;
|
|
@@ -71,7 +78,7 @@ export function recipesFromLlmsTxt(text, baseUrl) {
|
|
|
71
78
|
}
|
|
72
79
|
if (url.origin !== new URL(baseUrl).origin) continue;
|
|
73
80
|
const parts = url.pathname.replace(/\.md$/, '').split('/').filter(Boolean);
|
|
74
|
-
if (parts.length !== 2 || parts[0] !==
|
|
81
|
+
if (parts.length !== 2 || parts[0] !== section) continue;
|
|
75
82
|
const slug = decodeURIComponent(parts[1]);
|
|
76
83
|
if (seen.has(slug)) continue;
|
|
77
84
|
seen.add(slug);
|
|
@@ -80,6 +87,37 @@ export function recipesFromLlmsTxt(text, baseUrl) {
|
|
|
80
87
|
return out;
|
|
81
88
|
}
|
|
82
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
|
+
|
|
83
121
|
/** Every page in a ReadMe sidebar (categories > pages > child pages), in order. */
|
|
84
122
|
export function flattenSidebar(categories) {
|
|
85
123
|
const out = [];
|
|
@@ -147,6 +185,8 @@ export function projectFromSsr(ssr) {
|
|
|
147
185
|
customCss: a.custom_code?.css ?? null,
|
|
148
186
|
customJs: a.custom_code?.js ?? null,
|
|
149
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,
|
|
150
190
|
glossary: Array.isArray(d.glossary) ? d.glossary.map((g) => ({ term: g.term, definition: g.definition })) : [],
|
|
151
191
|
variables: Array.isArray(d.variable_defaults) ? d.variable_defaults.filter((v) => v.source !== 'security').map((v) => ({ name: v.name, default: v.default ?? '' })) : [],
|
|
152
192
|
};
|
|
@@ -167,6 +207,10 @@ export function pageFromSsr(ssr) {
|
|
|
167
207
|
metaDescription: doc.metadata?.description ?? null,
|
|
168
208
|
keywords: doc.metadata?.keywords ?? null,
|
|
169
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,
|
|
170
214
|
hidden: ssr?.meta?.hidden ?? false,
|
|
171
215
|
robots: ssr?.meta?.robots ?? null,
|
|
172
216
|
link: doc.content?.link?.url ? { url: doc.content.link.url, newTab: Boolean(doc.content.link.new_tab) } : null,
|
|
@@ -174,6 +218,11 @@ export function pageFromSsr(ssr) {
|
|
|
174
218
|
// The one-operation spec ReadMe embeds in an endpoint page - the
|
|
175
219
|
// fallback when the registry can't be read.
|
|
176
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 })),
|
|
177
226
|
registryId: typeof ssr?.oasPublicUrl === 'string' && ssr.oasPublicUrl.includes('#') ? ssr.oasPublicUrl.split('#').pop() : null,
|
|
178
227
|
apiDefinitions: (ssr?.apiDefinitions ?? []).map((d) => ({ filename: d.filename, uri: d.uri })),
|
|
179
228
|
};
|
|
@@ -192,6 +241,8 @@ async function mapLimit(items, limit, fn) {
|
|
|
192
241
|
return out;
|
|
193
242
|
}
|
|
194
243
|
|
|
244
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
245
|
+
|
|
195
246
|
/**
|
|
196
247
|
* Reads the site at `baseUrl` into a snapshot.
|
|
197
248
|
*
|
|
@@ -200,15 +251,28 @@ async function mapLimit(items, limit, fn) {
|
|
|
200
251
|
* @param {typeof fetch} [options.fetchImpl]
|
|
201
252
|
* @param {number} [options.concurrency] pages fetched at once (default 4)
|
|
202
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)
|
|
203
255
|
*/
|
|
204
|
-
export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, concurrency = 4, onProgress } = {}) {
|
|
256
|
+
export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, concurrency = 4, onProgress, retryDelay = 1000 } = {}) {
|
|
205
257
|
const base = normalizeBaseUrl(baseUrl);
|
|
206
258
|
const headers = { 'user-agent': USER_AGENT };
|
|
207
259
|
const problems = [];
|
|
208
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;
|
|
209
267
|
const get = async (url, { redirect = 'follow' } = {}) => {
|
|
210
|
-
|
|
211
|
-
|
|
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
|
+
}
|
|
212
276
|
};
|
|
213
277
|
const getText = async (url) => {
|
|
214
278
|
const res = await get(url);
|
|
@@ -216,16 +280,32 @@ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, c
|
|
|
216
280
|
return res.text();
|
|
217
281
|
};
|
|
218
282
|
|
|
219
|
-
// The home page: the project and both sidebars.
|
|
283
|
+
// The home page: the project, and on some sites both sidebars.
|
|
220
284
|
const homeHtml = await getText(`${base}/`);
|
|
221
285
|
const home = parseSsrProps(homeHtml);
|
|
222
286
|
if (!home?.context?.projectStore?.data) {
|
|
223
287
|
throw new Error(`${base} doesn't look like a ReadMe site - its home page has no ReadMe page data.`);
|
|
224
288
|
}
|
|
225
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
|
+
};
|
|
226
306
|
const sidebars = {
|
|
227
|
-
docs:
|
|
228
|
-
reference:
|
|
307
|
+
docs: project.sections.docs?.visible === false ? [] : await sectionSidebar('docs', home.guideCategories),
|
|
308
|
+
reference: project.sections.reference?.visible === false ? [] : await sectionSidebar('reference', home.referenceCategories),
|
|
229
309
|
};
|
|
230
310
|
|
|
231
311
|
// Every guide and reference page, from its own ssr-props.
|
|
@@ -234,12 +314,23 @@ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, c
|
|
|
234
314
|
for (const p of flattenSidebar(sidebars[section])) jobs.push({ section, slug: p.slug, type: p.type });
|
|
235
315
|
}
|
|
236
316
|
const recipesIndex = [];
|
|
317
|
+
const customPages = [];
|
|
318
|
+
const changelog = [];
|
|
237
319
|
let llmsTxt = null;
|
|
238
320
|
try {
|
|
239
321
|
llmsTxt = await getText(`${base}/llms.txt`);
|
|
240
|
-
recipesIndex.push(...recipesFromLlmsTxt(llmsTxt, base));
|
|
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'));
|
|
241
327
|
} catch (err) {
|
|
242
|
-
problems.push({ where: 'llms.txt', message: `Couldn't read llms.txt (${err.message}), so no recipes were found.` });
|
|
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.`);
|
|
243
334
|
}
|
|
244
335
|
const total = jobs.length + recipesIndex.length;
|
|
245
336
|
let done = 0;
|
|
@@ -265,7 +356,7 @@ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, c
|
|
|
265
356
|
// A page with no content of its own - an API tag's page above its
|
|
266
357
|
// endpoints - answers with a redirect to its first child, whose page
|
|
267
358
|
// data then comes back. Keep only where it leads.
|
|
268
|
-
if (page.slug && page.slug !== slug) {
|
|
359
|
+
if (page.slug && page.slug.normalize() !== slug.normalize()) {
|
|
269
360
|
pages[id] = { slug, title: null, type: 'basic', body: '', redirectsTo: `${section}/${page.slug}` };
|
|
270
361
|
return;
|
|
271
362
|
}
|
|
@@ -291,6 +382,63 @@ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, c
|
|
|
291
382
|
// Back in llms.txt's order - mapLimit finishes them in any order.
|
|
292
383
|
recipes.sort((a, b) => recipesIndex.findIndex((r) => r.slug === a.slug) - recipesIndex.findIndex((r) => r.slug === b.slug));
|
|
293
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
|
+
|
|
294
442
|
// The API definitions: one OpenAPI file each, from the registry.
|
|
295
443
|
const definitions = new Map(); // uri -> { filename, registryId }
|
|
296
444
|
for (const page of Object.values(pages)) {
|
|
@@ -330,6 +478,10 @@ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, c
|
|
|
330
478
|
sidebars,
|
|
331
479
|
pages,
|
|
332
480
|
recipes,
|
|
481
|
+
customPages,
|
|
482
|
+
changelog,
|
|
483
|
+
discovered,
|
|
484
|
+
linkRedirects,
|
|
333
485
|
openapi,
|
|
334
486
|
problems,
|
|
335
487
|
};
|
package/src/lib/readme-html.js
CHANGED
|
@@ -170,6 +170,68 @@ function element(node, rewriteUrl, indent) {
|
|
|
170
170
|
return `${open}>\n${lines.join('\n')}\n${indent}</${tag}>`;
|
|
171
171
|
}
|
|
172
172
|
|
|
173
|
+
/** The top-level statements of a style sheet - rules and at-rules, each
|
|
174
|
+
* with its block - skipping comments and strings while counting braces. */
|
|
175
|
+
function cssStatements(css) {
|
|
176
|
+
const out = [];
|
|
177
|
+
let start = 0;
|
|
178
|
+
let depth = 0;
|
|
179
|
+
let i = 0;
|
|
180
|
+
while (i < css.length) {
|
|
181
|
+
const c = css[i];
|
|
182
|
+
if (c === '/' && css[i + 1] === '*') {
|
|
183
|
+
const end = css.indexOf('*/', i + 2);
|
|
184
|
+
i = end === -1 ? css.length : end + 2;
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (c === '"' || c === "'") {
|
|
188
|
+
let j = i + 1;
|
|
189
|
+
while (j < css.length && css[j] !== c) j += css[j] === '\\' ? 2 : 1;
|
|
190
|
+
i = j + 1;
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
if (c === '{') depth++;
|
|
194
|
+
else if (c === '}') {
|
|
195
|
+
depth = Math.max(0, depth - 1);
|
|
196
|
+
if (depth === 0) {
|
|
197
|
+
out.push(css.slice(start, i + 1).trim());
|
|
198
|
+
start = i + 1;
|
|
199
|
+
}
|
|
200
|
+
} else if (c === ';' && depth === 0) {
|
|
201
|
+
out.push(css.slice(start, i + 1).trim());
|
|
202
|
+
start = i + 1;
|
|
203
|
+
}
|
|
204
|
+
i++;
|
|
205
|
+
}
|
|
206
|
+
const rest = css.slice(start).trim();
|
|
207
|
+
if (rest) out.push(rest);
|
|
208
|
+
return out.filter(Boolean);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// At-rules that can't go inside @scope (or mean nothing there), kept at the
|
|
212
|
+
// top level.
|
|
213
|
+
const TOP_LEVEL_AT = /^@(import|font-face|(-[a-z]+-)?keyframes|property|layer|namespace|counter-style|font-feature-values|page)\b/i;
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* A ReadMe project's custom CSS, applied only inside `scopeSelector` - the
|
|
217
|
+
* HTML converted from ReadMe. That CSS styled ReadMe's whole page: its own
|
|
218
|
+
* header and sidebar (`.rm-Header`), `html`, `body`, and the classes of the
|
|
219
|
+
* project's hand-written HTML. Inside `@scope`, only the last can match;
|
|
220
|
+
* nothing reaches writedocs' own layout. `@charset` is dropped; `@import`,
|
|
221
|
+
* `@font-face`, `@keyframes` and the like stay at the top level.
|
|
222
|
+
*/
|
|
223
|
+
export function scopeCustomCss(css, scopeSelector) {
|
|
224
|
+
const top = [];
|
|
225
|
+
const scoped = [];
|
|
226
|
+
for (const statement of cssStatements(String(css ?? ''))) {
|
|
227
|
+
if (/^@charset\b/i.test(statement)) continue;
|
|
228
|
+
(TOP_LEVEL_AT.test(statement) ? top : scoped).push(statement);
|
|
229
|
+
}
|
|
230
|
+
const parts = [...top];
|
|
231
|
+
if (scoped.length) parts.push(`@scope (${scopeSelector}) {\n${scoped.join('\n')}\n}`);
|
|
232
|
+
return `${parts.join('\n\n')}\n`;
|
|
233
|
+
}
|
|
234
|
+
|
|
173
235
|
/**
|
|
174
236
|
* The MDX for an HTML fragment: one block, no blank lines inside it.
|
|
175
237
|
* Top-level text becomes a <p>-free inline run of its own; top-level
|
package/src/lib/readme-mdx.js
CHANGED
|
@@ -158,6 +158,10 @@ export function makeLinkRewriter({ baseUrl, subdomain } = {}) {
|
|
|
158
158
|
// Splitting the body
|
|
159
159
|
// ---------------------------------------------------------------------
|
|
160
160
|
|
|
161
|
+
// A fence line: indentation and any list markers (`1. ```html`), the marks,
|
|
162
|
+
// and the info string.
|
|
163
|
+
const FENCE_RE = /^(\s*(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)*)(`{3,}|~{3,})(.*)$/;
|
|
164
|
+
|
|
161
165
|
/** The body as segments: { kind: 'text' | 'code' | 'html', lines | text }.
|
|
162
166
|
* A code segment is one fence; an html segment is an <HTMLBlock>'s HTML. */
|
|
163
167
|
export function splitBody(body) {
|
|
@@ -170,15 +174,19 @@ export function splitBody(body) {
|
|
|
170
174
|
};
|
|
171
175
|
for (let i = 0; i < lines.length; i++) {
|
|
172
176
|
const line = lines[i];
|
|
173
|
-
const fence =
|
|
177
|
+
const fence = FENCE_RE.exec(line);
|
|
174
178
|
if (fence && !(fence[2][0] === '`' && fence[3].includes('`'))) {
|
|
175
|
-
|
|
179
|
+
// `prefix` is what comes before the fence on its line - indentation,
|
|
180
|
+
// and list markers when the fence opens a list item (`1. ```html`);
|
|
181
|
+
// `indent` is the same width in spaces, for the lines after it.
|
|
182
|
+
const [, prefix, marks, info] = fence;
|
|
183
|
+
const indent = prefix.replace(/\S/g, ' ');
|
|
176
184
|
const close = new RegExp(`^\\s*${marks[0] === '`' ? '`' : '~'}{${marks.length},}\\s*$`);
|
|
177
185
|
const body = [];
|
|
178
186
|
let j = i + 1;
|
|
179
187
|
while (j < lines.length && !close.test(lines[j])) body.push(lines[j++]);
|
|
180
188
|
flushText();
|
|
181
|
-
segments.push({ kind: 'code', indent, marks, info: info.trim(), body });
|
|
189
|
+
segments.push({ kind: 'code', prefix, indent, marks, info: info.trim(), body });
|
|
182
190
|
i = j; // the closing fence (or the end)
|
|
183
191
|
continue;
|
|
184
192
|
}
|
|
@@ -222,9 +230,9 @@ export function normalizeFenceInfo(info, { inGroup = false } = {}) {
|
|
|
222
230
|
return title ? `${mapped} ${title}` : mapped;
|
|
223
231
|
}
|
|
224
232
|
|
|
225
|
-
function renderCode(seg, inGroup) {
|
|
233
|
+
function renderCode(seg, inGroup, prefix = seg.prefix ?? seg.indent) {
|
|
226
234
|
const info = normalizeFenceInfo(seg.info, { inGroup });
|
|
227
|
-
return [`${
|
|
235
|
+
return [`${prefix}${seg.marks}${info}`, ...seg.body, `${seg.indent}${seg.marks}`];
|
|
228
236
|
}
|
|
229
237
|
|
|
230
238
|
// ---------------------------------------------------------------------
|
|
@@ -273,8 +281,8 @@ export function convertBlockquoteCallouts(lines, unwrap = (s) => s.replace(/`([^
|
|
|
273
281
|
const out = [];
|
|
274
282
|
let fence = null;
|
|
275
283
|
for (let i = 0; i < lines.length; i++) {
|
|
276
|
-
const f =
|
|
277
|
-
if (f && (!fence || (f[
|
|
284
|
+
const f = FENCE_RE.exec(lines[i]);
|
|
285
|
+
if (f && (!fence || (f[2][0] === fence[0] && f[2].length >= fence.length))) fence = fence ? null : f[2];
|
|
278
286
|
const m = !fence && !f && /^(\s*)>\s?(.*)$/.exec(lines[i]);
|
|
279
287
|
const emoji = m && EMOJI_TYPES.find(([e]) => m[2].startsWith(e));
|
|
280
288
|
if (!emoji) {
|
|
@@ -301,6 +309,131 @@ export function convertBlockquoteCallouts(lines, unwrap = (s) => s.replace(/`([^
|
|
|
301
309
|
return out;
|
|
302
310
|
}
|
|
303
311
|
|
|
312
|
+
// ---------------------------------------------------------------------
|
|
313
|
+
// ReadMe's older block syntax
|
|
314
|
+
// ---------------------------------------------------------------------
|
|
315
|
+
|
|
316
|
+
/** A video service's embed address for `url` (YouTube, Vimeo, Loom), or null. */
|
|
317
|
+
export function videoEmbedUrl(url) {
|
|
318
|
+
let u;
|
|
319
|
+
try {
|
|
320
|
+
u = new URL(String(url).replace(/^\/\//, 'https://'));
|
|
321
|
+
} catch {
|
|
322
|
+
return null;
|
|
323
|
+
}
|
|
324
|
+
const host = u.hostname.replace(/^www\.|^m\./, '');
|
|
325
|
+
if (host === 'youtube.com' || host === 'youtube-nocookie.com') {
|
|
326
|
+
const id = u.searchParams.get('v') ?? /^\/(?:embed|shorts|live)\/([\w-]+)/.exec(u.pathname)?.[1];
|
|
327
|
+
return id ? `https://www.youtube.com/embed/${id}` : null;
|
|
328
|
+
}
|
|
329
|
+
if (host === 'youtu.be') return /^\/([\w-]+)/.test(u.pathname) ? `https://www.youtube.com/embed/${u.pathname.slice(1).split('/')[0]}` : null;
|
|
330
|
+
if (host === 'vimeo.com' || host === 'player.vimeo.com') {
|
|
331
|
+
const id = /(\d{5,})/.exec(u.pathname)?.[1];
|
|
332
|
+
return id ? `https://player.vimeo.com/video/${id}` : null;
|
|
333
|
+
}
|
|
334
|
+
if (host === 'loom.com') {
|
|
335
|
+
const id = /\/(?:share|embed)\/([\w-]+)/.exec(u.pathname)?.[1];
|
|
336
|
+
return id ? `https://www.loom.com/embed/${id}` : null;
|
|
337
|
+
}
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** An embed: a <Video> for a video service, otherwise a card to the URL. */
|
|
342
|
+
function embedToMdx(url, title, note) {
|
|
343
|
+
const video = videoEmbedUrl(url);
|
|
344
|
+
if (video) return `<Video src="${video}"${title ? ` ${jsxAttr('title', title)}` : ''} />`;
|
|
345
|
+
note('embed', 'An embed of something other than a video became a card linking to it.');
|
|
346
|
+
return `<Card ${jsxAttr('title', title || url)} icon="external-link" href="${url}" />`;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** A value safe in a ReadMe-style `name="..."` attribute, which the later
|
|
350
|
+
* passes read back with parseAttributes(). */
|
|
351
|
+
const attrText = (v) => String(v ?? '').replace(/"/g, "'").replace(/\s*\n\s*/g, ' ').trim();
|
|
352
|
+
|
|
353
|
+
/** One legacy block's JSON, as the ReadMe MDX the rest of the conversion
|
|
354
|
+
* handles - or null for a type that has no conversion. */
|
|
355
|
+
function legacyBlock(type, data, note) {
|
|
356
|
+
switch (type) {
|
|
357
|
+
case 'image':
|
|
358
|
+
return (data.images ?? [])
|
|
359
|
+
.map((img) => {
|
|
360
|
+
const [raw, title, alt] = Array.isArray(img.image) ? img.image : [img.image];
|
|
361
|
+
// Some exports hold the URL as a Markdown link to itself.
|
|
362
|
+
const src = /^\[[^\]]*\]\(\s*([^)\s]+)\s*\)$/.exec(String(raw ?? '').trim())?.[1] ?? raw;
|
|
363
|
+
if (!src) return '';
|
|
364
|
+
const parts = [`src="${attrText(src)}"`];
|
|
365
|
+
if (img.sizing && !/^(smart|auto|original|full)$/.test(img.sizing)) parts.push(`width="${attrText(img.sizing)}"`);
|
|
366
|
+
if (alt || title) parts.push(`alt="${attrText(alt || title)}"`);
|
|
367
|
+
if (img.caption) parts.push(`caption="${attrText(img.caption)}"`);
|
|
368
|
+
return `<Image ${parts.join(' ')} />`;
|
|
369
|
+
})
|
|
370
|
+
.filter(Boolean)
|
|
371
|
+
.join('\n\n');
|
|
372
|
+
case 'html':
|
|
373
|
+
return typeof data.html === 'string' ? `<HTMLBlock>{\`${data.html.replace(/`/g, '\\`').replace(/\$\{/g, '\\${')}\`}</HTMLBlock>` : '';
|
|
374
|
+
case 'parameters': {
|
|
375
|
+
const d = data.data ?? {};
|
|
376
|
+
const cols = Number(data.cols) || Object.keys(d).filter((k) => /^h-\d+$/.test(k)).length;
|
|
377
|
+
const rows = Number(data.rows) || Math.max(0, ...Object.keys(d).map((k) => Number(/^(\d+)-\d+$/.exec(k)?.[1] ?? -1) + 1));
|
|
378
|
+
if (!cols) return '';
|
|
379
|
+
const cell = (v) => String(v ?? '').trim().replace(/\|/g, '\\|').replace(/\s*\n\s*/g, '<br />');
|
|
380
|
+
const lines = [`| ${Array.from({ length: cols }, (_, c) => cell(d[`h-${c}`])).join(' | ')} |`, `| ${Array.from({ length: cols }, () => '---').join(' | ')} |`];
|
|
381
|
+
for (let r = 0; r < rows; r++) lines.push(`| ${Array.from({ length: cols }, (_, c) => cell(d[`${r}-${c}`])).join(' | ')} |`);
|
|
382
|
+
return lines.join('\n');
|
|
383
|
+
}
|
|
384
|
+
case 'callout': {
|
|
385
|
+
const theme = { info: 'info', success: 'success', warning: 'warning', danger: 'danger', error: 'danger' }[data.type] ?? 'default';
|
|
386
|
+
const head = data.title ? `### ${String(data.title).replace(/\n/g, ' ')}\n\n` : '';
|
|
387
|
+
return `<Callout theme="${theme}">\n${head}${String(data.body ?? '').trim()}\n</Callout>`;
|
|
388
|
+
}
|
|
389
|
+
case 'code':
|
|
390
|
+
return (data.codes ?? [])
|
|
391
|
+
.map((c) => {
|
|
392
|
+
const code = String(c.code ?? '');
|
|
393
|
+
const ticks = '`'.repeat(Math.max(3, ...[...code.matchAll(/`+/g)].map((m) => m[0].length + 1)));
|
|
394
|
+
const info = [c.language || 'text', c.name && c.name !== c.language ? c.name : ''].filter(Boolean).join(' ');
|
|
395
|
+
return `${ticks}${info}\n${code}\n${ticks}`;
|
|
396
|
+
})
|
|
397
|
+
.join('\n');
|
|
398
|
+
case 'api-header':
|
|
399
|
+
return data.title ? `## ${String(data.title).replace(/\n/g, ' ')}` : '';
|
|
400
|
+
case 'embed': {
|
|
401
|
+
const url = data.url || /src="([^"]+)"/.exec(data.html ?? '')?.[1];
|
|
402
|
+
return url ? embedToMdx(url, data.title, note) : '';
|
|
403
|
+
}
|
|
404
|
+
case 'tutorial-tile':
|
|
405
|
+
return data.slug ? `<TutorialTile slug="${attrText(data.slug)}" title="${attrText(data.title)}" />` : '';
|
|
406
|
+
default:
|
|
407
|
+
return null;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** Converts ReadMe's older `[block:type]{json}[/block]` syntax - on lines of
|
|
412
|
+
* its own, or on one line inside a list item - into the ReadMe MDX the
|
|
413
|
+
* rest of the conversion handles. A block whose JSON doesn't parse, or of
|
|
414
|
+
* a type with no conversion, goes in a code fence (so the page builds) and
|
|
415
|
+
* is reported. */
|
|
416
|
+
export function convertLegacyBlocks(source, note = () => {}) {
|
|
417
|
+
if (!source.includes('[block:')) return source;
|
|
418
|
+
return source.replace(/^([ \t]*)\[block:([\w-]+)\]\s*([\s\S]*?)\s*\[\/block\][ \t]*$/gm, (m, indent, type, json) => {
|
|
419
|
+
let data;
|
|
420
|
+
try {
|
|
421
|
+
data = JSON.parse(json);
|
|
422
|
+
} catch {
|
|
423
|
+
data = null;
|
|
424
|
+
}
|
|
425
|
+
let out = data ? legacyBlock(type, data, note) : null;
|
|
426
|
+
if (out === null) {
|
|
427
|
+
note('legacy-block', `A [block:${type}] in ReadMe's older syntax couldn't be converted - it's shown as a code block. Rewrite it with components.`);
|
|
428
|
+
out = `\`\`\`json block:${type}\n${json}\n\`\`\``;
|
|
429
|
+
}
|
|
430
|
+
return out
|
|
431
|
+
.split('\n')
|
|
432
|
+
.map((line) => (line ? indent + line : line))
|
|
433
|
+
.join('\n');
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
|
|
304
437
|
/** The class every converted HTML block is wrapped in - see READMEHTML_CSS. */
|
|
305
438
|
export const README_HTML_CLASS = 'readme-html';
|
|
306
439
|
|
|
@@ -317,8 +450,10 @@ export const README_HTML_CSS = `/* Written by writedocs convert --readme. The HT
|
|
|
317
450
|
}
|
|
318
451
|
`;
|
|
319
452
|
|
|
320
|
-
|
|
321
|
-
|
|
453
|
+
/** `extraClass`: ReadMe's own class for the container, when the project's
|
|
454
|
+
* CSS styles through it (`rm-LandingPage` around the landing page). */
|
|
455
|
+
export function wrapHtml(mdx, extraClass = '') {
|
|
456
|
+
return `<div className="${[README_HTML_CLASS, extraClass].filter(Boolean).join(' ')}">\n${mdx}\n</div>`;
|
|
322
457
|
}
|
|
323
458
|
|
|
324
459
|
/**
|
|
@@ -337,14 +472,7 @@ export function convertReadmeBody(body, ctx) {
|
|
|
337
472
|
const note = ctx.note ?? (() => {});
|
|
338
473
|
const glossary = ctx.glossary ?? new Map();
|
|
339
474
|
const recipes = ctx.recipes ?? new Set();
|
|
340
|
-
|
|
341
|
-
// ReadMe's older [block:type]{json}[/block] syntax isn't converted: each
|
|
342
|
-
// block goes in a code fence, so the page builds (its JSON is not MDX)
|
|
343
|
-
// and the author sees what to rewrite.
|
|
344
|
-
if (/^\[block:[\w-]+\]/m.test(source)) {
|
|
345
|
-
note('legacy-blocks', "The page uses ReadMe's older [block:...] syntax, which isn't converted - each block is shown as a code block. Rewrite them with components.");
|
|
346
|
-
source = source.replace(/^\[block:([\w-]+)\]\n([\s\S]*?)\n\[\/block\]$/gm, (m, type, json) => `\`\`\`json block:${type}\n${json}\n\`\`\``);
|
|
347
|
-
}
|
|
475
|
+
const source = convertLegacyBlocks(String(body ?? '').replace(/\r\n?/g, '\n'), note);
|
|
348
476
|
const lines = source.split('\n');
|
|
349
477
|
const segments = splitBody(convertBlockquoteCallouts(lines).join('\n'));
|
|
350
478
|
const out = [];
|
|
@@ -357,10 +485,10 @@ export function convertReadmeBody(body, ctx) {
|
|
|
357
485
|
while (segments[s + 1]?.kind === 'code') group.push(segments[++s]);
|
|
358
486
|
if (group.length === 1) out.push(...renderCode(seg, false));
|
|
359
487
|
else {
|
|
360
|
-
|
|
361
|
-
out.push(`${indent}<CodeGroup>`);
|
|
362
|
-
for (const g of group) out.push(...renderCode(g, true));
|
|
363
|
-
out.push(`${indent}</CodeGroup>`);
|
|
488
|
+
// The group takes the first fence's place - list marker included.
|
|
489
|
+
out.push(`${group[0].prefix ?? group[0].indent}<CodeGroup>`);
|
|
490
|
+
for (const g of group) out.push(...renderCode(g, true, g.indent));
|
|
491
|
+
out.push(`${group[0].indent}</CodeGroup>`);
|
|
364
492
|
}
|
|
365
493
|
continue;
|
|
366
494
|
}
|
|
@@ -435,15 +563,17 @@ function convertText(source, ctx) {
|
|
|
435
563
|
t = t.replace(/<Image\b((?:[^>"'{]|"[^"]*"|'[^']*'|\{[^}]*\})*?)\/>/g, (m, attrs) => image(attrs));
|
|
436
564
|
t = t.replace(/<Image\b((?:[^>"'{]|"[^"]*"|'[^']*'|\{[^}]*\})*?)>([\s\S]*?)<\/Image>/g, (m, attrs, child) => image(attrs, child));
|
|
437
565
|
|
|
438
|
-
// <Embed>: a card to what it embedded.
|
|
566
|
+
// <Embed>: a video, or a card to what it embedded.
|
|
439
567
|
t = t.replace(/<Embed\b([\s\S]*?)\/>/g, (m, attrs) => {
|
|
440
568
|
const a = parseAttributes(attrs);
|
|
441
569
|
const url = plain(a.url) ?? plain(a.href);
|
|
442
|
-
|
|
443
|
-
ctx.note('embed', 'An <Embed> became a card linking to what it embedded.');
|
|
444
|
-
return `<Card ${jsxAttr('title', plain(a.title) || url)} icon="external-link" href="${url}" />`;
|
|
570
|
+
return url ? embedToMdx(url, plain(a.title), ctx.note) : '';
|
|
445
571
|
});
|
|
446
572
|
|
|
573
|
+
// `<h2 id="x">Title\n</h2>`: in MDX an element whose text starts on its
|
|
574
|
+
// opening line has to end on that line too.
|
|
575
|
+
t = t.replace(/(<([a-z][a-z0-9]*)\b[^<>\n]*>[^\n]*\S)[ \t]*\n[ \t]*(<\/\2>)/g, '$1$3');
|
|
576
|
+
|
|
447
577
|
// Glossary terms.
|
|
448
578
|
const tooltip = (term) => {
|
|
449
579
|
const def = ctx.glossary.get(term.trim().toLowerCase());
|
|
@@ -475,6 +605,13 @@ function convertText(source, ctx) {
|
|
|
475
605
|
return restore(t);
|
|
476
606
|
}
|
|
477
607
|
|
|
608
|
+
// Braces in Markdown text are MDX expressions; ReadMe showed `{id}` as text
|
|
609
|
+
// (and an expression naming something undefined would fail the page), so
|
|
610
|
+
// they're escaped - all but an MDX comment, which is kept.
|
|
611
|
+
export function escapeTextBraces(text) {
|
|
612
|
+
return text.replace(/\{\/\*[\s\S]*?\*\/\}|[{}]/g, (m) => (m.length > 1 ? m : `\\${m}`));
|
|
613
|
+
}
|
|
614
|
+
|
|
478
615
|
/** Raw HTML and stray `<` in the text, made valid MDX - see the header. */
|
|
479
616
|
function fixRawHtml(text, ctx) {
|
|
480
617
|
let out = '';
|
|
@@ -482,10 +619,10 @@ function fixRawHtml(text, ctx) {
|
|
|
482
619
|
while (i < text.length) {
|
|
483
620
|
const lt = text.indexOf('<', i);
|
|
484
621
|
if (lt === -1) {
|
|
485
|
-
out += text.slice(i);
|
|
622
|
+
out += escapeTextBraces(text.slice(i));
|
|
486
623
|
break;
|
|
487
624
|
}
|
|
488
|
-
out += text.slice(i, lt);
|
|
625
|
+
out += escapeTextBraces(text.slice(i, lt));
|
|
489
626
|
if (text.startsWith('<!--', lt)) {
|
|
490
627
|
const end = text.indexOf('-->', lt + 4);
|
|
491
628
|
const body = text.slice(lt + 4, end === -1 ? text.length : end).trim().replace(/\*\//g, '* /');
|
|
@@ -503,7 +640,7 @@ function fixRawHtml(text, ctx) {
|
|
|
503
640
|
const [, closing, rawName] = tag;
|
|
504
641
|
const inner = text.slice(lt + tag[0].length, end); // attributes, and a trailing "/"
|
|
505
642
|
const name = TABLE_COMPONENTS[rawName] ?? rawName;
|
|
506
|
-
if (KNOWN_COMPONENTS.has(rawName) || isUnknownComponent(rawName, closing, inner, text, end)) {
|
|
643
|
+
if (KNOWN_COMPONENTS.has(rawName) || ctx.components?.has(rawName) || isUnknownComponent(rawName, closing, inner, text, end)) {
|
|
507
644
|
// A component: writedocs' own, or one it will report as unknown.
|
|
508
645
|
out += text.slice(lt, end + 1);
|
|
509
646
|
} else if (HTML_ELEMENTS.has(name) || name.includes('-') && /^[a-z]/.test(name) && /=/.test(inner)) {
|
|
@@ -91,7 +91,7 @@ export function convertRecipe(markdown, ctx) {
|
|
|
91
91
|
|
|
92
92
|
// The steps: split the rest of the page at its top-level headings.
|
|
93
93
|
const restText = rest
|
|
94
|
-
.map((seg) => (seg.kind === 'text' ? seg.lines.join('\n') : seg.kind === 'code' ? [seg.
|
|
94
|
+
.map((seg) => (seg.kind === 'text' ? seg.lines.join('\n') : seg.kind === 'code' ? [seg.prefix + seg.marks + seg.info, ...seg.body, seg.indent + seg.marks].join('\n') : `<HTMLBlock>{\`${seg.html}\`}</HTMLBlock>`))
|
|
95
95
|
.join('\n');
|
|
96
96
|
const steps = [];
|
|
97
97
|
const intro = [];
|