@writedocs/generator 0.11.1 → 0.13.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/astro.config.mjs CHANGED
@@ -38,6 +38,9 @@ import { writedocsTempDir, writedocsBuildStagingDir } from './src/lib/writedocs-
38
38
  import { stylesAssetFallback } from './src/lib/styles-asset-integration.js';
39
39
  import { mcpDevServer } from './src/lib/mcp-dev-integration.js';
40
40
  import { configReload } from './src/lib/config-reload-integration.js';
41
+ import { openapiReload } from './src/lib/openapi-reload-integration.js';
42
+ import { contentStoreReload } from './src/lib/content-store-reload-integration.js';
43
+ import { iconDataFromFile } from './src/lib/icon-data-dev.js';
41
44
  import { canonicalPath } from './src/lib/canonical-path.js';
42
45
  import { withBase, withoutBase } from './src/lib/base-path.js';
43
46
  import { folderAddresses } from './src/lib/folder-redirects.js';
@@ -379,6 +382,11 @@ export default defineConfig({
379
382
  mcpDevServer({ version: JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8')).version, basePath }),
380
383
  // writedocs dev: an edit to writedocs.json reloads the open tab.
381
384
  configReload({ configPath: path.join(contentDir, 'writedocs.json') }),
385
+ // writedocs dev: an edit to an OpenAPI spec regenerates its pages.
386
+ openapiReload({ contentDir, packageRoot }),
387
+ // writedocs dev, installed: a change to a page's entry (its title, an
388
+ // API page renamed) reaches the open tab.
389
+ contentStoreReload({ packageRoot }),
382
390
  ],
383
391
  output: 'static',
384
392
  // Dual Shiki themes for fenced code blocks (```) in MDX content, so
@@ -569,7 +577,10 @@ export default defineConfig({
569
577
  // Tailwind has to see the added @source when it compiles global.css.
570
578
  // mintlifyReactHooksPlugin() does for a site's .jsx/.tsx snippets what
571
579
  // remarkMintlifyReactHooks does for its MDX pages.
572
- plugins: [contentTailwindSource(), tailwindcss(), mintlifyReactHooksPlugin(contentDir)],
580
+ // iconDataFromFile() (writedocs dev only): astro-icon's ~15 MB of icon
581
+ // data read from a file rather than passed through Vite - about 5 s of
582
+ // every dev preview's first page (see src/lib/icon-data-dev.js).
583
+ plugins: [contentTailwindSource(), tailwindcss(), mintlifyReactHooksPlugin(contentDir), iconDataFromFile(writedocsTempDir(contentDir))],
573
584
  // `writedocs dev`: Vite only prepares for the browser the dependencies
574
585
  // it finds by scanning the project's own source - and when writedocs is
575
586
  // installed, its source sits in node_modules, which the scan skips. The
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedocs/generator",
3
- "version": "0.11.1",
3
+ "version": "0.13.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
@@ -1,177 +1,203 @@
1
- import { canonicalPath } from '../lib/canonical-path.js';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import { runAstro } from './run-astro.js';
5
- import { runPagefind } from './run-pagefind.js';
6
- import { preflightCheck, sameDriveCheck, writableInstallCheck } from './preflight.js';
7
- import { generateApiPages } from './generate-api-pages.js';
8
- import { writeRedirectsFile } from './write-redirects-file.js';
9
- import { rewriteRedirectPages } from './rewrite-redirect-pages.js';
10
- import { readConfigText } from '../lib/config-file.js';
11
- import { writeMcpFiles } from './write-mcp-files.js';
12
- import { pagesWithoutStyles } from './check-built-styles.js';
13
- import { writedocsBuildStagingDir } from '../lib/writedocs-temp-dir.js';
14
- import { normalizeBasePath } from '../lib/base-path.js';
15
- import { siteDirFor, moveRootFiles } from './base-path-layout.js';
16
- import { log, step, plural, duration, displayPath, formatProblems, color, CliExit } from './output.js';
17
- import { describeError, builtRoute, authorWarning, verboseLine } from './astro-output.js';
18
- import { reportApiPages } from './api-pages-output.js';
19
-
20
- export async function runBuild({ contentDir, packageRoot, verbose = false }) {
21
- // One spelling of each folder throughout - see lib/canonical-path.js.
22
- contentDir = canonicalPath(contentDir);
23
- packageRoot = canonicalPath(packageRoot);
24
- const started = Date.now();
25
- preflightCheck(contentDir);
26
- writableInstallCheck(packageRoot);
27
-
28
- // Collected while building, printed together at the end - a warning in
29
- // the middle of a spinner is easy to miss.
30
- const warnings = [];
31
- const notes = [];
32
- const seen = new Set();
33
- const addWarning = (where, message) => {
34
- const key = `${where ?? ''}\n${message}`;
35
- if (seen.has(key)) return;
36
- seen.add(key);
37
- warnings.push({ where, message });
38
- };
39
-
40
- const api = await generateApiPages({ contentDir });
41
- sameDriveCheck(contentDir, packageRoot, { generatedPages: api.groups.length > 0 });
42
- reportApiPages(api);
43
- api.warnings.forEach((message) => addWarning(null, message));
44
-
45
- const building = step('Building pages');
46
- const buildStarted = Date.now();
47
- let pages = 0;
48
- let fatal = null;
49
- const rawTail = [];
50
- const { exited } = runAstro('build', {
51
- packageRoot,
52
- contentDir,
53
- onEvent(event) {
54
- if (verbose) {
55
- const line = verboseLine(event);
56
- if (line !== null) log.line(color.dim(line));
57
- }
58
- if (event.type === 'fatal') {
59
- fatal = event.error;
60
- return;
61
- }
62
- if (event.type === 'report') {
63
- if (event.level === 'warn') addWarning(event.where, event.message);
64
- else if (event.level === 'info' && !notes.includes(event.message)) notes.push(event.message);
65
- return;
66
- }
67
- if (event.type === 'raw') {
68
- rawTail.push(event.line);
69
- if (rawTail.length > 40) rawTail.shift();
70
- return;
71
- }
72
- const route = builtRoute(event);
73
- if (route) {
74
- if (route.endsWith('.html')) pages += 1;
75
- building.update(`Building pages ${color.dim(`(${pages})`)}`);
76
- return;
77
- }
78
- const warning = authorWarning(event, contentDir, { root: packageRoot });
79
- if (warning) addWarning(null, warning);
80
- },
81
- });
82
- const code = await exited;
83
-
84
- if (fatal || code !== 0) {
85
- building.fail('Build failed');
86
- if (fatal) {
87
- const problem = describeError(fatal, contentDir, { root: packageRoot });
88
- log.line();
89
- log.line(formatProblems([{ where: problem.where, message: problem.message }]));
90
- if (problem.hint) log.line(`\n${color.dim(` Hint: ${problem.hint}`)}`);
91
- if (verbose && fatal.stack) log.line(`\n${color.dim(fatal.stack)}`);
92
- } else if (rawTail.length) {
93
- // No structured error (the worker itself crashed) - show what it printed.
94
- log.line();
95
- log.line(color.dim(rawTail.join('\n')));
96
- }
97
- log.line();
98
- log.line(color.dim('Run "writedocs validate" to list every problem in the project at once.'));
99
- throw new CliExit(1);
100
- }
101
- building.succeed(`Built ${plural(pages, 'page')} ${color.dim(`in ${duration(Date.now() - buildStarted)}`)}`);
102
-
103
- const distDir = path.join(contentDir, 'dist');
104
- // writedocs.json has been through the build's own validation by now.
105
- const siteConfig = JSON.parse(readConfigText(contentDir));
106
- // With a `basePath` ("/docs"), the site goes to dist/docs/ and only the
107
- // host's own files stay at the root of dist/ - see base-path-layout.js.
108
- // Without one, siteDir is distDir, and every step below is what it was.
109
- const basePath = normalizeBasePath(siteConfig.basePath);
110
- const siteDir = siteDirFor(distDir, basePath);
111
- // Astro just wrote its actual output to writedocsBuildStagingDir()
112
- // (astro.config.mjs's own `outDir`), not distDir directly - see that
113
- // function's own comment (writedocs-temp-dir.js) for why. fs.cpSync
114
- // (unlike the fs.rename() Astro uses internally to get *into* that
115
- // staging dir in the first place) copies across filesystem boundaries
116
- // without issue, so this is the one step that actually needs to bridge
117
- // packageRoot and contentDir potentially living on different devices.
118
- // distDir is cleared first so a rebuild doesn't leave a stale file
119
- // behind from a previous build that the new one no longer produces -
120
- // the same "the output directory reflects exactly this build, nothing
121
- // older" expectation `astro build` itself already guarantees when
122
- // writing directly into outDir.
123
- const stagingDir = writedocsBuildStagingDir(packageRoot, contentDir);
124
- fs.rmSync(distDir, { recursive: true, force: true });
125
- fs.cpSync(stagingDir, siteDir, { recursive: true });
126
- fs.rmSync(stagingDir, { recursive: true, force: true });
127
- moveRootFiles(siteDir, distDir);
128
- // Every page writedocs renders links the site's stylesheet. Builds have
129
- // come out without it on every page while reporting success (the package
130
- // folder spelled `c:`, fixed in lib/canonical-path.js) - so it's checked
131
- // here, and a build like that stops instead of being deployed unstyled.
132
- const unstyled = pagesWithoutStyles(distDir, { basePath });
133
- if (unstyled.length) {
134
- log.error(`The build produced ${plural(unstyled.length, 'page')} without the site's styles - for example ${unstyled[0]}.`);
135
- log.detail(color.dim('This is a fault in the build, not in your pages. Build again; if it happens again, report it with the output of --verbose.'));
136
- throw new CliExit(1);
137
- }
138
- // Astro's own writedocs.json `redirects` + the automatic "/" redirect only
139
- // ever produce client-side meta-refresh pages (see write-redirects-file.js)
140
- // - this turns those into real instant edge redirects on hosts that read
141
- // a `_redirects` file (Cloudflare Pages, Netlify), purely additively.
142
- writeRedirectsFile(siteDir, contentDir, { outDir: distDir, basePath });
143
- // Every other host follows Astro's redirect pages - rewritten so the
144
- // reader never sees one (rewrite-redirect-pages.js).
145
- rewriteRedirectPages(siteDir, { background: siteConfig.styles?.background?.colors });
146
- // The site's MCP server at /mcp: mcp-index.json is already in dist/ (an
147
- // Astro route); this adds the Cloudflare _worker.js that serves it - see
148
- // write-mcp-files.js for every host.
149
- const { version: writedocsVersion } = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8'));
150
- const mcp = writeMcpFiles(distDir, contentDir, writedocsVersion, { siteDir, basePath });
151
- if (mcp.written.length) notes.push(`MCP server at ${basePath}/mcp - dist/_worker.js runs it on Cloudflare; mcp-index.json holds the pages.`);
152
- if (mcp.skipped) addWarning(null, `No _worker.js for the MCP server: ${mcp.skipped}.`);
153
-
154
- const indexing = step('Indexing search');
155
- try {
156
- await runPagefind(siteDir, { packageRoot });
157
- } catch (err) {
158
- indexing.fail('Search indexing failed');
159
- log.line();
160
- log.line(color.dim(err.message));
161
- throw new CliExit(1);
162
- }
163
- indexing.succeed('Indexed search');
164
-
165
- if (warnings.length) {
166
- log.line();
167
- log.warn(plural(warnings.length, 'warning'));
168
- log.line();
169
- log.line(formatProblems(warnings));
170
- }
171
- if (notes.length) {
172
- log.line();
173
- notes.forEach((note) => log.info(note));
174
- }
175
- log.line();
176
- log.success(`Done in ${duration(Date.now() - started)} ${color.dim('-')} site written to ${color.bold(displayPath(distDir))}`);
177
- }
1
+ import { canonicalPath } from '../lib/canonical-path.js';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { runAstro } from './run-astro.js';
5
+ import { runPagefind } from './run-pagefind.js';
6
+ import { preflightCheck, sameDriveCheck, writableInstallCheck } from './preflight.js';
7
+ import { generateApiPages } from './generate-api-pages.js';
8
+ import { writeRedirectsFile } from './write-redirects-file.js';
9
+ import { rewriteRedirectPages } from './rewrite-redirect-pages.js';
10
+ import { readConfigText } from '../lib/config-file.js';
11
+ import { writeMcpFiles } from './write-mcp-files.js';
12
+ import { pagesWithoutStyles } from './check-built-styles.js';
13
+ import { writedocsBuildStagingDir, writedocsTempDir } from '../lib/writedocs-temp-dir.js';
14
+ import { drawOgImages } from './og-images.js';
15
+ import { normalizeBasePath } from '../lib/base-path.js';
16
+ import { siteDirFor, moveRootFiles } from './base-path-layout.js';
17
+ import { log, step, plural, duration, displayPath, formatProblems, color, CliExit } from './output.js';
18
+ import { describeError, builtRoute, authorWarning, verboseLine } from './astro-output.js';
19
+ import { reportApiPages } from './api-pages-output.js';
20
+
21
+ export async function runBuild({ contentDir, packageRoot, verbose = false }) {
22
+ // One spelling of each folder throughout - see lib/canonical-path.js.
23
+ contentDir = canonicalPath(contentDir);
24
+ packageRoot = canonicalPath(packageRoot);
25
+ const started = Date.now();
26
+ preflightCheck(contentDir);
27
+ writableInstallCheck(packageRoot);
28
+
29
+ // Collected while building, printed together at the end - a warning in
30
+ // the middle of a spinner is easy to miss.
31
+ const warnings = [];
32
+ const notes = [];
33
+ const seen = new Set();
34
+ const addWarning = (where, message) => {
35
+ const key = `${where ?? ''}\n${message}`;
36
+ if (seen.has(key)) return;
37
+ seen.add(key);
38
+ warnings.push({ where, message });
39
+ };
40
+
41
+ const api = await generateApiPages({ contentDir });
42
+ sameDriveCheck(contentDir, packageRoot, { generatedPages: api.groups.length > 0 });
43
+ reportApiPages(api);
44
+ api.warnings.forEach((message) => addWarning(null, message));
45
+
46
+ const building = step('Building pages');
47
+ const buildStarted = Date.now();
48
+ let pages = 0;
49
+ let fatal = null;
50
+ const rawTail = [];
51
+ // The link-preview cards: Astro's og route only writes their list here,
52
+ // and this process draws them after Astro, in parallel (og-images.js).
53
+ // Removed first, so a list from an earlier build is never drawn.
54
+ const ogCardsFile = path.join(writedocsTempDir(contentDir), 'og-cards.json');
55
+ fs.mkdirSync(path.dirname(ogCardsFile), { recursive: true });
56
+ fs.rmSync(ogCardsFile, { force: true });
57
+ const { exited } = runAstro('build', {
58
+ packageRoot,
59
+ contentDir,
60
+ env: { WRITEDOCS_OG_CARDS_FILE: ogCardsFile },
61
+ onEvent(event) {
62
+ if (verbose) {
63
+ const line = verboseLine(event);
64
+ if (line !== null) log.line(color.dim(line));
65
+ }
66
+ if (event.type === 'fatal') {
67
+ fatal = event.error;
68
+ return;
69
+ }
70
+ if (event.type === 'report') {
71
+ if (event.level === 'warn') addWarning(event.where, event.message);
72
+ else if (event.level === 'info' && !notes.includes(event.message)) notes.push(event.message);
73
+ return;
74
+ }
75
+ if (event.type === 'raw') {
76
+ rawTail.push(event.line);
77
+ if (rawTail.length > 40) rawTail.shift();
78
+ return;
79
+ }
80
+ const route = builtRoute(event);
81
+ if (route) {
82
+ if (route.endsWith('.html')) pages += 1;
83
+ building.update(`Building pages ${color.dim(`(${pages})`)}`);
84
+ return;
85
+ }
86
+ const warning = authorWarning(event, contentDir, { root: packageRoot });
87
+ if (warning) addWarning(null, warning);
88
+ },
89
+ });
90
+ const code = await exited;
91
+
92
+ if (fatal || code !== 0) {
93
+ building.fail('Build failed');
94
+ if (fatal) {
95
+ const problem = describeError(fatal, contentDir, { root: packageRoot });
96
+ log.line();
97
+ log.line(formatProblems([{ where: problem.where, message: problem.message }]));
98
+ if (problem.hint) log.line(`\n${color.dim(` Hint: ${problem.hint}`)}`);
99
+ if (verbose && fatal.stack) log.line(`\n${color.dim(fatal.stack)}`);
100
+ } else if (rawTail.length) {
101
+ // No structured error (the worker itself crashed) - show what it printed.
102
+ log.line();
103
+ log.line(color.dim(rawTail.join('\n')));
104
+ }
105
+ log.line();
106
+ log.line(color.dim('Run "writedocs validate" to list every problem in the project at once.'));
107
+ throw new CliExit(1);
108
+ }
109
+ building.succeed(`Built ${plural(pages, 'page')} ${color.dim(`in ${duration(Date.now() - buildStarted)}`)}`);
110
+
111
+ const distDir = path.join(contentDir, 'dist');
112
+ // writedocs.json has been through the build's own validation by now.
113
+ const siteConfig = JSON.parse(readConfigText(contentDir));
114
+ // With a `basePath` ("/docs"), the site goes to dist/docs/ and only the
115
+ // host's own files stay at the root of dist/ - see base-path-layout.js.
116
+ // Without one, siteDir is distDir, and every step below is what it was.
117
+ const basePath = normalizeBasePath(siteConfig.basePath);
118
+ const siteDir = siteDirFor(distDir, basePath);
119
+ // Astro just wrote its actual output to writedocsBuildStagingDir()
120
+ // (astro.config.mjs's own `outDir`), not distDir directly - see that
121
+ // function's own comment (writedocs-temp-dir.js) for why. fs.cpSync
122
+ // (unlike the fs.rename() Astro uses internally to get *into* that
123
+ // staging dir in the first place) copies across filesystem boundaries
124
+ // without issue, so this is the one step that actually needs to bridge
125
+ // packageRoot and contentDir potentially living on different devices.
126
+ // distDir is cleared first so a rebuild doesn't leave a stale file
127
+ // behind from a previous build that the new one no longer produces -
128
+ // the same "the output directory reflects exactly this build, nothing
129
+ // older" expectation `astro build` itself already guarantees when
130
+ // writing directly into outDir.
131
+ const stagingDir = writedocsBuildStagingDir(packageRoot, contentDir);
132
+ // The cards Astro's route listed, into the staging folder's og/ - the
133
+ // same files the route would have made, one thread per CPU (at most 4).
134
+ // Drawn here, before the staging folder replaces dist/: when drawing
135
+ // fails, the build stops with dist/ as it was - no dist/ at all, or the
136
+ // last good build's - the same as when Astro itself fails. Drawn after the
137
+ // copy, a failure left a dist/ with the new pages and none of their cards.
138
+ const drawing = step('Drawing link previews');
139
+ const drawStarted = Date.now();
140
+ try {
141
+ const drawn = await drawOgImages(ogCardsFile, stagingDir);
142
+ if (drawn) drawing.succeed(`Drew ${plural(drawn, 'preview image')} ${color.dim(`in ${duration(Date.now() - drawStarted)}`)}`);
143
+ else drawing.stop();
144
+ } catch (err) {
145
+ drawing.fail('Drawing the link previews failed');
146
+ log.line();
147
+ log.line(color.dim(err.message));
148
+ throw new CliExit(1);
149
+ }
150
+ fs.rmSync(distDir, { recursive: true, force: true });
151
+ fs.cpSync(stagingDir, siteDir, { recursive: true });
152
+ fs.rmSync(stagingDir, { recursive: true, force: true });
153
+ moveRootFiles(siteDir, distDir);
154
+ // Every page writedocs renders links the site's stylesheet. Builds have
155
+ // come out without it on every page while reporting success (the package
156
+ // folder spelled `c:`, fixed in lib/canonical-path.js) - so it's checked
157
+ // here, and a build like that stops instead of being deployed unstyled.
158
+ const unstyled = pagesWithoutStyles(distDir, { basePath });
159
+ if (unstyled.length) {
160
+ log.error(`The build produced ${plural(unstyled.length, 'page')} without the site's styles - for example ${unstyled[0]}.`);
161
+ log.detail(color.dim('This is a fault in the build, not in your pages. Build again; if it happens again, report it with the output of --verbose.'));
162
+ throw new CliExit(1);
163
+ }
164
+ // Astro's own writedocs.json `redirects` + the automatic "/" redirect only
165
+ // ever produce client-side meta-refresh pages (see write-redirects-file.js)
166
+ // - this turns those into real instant edge redirects on hosts that read
167
+ // a `_redirects` file (Cloudflare Pages, Netlify), purely additively.
168
+ writeRedirectsFile(siteDir, contentDir, { outDir: distDir, basePath });
169
+ // Every other host follows Astro's redirect pages - rewritten so the
170
+ // reader never sees one (rewrite-redirect-pages.js).
171
+ rewriteRedirectPages(siteDir, { background: siteConfig.styles?.background?.colors });
172
+ // The site's MCP server at /mcp: mcp-index.json is already in dist/ (an
173
+ // Astro route); this adds the Cloudflare _worker.js that serves it - see
174
+ // write-mcp-files.js for every host.
175
+ const { version: writedocsVersion } = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8'));
176
+ const mcp = writeMcpFiles(distDir, contentDir, writedocsVersion, { siteDir, basePath });
177
+ if (mcp.written.length) notes.push(`MCP server at ${basePath}/mcp - dist/_worker.js runs it on Cloudflare; mcp-index.json holds the pages.`);
178
+ if (mcp.skipped) addWarning(null, `No _worker.js for the MCP server: ${mcp.skipped}.`);
179
+
180
+ const indexing = step('Indexing search');
181
+ try {
182
+ await runPagefind(siteDir, { packageRoot });
183
+ } catch (err) {
184
+ indexing.fail('Search indexing failed');
185
+ log.line();
186
+ log.line(color.dim(err.message));
187
+ throw new CliExit(1);
188
+ }
189
+ indexing.succeed('Indexed search');
190
+
191
+ if (warnings.length) {
192
+ log.line();
193
+ log.warn(plural(warnings.length, 'warning'));
194
+ log.line();
195
+ log.line(formatProblems(warnings));
196
+ }
197
+ if (notes.length) {
198
+ log.line();
199
+ notes.forEach((note) => log.info(note));
200
+ }
201
+ log.line();
202
+ log.success(`Done in ${duration(Date.now() - started)} ${color.dim('-')} site written to ${color.bold(displayPath(distDir))}`);
203
+ }