@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.
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 config into writedocs.json")
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('--force', 'overwrite an existing writedocs.json')
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
- if (mintlify === legacy) {
296
+ const readme = options.readme;
297
+ const chosen = [mintlify, legacy, readme].filter(Boolean).length;
298
+ if (chosen !== 1) {
296
299
  log.error(
297
- mintlify
298
- ? 'Pick one: --mintlify or --writedocs.'
299
- : 'Say what to convert from: writedocs convert --mintlify [dir], or --writedocs for the previous writedocs.'
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',
@@ -343,9 +359,11 @@ program
343
359
  // is asynchronous, and `writedocs validate` with 1,000 errors reached a CI log
344
360
  // or the platform's build log with 1,198 of its 5,003 lines. exitWhenFlushed()
345
361
  // waits for stdout and stderr first (10 s at most, for a reader that stopped
346
- // reading). The exit codes are a contract with the platform: 0, 1, and 75
347
- // from requireBuildKey() (src/cli/build-auth.js), which exits on its own after
348
- // a few lines - they always fit in an empty pipe. Tested in
362
+ // reading). The exit codes are a contract with the platform: 0, 1, and 75 -
363
+ // worth trying again - from requireBuildKey() (src/cli/build-auth.js), which
364
+ // exits on its own after a few lines - they always fit in an empty pipe - and
365
+ // from the build when Pagefind leaves a search index file empty twice
366
+ // (src/cli/run-pagefind.js), through CliExit like any failed build. Tested in
349
367
  // scripts/cli-exit-flush.test.js.
350
368
  program
351
369
  .parseAsync(process.argv)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedocs/generator",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "description": "Static site generator for docs — a writedocs.json + MDX folder in, a static site out.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli/build.js CHANGED
@@ -2,7 +2,8 @@ import { canonicalPath } from '../lib/canonical-path.js';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { runAstro } from './run-astro.js';
5
- import { runPagefind } from './run-pagefind.js';
5
+ import { runPagefind, PagefindEmptyFilesError } from './run-pagefind.js';
6
+ import { EX_TEMPFAIL } from './build-auth.js';
6
7
  import { preflightCheck, sameDriveCheck, writableInstallCheck } from './preflight.js';
7
8
  import { generateApiPages } from './generate-api-pages.js';
8
9
  import { writeRedirectsFile } from './write-redirects-file.js';
@@ -215,10 +216,20 @@ export async function runBuild({ contentDir, packageRoot, verbose = false, draft
215
216
  const indexing = step('Indexing search');
216
217
  let searchSpaces = [];
217
218
  try {
218
- ({ spaces: searchSpaces } = await runPagefind(siteDir, { packageRoot }));
219
+ const search = await runPagefind(siteDir, { packageRoot });
220
+ searchSpaces = search.spaces;
221
+ if (search.rewritten) notes.push(`Search: Pagefind left ${plural(search.rewritten.length, 'index file')} empty (${search.rewritten.join(', ')}); the indexes were written again, whole.`);
219
222
  } catch (err) {
220
223
  indexing.fail('Search indexing failed');
221
224
  log.line();
225
+ // A file of the index left empty twice (run-pagefind.js): a passing
226
+ // fault, not the pages' - exit 75 (EX_TEMPFAIL), the code the WriteDocs
227
+ // platform tries a build again on, as when no key server answers.
228
+ if (err instanceof PagefindEmptyFilesError) {
229
+ log.error(`The search index is incomplete: Pagefind wrote ${plural(err.files.length, 'file')} empty, and again when written a second time - ${err.files.join(', ')}.`);
230
+ log.detail(color.dim('This is a fault on the machine running the build, not in your pages. Build again.'));
231
+ throw new CliExit(EX_TEMPFAIL);
232
+ }
222
233
  log.line(color.dim(err.message));
223
234
  throw new CliExit(1);
224
235
  }
@@ -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 = `${JSON.stringify(config, null, 2)}\n`;
76
+ const text = configText(config);
69
77
 
70
- // The result must pass writedocs' own schema - if it doesn't, that's a
71
- // converter bug, and writing it would only hand the author a broken file.
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
- if (dryRun) {
82
- process.stdout.write(text);
83
- } else {
84
- fs.writeFileSync(outPath, text);
85
- log.success(`Converted ${from.file} to ${color.bold(displayPath(outPath))}`);
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
- if (notes.length) {
89
- log.line();
90
- log.info(`${plural(notes.length, 'thing')} couldn't be carried over as-is:`);
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.line(formatNotes(notes));
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
- // The pages, checked against the converted config - what's left to fix
96
- // before the first build.
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. ${from.domainHint}`
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
  }
@@ -4,7 +4,7 @@ import SwaggerParser from '@apidevtools/swagger-parser';
4
4
  import matter from 'gray-matter';
5
5
  import { writedocsTempDir } from '../lib/writedocs-temp-dir.js';
6
6
  import { parseOpenApiRef, openApiOperationKey, specDirName } from '../lib/openapi-ref.js';
7
- import { findAllPages } from '../lib/pages.js';
7
+ import { findAllPages, projectPageIds } from '../lib/pages.js';
8
8
  import { projectIgnore } from '../lib/project-ignore.js';
9
9
  import { readConfigText } from '../lib/config-file.js';
10
10
  import { HTTP_METHODS, collectOpenApiGroups } from '../lib/openapi-spec.js';
@@ -12,6 +12,7 @@ import { operationMetaDescription, plainLine, truncateAtWord } from '../lib/meta
12
12
  import { movedApiPagesFile, untaggedRedirects } from '../lib/moved-api-pages.js';
13
13
  import { scalarReferencesFile, scalarDocumentFile } from '../lib/scalar-reference.js';
14
14
  import { scalarOperationAnchor } from '../lib/scalar-anchors.js';
15
+ import { scalarRootPathMessage, scalarPagePathMessage } from '../lib/scalar-path.js';
15
16
  import { canonicalPath } from '../lib/canonical-path.js';
16
17
 
17
18
 
@@ -253,19 +254,10 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
253
254
  }
254
255
  // Scalar's reference (lib/scalar-reference.js) is a page of its own, at the
255
256
  // group's path - which then can't be the site's root, nor a page's.
257
+ // `writedocs validate` refuses both with the same words (lib/scalar-path.js).
256
258
  const scalar = group.openapi.renderer === 'scalar';
257
- if (scalar && !pathPrefix) {
258
- throw new Error(
259
- `[writedocs] writedocs.json's "${group.group}" group has openapi.renderer "scalar" and openapi.path "${group.openapi.path}" - ` +
260
- 'the reference is a page at that path, so give it one of its own, like "/api".'
261
- );
262
- }
263
- if (scalar && pageIds.has(pathPrefix)) {
264
- throw new Error(
265
- `[writedocs] writedocs.json's "${group.group}" group has openapi.renderer "scalar" - its reference is the page at /${pathPrefix}/, ` +
266
- 'and a page of the project is already there. Move that page or give the group another openapi.path.'
267
- );
268
- }
259
+ if (scalar && !pathPrefix) throw new Error(`[writedocs] ${scalarRootPathMessage(group.group, group.openapi.path)}`);
260
+ if (scalar && pageIds.has(pathPrefix)) throw new Error(`[writedocs] ${scalarPagePathMessage(group.group, pathPrefix)}`);
269
261
 
270
262
  const spec = await dereferenceSpec(specPath, sources);
271
263
  const operations = buildOperations(spec);
@@ -438,7 +430,7 @@ export async function planApiPages({ contentDir, drafts }) {
438
430
  // Groups shown as Scalar's reference (lib/scalar-reference.js), and the
439
431
  // addresses of the project's own pages - a reference can't take one.
440
432
  const references = [];
441
- const pageIds = groups.some((g) => g.openapi.renderer === 'scalar') ? projectPageIds(contentDir, drafts) : new Set();
433
+ const pageIds = groups.some((g) => g.openapi.renderer === 'scalar') ? projectPageIds(contentDir, { drafts }) : new Set();
442
434
  for (const group of groups) {
443
435
  await generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves, files, sources, references, pageIds });
444
436
  }
@@ -459,20 +451,6 @@ export async function planApiPages({ contentDir, drafts }) {
459
451
  return { summary, files, roots };
460
452
  }
461
453
 
462
- /** The addresses (file ids) of the project's own pages: its path without the
463
- * extension or a trailing /index, or its frontmatter `slug`. */
464
- function projectPageIds(contentDir, drafts) {
465
- const ids = new Set();
466
- for (const rel of findAllPages(contentDir, { drafts })) {
467
- ids.add(rel.replace(/\.mdx?$/i, '').replace(/\/index$/, ''));
468
- try {
469
- const { data } = matter(fs.readFileSync(path.join(contentDir, rel), 'utf-8'));
470
- if (typeof data?.slug === 'string') ids.add(data.slug.replace(/^\/+|\/+$/g, ''));
471
- } catch {}
472
- }
473
- return ids;
474
- }
475
-
476
454
  /** Text for a Markdown link's label inside MDX: what MDX or Markdown would
477
455
  * read as syntax is escaped. */
478
456
  function markdownText(text) {
@@ -63,9 +63,64 @@ function resolvePagefindBin(packageRoot) {
63
63
  /**
64
64
  * Returns the ids of the search spaces it wrote, each in
65
65
  * pagefind-spaces/<id>/ - the build lists a protected one's folder in
66
- * dist/.writedocs/access.json (lib/protected-sections.js).
66
+ * dist/.writedocs/access.json (lib/protected-sections.js) - and, when the
67
+ * indexes had to be written again, `rewritten`: the files left empty the
68
+ * first time.
67
69
  */
68
- export async function runPagefind(siteDir, { packageRoot }) {
70
+ export async function runPagefind(siteDir, { packageRoot, index = writeIndexes }) {
71
+ // An index file Pagefind left empty (none is on purpose): its Node API's
72
+ // writeFiles() resolves while files are still being written, and close()
73
+ // then ends its process - in gerador/14's probe, 3 of 60 writes followed
74
+ // by close() kept a file at 0 bytes (wasm.unknown.pagefind,
75
+ // pagefind-entry.json...), which breaks that index's search without a
76
+ // word. So: written again once, and if a file is still empty, the build
77
+ // fails as a passing fault - PagefindEmptyFilesError, exit 75 (build.js).
78
+ // `index` is writeIndexes unless a test passes a stand-in.
79
+ const result = await index(siteDir, packageRoot);
80
+ const empty = emptyPagefindFiles(siteDir);
81
+ if (!empty.length) return result;
82
+ removePagefindFolders(siteDir);
83
+ const again = await index(siteDir, packageRoot);
84
+ const still = emptyPagefindFiles(siteDir);
85
+ if (still.length) throw new PagefindEmptyFilesError(still);
86
+ return { ...again, rewritten: empty };
87
+ }
88
+
89
+ /** The search indexes' folders in a built site. */
90
+ const PAGEFIND_FOLDERS = ['pagefind', 'pagefind-spaces'];
91
+
92
+ /** Every file of 0 bytes in the site's search indexes, as paths in the site
93
+ * with forward slashes. Exported for scripts/run-pagefind.test.js. */
94
+ export function emptyPagefindFiles(siteDir) {
95
+ const empty = [];
96
+ const walk = (dir) => {
97
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
98
+ const full = path.join(dir, entry.name);
99
+ if (entry.isDirectory()) walk(full);
100
+ else if (fs.statSync(full).size === 0) empty.push(path.relative(siteDir, full).split(path.sep).join('/'));
101
+ }
102
+ };
103
+ for (const folder of PAGEFIND_FOLDERS) if (fs.existsSync(path.join(siteDir, folder))) walk(path.join(siteDir, folder));
104
+ return empty.sort();
105
+ }
106
+
107
+ function removePagefindFolders(siteDir) {
108
+ for (const folder of PAGEFIND_FOLDERS) fs.rmSync(path.join(siteDir, folder), { recursive: true, force: true });
109
+ }
110
+
111
+ /** Pagefind left a file empty twice: the search index isn't whole. A fault
112
+ * of the machine or the moment, not of the pages - the build exits 75, the
113
+ * code the WriteDocs platform tries again on. */
114
+ export class PagefindEmptyFilesError extends Error {
115
+ constructor(files) {
116
+ super(`Pagefind wrote ${files.length === 1 ? 'a search index file' : `${files.length} search index files`} empty, twice: ${files.join(', ')}`);
117
+ this.files = files;
118
+ }
119
+ }
120
+
121
+ /** Writes the site's search indexes - `{ spaces }`, the ids of the search
122
+ * spaces written. */
123
+ async function writeIndexes(siteDir, packageRoot) {
69
124
  // With a hidden or protected space, or a page whose result leads elsewhere
70
125
  // - the operation page of a Scalar group, whose result is its operation in
71
126
  // the reference (lib/scalar-reference.js) - the indexes are written by