@writedocs/generator 0.20.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.
- package/bin/writedocs.js +23 -7
- package/package.json +1 -1
- package/src/cli/convert.js +120 -15
- package/src/lib/readme-convert.js +325 -0
- package/src/lib/readme-fetch.js +336 -0
- package/src/lib/readme-html.js +201 -0
- package/src/lib/readme-mdx.js +569 -0
- package/src/lib/readme-recipes.js +135 -0
- package/src/pages/[...slug].astro +60 -1
package/bin/writedocs.js
CHANGED
|
@@ -279,27 +279,43 @@ program
|
|
|
279
279
|
|
|
280
280
|
program
|
|
281
281
|
.command('convert')
|
|
282
|
-
.description("Convert another docs tool's
|
|
283
|
-
.argument('[dir]', 'project directory (contains docs.json or config.json)', '.')
|
|
282
|
+
.description("Convert another docs tool's project into a writedocs project")
|
|
283
|
+
.argument('[dir]', 'project directory (contains docs.json or config.json; with --readme, where to write the project)', '.')
|
|
284
284
|
.option('--mintlify', "convert a Mintlify project's docs.json")
|
|
285
285
|
.option('--docs.json', 'same as --mintlify')
|
|
286
286
|
.option('--writedocs', "convert a project from the previous writedocs (its config.json)")
|
|
287
287
|
.option('--config.json', 'same as --writedocs')
|
|
288
|
-
.option('--
|
|
288
|
+
.option('--readme <site>', 'convert a published ReadMe site (its address) into a new project in [dir]')
|
|
289
|
+
.option('--force', 'overwrite an existing writedocs.json (with --readme: and every file the conversion writes)')
|
|
289
290
|
.option('--dry-run', 'print the converted writedocs.json instead of writing it')
|
|
290
291
|
.action(async (dir, options) => {
|
|
291
292
|
// Commander camel-cases only on hyphens: `--docs.json` is stored under
|
|
292
293
|
// the key "docs.json", not `docsJson`.
|
|
293
294
|
const mintlify = options.mintlify || options['docs.json'];
|
|
294
295
|
const legacy = options.writedocs || options['config.json'];
|
|
295
|
-
|
|
296
|
+
const readme = options.readme;
|
|
297
|
+
const chosen = [mintlify, legacy, readme].filter(Boolean).length;
|
|
298
|
+
if (chosen !== 1) {
|
|
296
299
|
log.error(
|
|
297
|
-
|
|
298
|
-
? 'Pick one: --mintlify or --
|
|
299
|
-
: 'Say what to convert from: writedocs convert --mintlify [dir],
|
|
300
|
+
chosen
|
|
301
|
+
? 'Pick one: --mintlify, --writedocs or --readme.'
|
|
302
|
+
: 'Say what to convert from: writedocs convert --mintlify [dir], --writedocs for the previous writedocs, or --readme <site> [dir].'
|
|
300
303
|
);
|
|
301
304
|
throw new CliExit(1);
|
|
302
305
|
}
|
|
306
|
+
if (readme) {
|
|
307
|
+
if (options.dryRun) {
|
|
308
|
+
log.error('--dry-run isn\'t available with --readme - convert into an empty folder instead.');
|
|
309
|
+
throw new CliExit(1);
|
|
310
|
+
}
|
|
311
|
+
const { runReadmeConvert } = await import('../src/cli/convert.js');
|
|
312
|
+
await runReadmeConvert({
|
|
313
|
+
site: readme,
|
|
314
|
+
contentDir: canonicalPath(path.resolve(process.cwd(), dir)),
|
|
315
|
+
force: Boolean(options.force),
|
|
316
|
+
});
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
303
319
|
const { runConvert } = await import('../src/cli/convert.js');
|
|
304
320
|
await runConvert({
|
|
305
321
|
source: legacy ? 'writedocs' : 'mintlify',
|
package/package.json
CHANGED
package/src/cli/convert.js
CHANGED
|
@@ -4,10 +4,18 @@
|
|
|
4
4
|
// `writedocs validate` does. The conversions themselves are
|
|
5
5
|
// lib/mintlify-convert.js and lib/writedocs-legacy-convert.js; this file is
|
|
6
6
|
// the CLI around them.
|
|
7
|
+
//
|
|
8
|
+
// `writedocs convert --readme <site> [dir]` is different: there's no project
|
|
9
|
+
// folder to start from, only a published ReadMe site. It reads the site
|
|
10
|
+
// (lib/readme-fetch.js), converts it into a whole project - pages, OpenAPI
|
|
11
|
+
// files and writedocs.json (lib/readme-convert.js) - writes that into [dir],
|
|
12
|
+
// downloads the images ReadMe hosts, and then checks the pages the same way.
|
|
7
13
|
import fs from 'node:fs';
|
|
8
14
|
import path from 'node:path';
|
|
9
15
|
import { loadMintlifyConfig, convertMintlifyConfig, formatNotes } from '../lib/mintlify-convert.js';
|
|
10
16
|
import { loadLegacyConfig, convertLegacyConfig } from '../lib/writedocs-legacy-convert.js';
|
|
17
|
+
import { fetchReadmeSite, normalizeBaseUrl } from '../lib/readme-fetch.js';
|
|
18
|
+
import { convertReadmeSnapshot } from '../lib/readme-convert.js';
|
|
11
19
|
import { validateDocsConfig, formatValidationIssuesDetailed } from '../lib/config-schema.js';
|
|
12
20
|
import { checkContent, formatContentIssues } from '../lib/content-check.js';
|
|
13
21
|
import { log, step, plural, color, displayPath, CliExit, logToStderr } from './output.js';
|
|
@@ -65,10 +73,24 @@ export async function runConvert({ source = 'mintlify', contentDir, force = fals
|
|
|
65
73
|
}
|
|
66
74
|
|
|
67
75
|
const { config, notes } = await from.convert(input, contentDir);
|
|
68
|
-
const text =
|
|
76
|
+
const text = configText(config);
|
|
69
77
|
|
|
70
|
-
|
|
71
|
-
|
|
78
|
+
if (dryRun) {
|
|
79
|
+
process.stdout.write(text);
|
|
80
|
+
} else {
|
|
81
|
+
fs.writeFileSync(outPath, text);
|
|
82
|
+
log.success(`Converted ${from.file} to ${color.bold(displayPath(outPath))}`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
reportNotes(notes);
|
|
86
|
+
await checkPages(contentDir, text, config, from.domainHint);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** writedocs.json's text - which must pass writedocs' own schema: if it
|
|
90
|
+
* doesn't, that's a converter bug, and writing it would only hand the
|
|
91
|
+
* author a broken file. */
|
|
92
|
+
function configText(config) {
|
|
93
|
+
const text = `${JSON.stringify(config, null, 2)}\n`;
|
|
72
94
|
const result = validateDocsConfig(text);
|
|
73
95
|
if (!result.ok) {
|
|
74
96
|
log.error('The converted writedocs.json is not valid - this is a bug in the converter, please report it:');
|
|
@@ -77,23 +99,106 @@ export async function runConvert({ source = 'mintlify', contentDir, force = fals
|
|
|
77
99
|
log.line(`\n${text}`);
|
|
78
100
|
throw new CliExit(1);
|
|
79
101
|
}
|
|
102
|
+
return text;
|
|
103
|
+
}
|
|
80
104
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
105
|
+
function reportNotes(notes) {
|
|
106
|
+
if (!notes.length) return;
|
|
107
|
+
log.line();
|
|
108
|
+
log.info(`${plural(notes.length, 'thing')} couldn't be carried over as-is:`);
|
|
109
|
+
log.line();
|
|
110
|
+
log.line(formatNotes(notes));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Downloads `assets` ({ url, path }) into `contentDir`, a few at a time.
|
|
114
|
+
* Returns the ones that failed. */
|
|
115
|
+
async function downloadAssets(assets, contentDir, { fetchImpl = globalThis.fetch, concurrency = 4, onProgress } = {}) {
|
|
116
|
+
const failed = [];
|
|
117
|
+
let next = 0;
|
|
118
|
+
let done = 0;
|
|
119
|
+
const worker = async () => {
|
|
120
|
+
while (next < assets.length) {
|
|
121
|
+
const asset = assets[next++];
|
|
122
|
+
try {
|
|
123
|
+
const res = await fetchImpl(asset.url);
|
|
124
|
+
if (!res.ok) throw new Error(`answered ${res.status}`);
|
|
125
|
+
const target = path.join(contentDir, asset.path);
|
|
126
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
127
|
+
fs.writeFileSync(target, Buffer.from(await res.arrayBuffer()));
|
|
128
|
+
} catch (err) {
|
|
129
|
+
failed.push({ ...asset, error: err.message });
|
|
130
|
+
}
|
|
131
|
+
onProgress?.(++done, assets.length);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, assets.length) }, worker));
|
|
135
|
+
return failed;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function runReadmeConvert({ site, contentDir, force = false, fetchImpl }) {
|
|
139
|
+
let baseUrl;
|
|
140
|
+
try {
|
|
141
|
+
baseUrl = normalizeBaseUrl(site);
|
|
142
|
+
} catch (err) {
|
|
143
|
+
log.error(`"${site}" isn't a site address: ${err.message}`);
|
|
144
|
+
throw new CliExit(1);
|
|
145
|
+
}
|
|
146
|
+
const outPath = path.join(contentDir, 'writedocs.json');
|
|
147
|
+
if (!force && fs.existsSync(outPath)) {
|
|
148
|
+
log.error(`${displayPath(outPath)} already exists.`);
|
|
149
|
+
log.detail(color.dim('Convert into an empty folder, or pass --force to overwrite the files the conversion writes.'));
|
|
150
|
+
throw new CliExit(1);
|
|
86
151
|
}
|
|
87
152
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
153
|
+
const reading = step(`Reading ${baseUrl}`);
|
|
154
|
+
let snapshot;
|
|
155
|
+
try {
|
|
156
|
+
snapshot = await fetchReadmeSite(baseUrl, {
|
|
157
|
+
fetchImpl,
|
|
158
|
+
onProgress: ({ done, total }) => reading.update?.(`Reading ${baseUrl} - ${done} of ${total} pages`),
|
|
159
|
+
});
|
|
160
|
+
} catch (err) {
|
|
161
|
+
reading.stop();
|
|
162
|
+
log.error(`Couldn't read ${baseUrl}: ${err.message}`);
|
|
163
|
+
throw new CliExit(1);
|
|
164
|
+
}
|
|
165
|
+
reading.stop();
|
|
166
|
+
|
|
167
|
+
const { config, files, assets, notes, counts } = convertReadmeSnapshot(snapshot);
|
|
168
|
+
const text = configText(config);
|
|
169
|
+
|
|
170
|
+
fs.mkdirSync(contentDir, { recursive: true });
|
|
171
|
+
for (const file of files) {
|
|
172
|
+
const target = path.join(contentDir, file.path);
|
|
173
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
174
|
+
fs.writeFileSync(target, file.content);
|
|
175
|
+
}
|
|
176
|
+
fs.writeFileSync(outPath, text);
|
|
177
|
+
|
|
178
|
+
const downloading = step(`Downloading ${plural(assets.length, 'image')}`);
|
|
179
|
+
const failed = await downloadAssets(assets, contentDir, {
|
|
180
|
+
fetchImpl,
|
|
181
|
+
onProgress: (done, total) => downloading.update?.(`Downloading images - ${done} of ${total}`),
|
|
182
|
+
});
|
|
183
|
+
downloading.stop();
|
|
184
|
+
|
|
185
|
+
const parts = [plural(counts.pages, 'page')];
|
|
186
|
+
if (counts.endpoints) parts.push(`${counts.endpoints} of them API operations`);
|
|
187
|
+
if (counts.recipes) parts.push(plural(counts.recipes, 'recipe'));
|
|
188
|
+
log.success(`Converted ${baseUrl} into ${color.bold(displayPath(contentDir))}: ${parts.join(', ')}, ${plural(assets.length - failed.length, 'image')}`);
|
|
189
|
+
if (failed.length) {
|
|
91
190
|
log.line();
|
|
92
|
-
log.
|
|
191
|
+
log.warn(`${plural(failed.length, 'image')} couldn't be downloaded - the pages point at a file that isn't there:`);
|
|
192
|
+
for (const f of failed) log.detail(`${f.path} ${color.dim(`${f.url} (${f.error})`)}`);
|
|
93
193
|
}
|
|
94
194
|
|
|
95
|
-
|
|
96
|
-
|
|
195
|
+
reportNotes(notes);
|
|
196
|
+
await checkPages(contentDir, text, config, '(ReadMe had no custom domain set.)');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// The pages, checked against the converted config - what's left to fix
|
|
200
|
+
// before the first build.
|
|
201
|
+
async function checkPages(contentDir, text, config, domainHint) {
|
|
97
202
|
const checking = step('Checking pages');
|
|
98
203
|
const content = await checkContent(contentDir, text);
|
|
99
204
|
// The domain reminder comes once, at the end, with where the source tool
|
|
@@ -118,7 +223,7 @@ export async function runConvert({ source = 'mintlify', contentDir, force = fals
|
|
|
118
223
|
else log.success(summary);
|
|
119
224
|
if (!config.domain) {
|
|
120
225
|
log.info(
|
|
121
|
-
`Next: set "domain" in writedocs.json to your site's URL - it turns on sitemap.xml and absolute links for social previews. ${
|
|
226
|
+
`Next: set "domain" in writedocs.json to your site's URL - it turns on sitemap.xml and absolute links for social previews. ${domainHint}`
|
|
122
227
|
);
|
|
123
228
|
}
|
|
124
229
|
}
|
|
@@ -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
|
+
}
|