@writedocs/generator 0.13.4 → 0.13.5

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.
Files changed (86) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +356 -356
  4. package/package.json +99 -99
  5. package/src/cli/base-path-layout.js +44 -44
  6. package/src/cli/build-auth.js +135 -135
  7. package/src/cli/build.js +203 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +124 -124
  10. package/src/cli/dev.js +268 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +507 -507
  13. package/src/cli/og-image-worker.js +20 -20
  14. package/src/cli/og-images.js +70 -70
  15. package/src/cli/page-list-watch.js +69 -69
  16. package/src/cli/run-astro.js +97 -97
  17. package/src/cli/run-pagefind.js +154 -154
  18. package/src/cli/write-mcp-files.js +103 -103
  19. package/src/cli/write-redirects-file.js +158 -158
  20. package/src/components/ApiReferencePanel.astro +1792 -1792
  21. package/src/components/AppIcon.astro +51 -51
  22. package/src/components/Card.astro +193 -193
  23. package/src/components/CodeGroup.astro +63 -39
  24. package/src/components/CopyPageMenu.astro +374 -374
  25. package/src/components/Hint.astro +188 -188
  26. package/src/components/Icon.astro +72 -72
  27. package/src/components/Image.astro +165 -165
  28. package/src/components/Tile.astro +67 -67
  29. package/src/components/Video.astro +137 -137
  30. package/src/content.config.ts +203 -203
  31. package/src/layout/BaseLayout.astro +908 -908
  32. package/src/layout/components/AnalyticsScripts.astro +49 -49
  33. package/src/layout/components/Breadcrumbs.astro +98 -98
  34. package/src/layout/components/ConsentBanner.astro +119 -119
  35. package/src/layout/components/MobileMenu.astro +225 -225
  36. package/src/layout/components/NavTree.astro +408 -408
  37. package/src/layout/components/Sidebar.astro +232 -232
  38. package/src/layout/components/SiteFooter.astro +87 -87
  39. package/src/layout/components/TopBar.astro +386 -386
  40. package/src/layout/styles/base.css +332 -326
  41. package/src/layout/styles/mobile-menu.css +285 -285
  42. package/src/lib/agent-markdown.js +164 -164
  43. package/src/lib/asset-dimensions.js +89 -89
  44. package/src/lib/base-path.js +90 -90
  45. package/src/lib/cli-report.js +22 -22
  46. package/src/lib/code-line-numbers.js +13 -0
  47. package/src/lib/config-schema.ts +2509 -2509
  48. package/src/lib/config.ts +1316 -1316
  49. package/src/lib/consent.js +108 -108
  50. package/src/lib/content-store-reload-integration.js +101 -101
  51. package/src/lib/icon-data-dev.js +53 -53
  52. package/src/lib/image-size.js +152 -152
  53. package/src/lib/json-schema-descriptions.js +228 -228
  54. package/src/lib/link-check.js +544 -544
  55. package/src/lib/llms-index.ts +90 -90
  56. package/src/lib/mcp-dev-integration.js +65 -65
  57. package/src/lib/mcp-index.ts +102 -102
  58. package/src/lib/mintlify-convert.js +605 -605
  59. package/src/lib/moved-api-pages.js +49 -49
  60. package/src/lib/og-cards.js +33 -33
  61. package/src/lib/og-image.js +235 -235
  62. package/src/lib/openapi-dev-status.js +80 -80
  63. package/src/lib/openapi-reload-integration.js +193 -193
  64. package/src/lib/pages.js +312 -312
  65. package/src/lib/project-files-integration.js +116 -116
  66. package/src/lib/project-files.js +137 -137
  67. package/src/lib/rehype-base-path.js +62 -62
  68. package/src/lib/rehype-image-loading.js +71 -71
  69. package/src/lib/robots-txt.js +21 -21
  70. package/src/lib/search-scope.js +44 -44
  71. package/src/lib/selector-placement.js +50 -50
  72. package/src/lib/seo-tags.js +155 -155
  73. package/src/lib/shiki-code-block.js +7 -1
  74. package/src/lib/site-base.ts +27 -27
  75. package/src/lib/styles-asset-integration.js +291 -291
  76. package/src/lib/wdignore-cases.json +195 -195
  77. package/src/lib/wdignore.js +177 -177
  78. package/src/pages/404.astro +63 -63
  79. package/src/pages/[...slug].astro +1762 -1608
  80. package/src/pages/[...slug].md.ts +93 -93
  81. package/src/pages/llms-full.txt.ts +88 -88
  82. package/src/pages/og/[...slug].png.ts +63 -63
  83. package/src/scripts/mobile-menu.ts +80 -80
  84. package/src/scripts/search.ts +245 -245
  85. package/src/scripts/sidebar-scroll.ts +61 -61
  86. package/src/styles/global.css +40 -40
@@ -1,80 +1,80 @@
1
- // `writedocs dev`: what the preview knows about the OpenAPI specs between one
2
- // regeneration and the next - the files to watch, and a spec that stopped
3
- // parsing. Kept in a file in the project's temp folder, because three places
4
- // need it: cli/dev.js writes it after the first generateApiPages(),
5
- // lib/openapi-reload-integration.js after each regeneration (and reads it when
6
- // the preview restarts), and every page reads it when it renders.
7
- //
8
- // A spec that doesn't parse: generateApiPages() writes nothing, so the API
9
- // pages stay those of the last version that parsed, and every page throws
10
- // the error instead of rendering (throwIfOpenApiProblem(), called from
11
- // src/pages/[...slug].astro) - Astro shows it as it shows a broken page or a
12
- // broken writedocs.json, until the spec parses again.
13
- //
14
- // Only `writedocs dev` reads or writes it: a build never looks.
15
- //
16
- // Plain JavaScript: the integration and cli/dev.js run under plain Node.
17
- import fs from 'node:fs';
18
- import path from 'node:path';
19
- import { writedocsTempDir } from './writedocs-temp-dir.js';
20
-
21
- const stateFile = (contentDir) => path.join(writedocsTempDir(contentDir), 'dev-openapi.json');
22
-
23
- /** `{ sources: [absolute paths], problem: null | specProblem() }` - empty
24
- * when nothing was written yet. */
25
- export function readDevOpenApiState(contentDir) {
26
- try {
27
- const state = JSON.parse(fs.readFileSync(stateFile(contentDir), 'utf-8'));
28
- return { sources: Array.isArray(state.sources) ? state.sources : [], problem: state.problem ?? null };
29
- } catch {
30
- return { sources: [], problem: null };
31
- }
32
- }
33
-
34
- export function writeDevOpenApiState(contentDir, { sources, problem }) {
35
- const file = stateFile(contentDir);
36
- fs.mkdirSync(path.dirname(file), { recursive: true });
37
- fs.writeFileSync(file, JSON.stringify({ sources, problem: problem ?? null }, null, 2));
38
- }
39
-
40
- /** A generateApiPages() failure, for the terminal and the page: the file it
41
- * is about (absolute, or null), where in it ("openapi.yaml:12:5", relative
42
- * to the project), and the message without the parser's "Error parsing
43
- * <file>:" prefix and code frame. */
44
- export function specProblem(err, contentDir) {
45
- const firstLine = String(err?.message ?? err).split('\n')[0];
46
- let message = firstLine.replace(/^\[writedocs\]\s*/, '');
47
- let file = typeof err?.source === 'string' && err.source ? path.resolve(err.source) : null;
48
- let line = null;
49
- let column = null;
50
- // swagger-parser: "Error parsing <file>: <reason> (12:5)" and "Error
51
- // opening file <file>: ENOENT: ..." - the file is err.source.
52
- const parsing = message.match(/^Error (?:parsing|opening file) .+?: (.*)$/);
53
- if (parsing) message = parsing[1];
54
- if (err?.ioErrorCode === 'ENOENT' || /^ENOENT\b/.test(message)) message = "This file doesn't exist - a $ref points to it.";
55
- const pos = message.match(/\s*\((\d+):(\d+)\)\s*$/);
56
- if (pos) {
57
- line = Number(pos[1]);
58
- column = Number(pos[2]);
59
- message = message.slice(0, pos.index);
60
- }
61
- // Errors about writedocs.json's openapi groups (a missing spec, two
62
- // groups on one path) name no spec file - they're about writedocs.json.
63
- if (!file && /writedocs\.json/.test(message)) file = path.join(contentDir, 'writedocs.json');
64
- const rel = file ? path.relative(contentDir, file).split(path.sep).join('/') : null;
65
- const where = rel ? `${rel}${line ? `:${line}${column ? `:${column}` : ''}` : ''}` : null;
66
- return { file, line, column, where, message: message.trim() || 'The OpenAPI spec could not be read.' };
67
- }
68
-
69
- /** The error a page throws while a spec doesn't parse - nothing otherwise,
70
- * and nothing outside `writedocs dev`. */
71
- export function throwIfOpenApiProblem(contentDir) {
72
- if (process.env.WRITEDOCS_COMMAND !== 'dev') return;
73
- const { problem } = readDevOpenApiState(contentDir);
74
- if (!problem) return;
75
- const err = new Error(problem.where ? `${problem.where} ${problem.message}` : problem.message);
76
- err.name = 'OpenAPIError';
77
- err.hint = "The OpenAPI spec can't be read, so the API pages show the last version that could. Fix the spec and the preview reloads by itself.";
78
- if (problem.file) err.loc = { file: problem.file, line: problem.line ?? undefined, column: problem.column ?? undefined };
79
- throw err;
80
- }
1
+ // `writedocs dev`: what the preview knows about the OpenAPI specs between one
2
+ // regeneration and the next - the files to watch, and a spec that stopped
3
+ // parsing. Kept in a file in the project's temp folder, because three places
4
+ // need it: cli/dev.js writes it after the first generateApiPages(),
5
+ // lib/openapi-reload-integration.js after each regeneration (and reads it when
6
+ // the preview restarts), and every page reads it when it renders.
7
+ //
8
+ // A spec that doesn't parse: generateApiPages() writes nothing, so the API
9
+ // pages stay those of the last version that parsed, and every page throws
10
+ // the error instead of rendering (throwIfOpenApiProblem(), called from
11
+ // src/pages/[...slug].astro) - Astro shows it as it shows a broken page or a
12
+ // broken writedocs.json, until the spec parses again.
13
+ //
14
+ // Only `writedocs dev` reads or writes it: a build never looks.
15
+ //
16
+ // Plain JavaScript: the integration and cli/dev.js run under plain Node.
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { writedocsTempDir } from './writedocs-temp-dir.js';
20
+
21
+ const stateFile = (contentDir) => path.join(writedocsTempDir(contentDir), 'dev-openapi.json');
22
+
23
+ /** `{ sources: [absolute paths], problem: null | specProblem() }` - empty
24
+ * when nothing was written yet. */
25
+ export function readDevOpenApiState(contentDir) {
26
+ try {
27
+ const state = JSON.parse(fs.readFileSync(stateFile(contentDir), 'utf-8'));
28
+ return { sources: Array.isArray(state.sources) ? state.sources : [], problem: state.problem ?? null };
29
+ } catch {
30
+ return { sources: [], problem: null };
31
+ }
32
+ }
33
+
34
+ export function writeDevOpenApiState(contentDir, { sources, problem }) {
35
+ const file = stateFile(contentDir);
36
+ fs.mkdirSync(path.dirname(file), { recursive: true });
37
+ fs.writeFileSync(file, JSON.stringify({ sources, problem: problem ?? null }, null, 2));
38
+ }
39
+
40
+ /** A generateApiPages() failure, for the terminal and the page: the file it
41
+ * is about (absolute, or null), where in it ("openapi.yaml:12:5", relative
42
+ * to the project), and the message without the parser's "Error parsing
43
+ * <file>:" prefix and code frame. */
44
+ export function specProblem(err, contentDir) {
45
+ const firstLine = String(err?.message ?? err).split('\n')[0];
46
+ let message = firstLine.replace(/^\[writedocs\]\s*/, '');
47
+ let file = typeof err?.source === 'string' && err.source ? path.resolve(err.source) : null;
48
+ let line = null;
49
+ let column = null;
50
+ // swagger-parser: "Error parsing <file>: <reason> (12:5)" and "Error
51
+ // opening file <file>: ENOENT: ..." - the file is err.source.
52
+ const parsing = message.match(/^Error (?:parsing|opening file) .+?: (.*)$/);
53
+ if (parsing) message = parsing[1];
54
+ if (err?.ioErrorCode === 'ENOENT' || /^ENOENT\b/.test(message)) message = "This file doesn't exist - a $ref points to it.";
55
+ const pos = message.match(/\s*\((\d+):(\d+)\)\s*$/);
56
+ if (pos) {
57
+ line = Number(pos[1]);
58
+ column = Number(pos[2]);
59
+ message = message.slice(0, pos.index);
60
+ }
61
+ // Errors about writedocs.json's openapi groups (a missing spec, two
62
+ // groups on one path) name no spec file - they're about writedocs.json.
63
+ if (!file && /writedocs\.json/.test(message)) file = path.join(contentDir, 'writedocs.json');
64
+ const rel = file ? path.relative(contentDir, file).split(path.sep).join('/') : null;
65
+ const where = rel ? `${rel}${line ? `:${line}${column ? `:${column}` : ''}` : ''}` : null;
66
+ return { file, line, column, where, message: message.trim() || 'The OpenAPI spec could not be read.' };
67
+ }
68
+
69
+ /** The error a page throws while a spec doesn't parse - nothing otherwise,
70
+ * and nothing outside `writedocs dev`. */
71
+ export function throwIfOpenApiProblem(contentDir) {
72
+ if (process.env.WRITEDOCS_COMMAND !== 'dev') return;
73
+ const { problem } = readDevOpenApiState(contentDir);
74
+ if (!problem) return;
75
+ const err = new Error(problem.where ? `${problem.where} ${problem.message}` : problem.message);
76
+ err.name = 'OpenAPIError';
77
+ err.hint = "The OpenAPI spec can't be read, so the API pages show the last version that could. Fix the spec and the preview reloads by itself.";
78
+ if (problem.file) err.loc = { file: problem.file, line: problem.line ?? undefined, column: problem.column ?? undefined };
79
+ throw err;
80
+ }
@@ -1,193 +1,193 @@
1
- // `writedocs dev`: an edit to an OpenAPI spec shows up in the preview.
2
- // generateApiPages() runs once before the preview starts (cli/dev.js); this
3
- // watches every file it read - each spec writedocs.json's navigation mounts,
4
- // each spec a page names (Mintlify's "spec.json GET /x") and each file a $ref
5
- // points into - and runs it again when one of them changes, or when an edit
6
- // to writedocs.json changes which spec is mounted where.
7
- //
8
- // A regeneration writes in two steps (writeInTwoSteps()), so the navigation
9
- // never names a page Astro doesn't have yet. The navigation comes from the
10
- // manifest, read on every request; a page is an entry in Astro's content
11
- // store, which only changes when the generated-docs/ collection is synced
12
- // again (refreshContent() - content.config.ts doesn't give that collection
13
- // a watcher of its own, so nothing syncs it halfway). First the pages added
14
- // or changed, then a sync; then the manifest, the operation JSON and the
15
- // removal of what went, and a sync if pages went.
16
- //
17
- // What reloads the open tab: when pages were added, changed or removed, once
18
- // the last sync is done this hands Astro its store's change event
19
- // (contentStoreChanged(), lib/content-store-reload-integration.js) - Astro
20
- // re-reads the store, clears its routes and reloads the tab. Left to the
21
- // file watcher, that event came at the first save of the store, which can
22
- // be before the sync ends: the tab reloaded halfway, and nothing reloaded it
23
- // again. When only what pages read as they render changed - the operation
24
- // JSON, the manifest - there's nothing for Astro to re-read: this sends the
25
- // reload.
26
- //
27
- // A spec that doesn't parse leaves the last pages that worked in place
28
- // (nothing is written then): the error goes to the terminal, and every page
29
- // shows it until the spec parses again - see lib/openapi-dev-status.js.
30
- import path from 'node:path';
31
- import { planApiPages, writeGeneratedFiles } from '../cli/generate-api-pages.js';
32
- import { collectOpenApiGroups } from './openapi-spec.js';
33
- import { readConfigText } from './config-file.js';
34
- import { writedocsTempDir } from './writedocs-temp-dir.js';
35
- import { report } from './cli-report.js';
36
- import { readDevOpenApiState, writeDevOpenApiState, specProblem } from './openapi-dev-status.js';
37
- import { contentStoreChanged } from './content-store-reload-integration.js';
38
-
39
- /** Wait this long after the last change before regenerating - an editor's
40
- * save can arrive as more than one write. */
41
- export const REGENERATE_DELAY_MS = 200;
42
-
43
- /** Which spec writedocs.json mounts at which path, as one string - null when
44
- * the file doesn't parse (the preview reports that itself). */
45
- export function openApiMounts(configText) {
46
- try {
47
- const groups = collectOpenApiGroups(JSON.parse(configText).navigation);
48
- return JSON.stringify(groups.map((group) => [group.openapi.src, group.openapi.path]));
49
- } catch {
50
- return null;
51
- }
52
- }
53
-
54
- function mountedSpecs(contentDir) {
55
- try {
56
- return collectOpenApiGroups(JSON.parse(readConfigText(contentDir)).navigation).map((group) => path.resolve(contentDir, group.openapi.src));
57
- } catch {
58
- return [];
59
- }
60
- }
61
-
62
- const sameFileKey = (file) => (process.platform === 'win32' ? path.resolve(file).toLowerCase() : path.resolve(file));
63
-
64
- /** The watching itself, apart from Vite. `changed(file)` is called for every
65
- * file that changed; when it's a watched spec, or writedocs.json with
66
- * different mounts, `regenerate()` runs after `delayMs` - one run at a time,
67
- * and once more if something changed during one. `onDone({ ok, result })`
68
- * or `onDone({ ok: false, error })` follows each run. `files()` is what to
69
- * watch: the specs generateApiPages() last read (`sources` at first), and
70
- * the specs writedocs.json mounts even when they don't parse. */
71
- export function createSpecWatch({ contentDir, sources = [], regenerate, onDone, delayMs = REGENERATE_DELAY_MS }) {
72
- const configKey = sameFileKey(path.join(contentDir, 'writedocs.json'));
73
- let watched = new Map();
74
- const watch = (files) => {
75
- watched = new Map([...files, ...mountedSpecs(contentDir)].map((file) => [sameFileKey(file), path.resolve(file)]));
76
- };
77
- watch(sources);
78
- let mounts = openApiMounts(readConfigTextOrEmpty(contentDir));
79
- let timer = null;
80
- let running = null;
81
- let again = false;
82
-
83
- async function run() {
84
- timer = null;
85
- if (running) {
86
- again = true;
87
- return;
88
- }
89
- running = (async () => {
90
- try {
91
- const result = await regenerate();
92
- watch(result.sources);
93
- await onDone({ ok: true, result });
94
- } catch (error) {
95
- watch([...watched.values(), ...(typeof error?.source === 'string' ? [error.source] : [])]);
96
- await onDone({ ok: false, error });
97
- }
98
- })();
99
- await running;
100
- running = null;
101
- if (again) {
102
- again = false;
103
- schedule();
104
- }
105
- }
106
- function schedule() {
107
- clearTimeout(timer);
108
- timer = setTimeout(run, delayMs);
109
- }
110
- return {
111
- files: () => [...watched.values()],
112
- changed(file) {
113
- const key = sameFileKey(file);
114
- if (key === configKey) {
115
- const next = openApiMounts(readConfigTextOrEmpty(contentDir));
116
- if (next === null || next === mounts) return false;
117
- mounts = next;
118
- } else if (!watched.has(key)) {
119
- return false;
120
- }
121
- schedule();
122
- return true;
123
- },
124
- /** Resolves when no run is waiting or under way (for tests). */
125
- async idle() {
126
- while (timer || running) await (running ?? new Promise((r) => setTimeout(r, delayMs)));
127
- },
128
- close() {
129
- clearTimeout(timer);
130
- timer = null;
131
- },
132
- };
133
- }
134
-
135
- function readConfigTextOrEmpty(contentDir) {
136
- try {
137
- return readConfigText(contentDir);
138
- } catch {
139
- return '';
140
- }
141
- }
142
-
143
- /** generateApiPages() for a running preview: the same files, written in two
144
- * steps with `refresh()` - a sync of the generated-docs/ collection - after
145
- * each step that changed pages (see the top of this file). Returns what
146
- * generateApiPages() returns. */
147
- export async function writeInTwoSteps({ contentDir, refresh }) {
148
- const { summary, files, roots } = await planApiPages({ contentDir });
149
- const isPage = (file) => file.startsWith(roots[0] + path.sep);
150
- const pages = files && new Map([...files].filter(([file]) => isPage(file)));
151
- const first = writeGeneratedFiles([], pages);
152
- if (first.written.length) await refresh();
153
- const second = writeGeneratedFiles(roots, files, { keepEmptyFolders: true });
154
- if (second.removed.some(isPage)) await refresh();
155
- return { ...summary, written: [...first.written, ...second.written], removed: second.removed };
156
- }
157
-
158
- export function openapiReload({ contentDir, packageRoot }) {
159
- return {
160
- name: 'writedocs-openapi-reload',
161
- hooks: {
162
- 'astro:server:setup': ({ server, refreshContent }) => {
163
- const generatedDocsDir = path.join(writedocsTempDir(contentDir), 'generated-docs');
164
- const isPage = (file) => file.startsWith(generatedDocsDir + path.sep);
165
- const reload = () => server.ws.send({ type: 'full-reload', path: '*' });
166
- // The loader's name: content.config.ts's generatedDocs collection.
167
- const refresh = () => refreshContent?.({ loaders: ['glob-loader'] });
168
- const watch = createSpecWatch({
169
- contentDir,
170
- sources: readDevOpenApiState(contentDir).sources,
171
- regenerate: () => writeInTwoSteps({ contentDir, refresh }),
172
- onDone: async ({ ok, result, error }) => {
173
- for (const file of watch.files()) server.watcher.add(file);
174
- if (!ok) {
175
- const problem = specProblem(error, contentDir);
176
- writeDevOpenApiState(contentDir, { sources: watch.files(), problem });
177
- report('error', problem.message, problem.where);
178
- reload();
179
- return;
180
- }
181
- writeDevOpenApiState(contentDir, { sources: result.sources, problem: null });
182
- result.warnings.forEach((message) => report('warn', message));
183
- if ([...result.written, ...result.removed].some(isPage)) contentStoreChanged(server, packageRoot);
184
- else reload();
185
- },
186
- });
187
- for (const file of watch.files()) server.watcher.add(file);
188
- for (const event of ['add', 'change', 'unlink']) server.watcher.on(event, (file) => watch.changed(file));
189
- server.httpServer?.once('close', () => watch.close());
190
- },
191
- },
192
- };
193
- }
1
+ // `writedocs dev`: an edit to an OpenAPI spec shows up in the preview.
2
+ // generateApiPages() runs once before the preview starts (cli/dev.js); this
3
+ // watches every file it read - each spec writedocs.json's navigation mounts,
4
+ // each spec a page names (Mintlify's "spec.json GET /x") and each file a $ref
5
+ // points into - and runs it again when one of them changes, or when an edit
6
+ // to writedocs.json changes which spec is mounted where.
7
+ //
8
+ // A regeneration writes in two steps (writeInTwoSteps()), so the navigation
9
+ // never names a page Astro doesn't have yet. The navigation comes from the
10
+ // manifest, read on every request; a page is an entry in Astro's content
11
+ // store, which only changes when the generated-docs/ collection is synced
12
+ // again (refreshContent() - content.config.ts doesn't give that collection
13
+ // a watcher of its own, so nothing syncs it halfway). First the pages added
14
+ // or changed, then a sync; then the manifest, the operation JSON and the
15
+ // removal of what went, and a sync if pages went.
16
+ //
17
+ // What reloads the open tab: when pages were added, changed or removed, once
18
+ // the last sync is done this hands Astro its store's change event
19
+ // (contentStoreChanged(), lib/content-store-reload-integration.js) - Astro
20
+ // re-reads the store, clears its routes and reloads the tab. Left to the
21
+ // file watcher, that event came at the first save of the store, which can
22
+ // be before the sync ends: the tab reloaded halfway, and nothing reloaded it
23
+ // again. When only what pages read as they render changed - the operation
24
+ // JSON, the manifest - there's nothing for Astro to re-read: this sends the
25
+ // reload.
26
+ //
27
+ // A spec that doesn't parse leaves the last pages that worked in place
28
+ // (nothing is written then): the error goes to the terminal, and every page
29
+ // shows it until the spec parses again - see lib/openapi-dev-status.js.
30
+ import path from 'node:path';
31
+ import { planApiPages, writeGeneratedFiles } from '../cli/generate-api-pages.js';
32
+ import { collectOpenApiGroups } from './openapi-spec.js';
33
+ import { readConfigText } from './config-file.js';
34
+ import { writedocsTempDir } from './writedocs-temp-dir.js';
35
+ import { report } from './cli-report.js';
36
+ import { readDevOpenApiState, writeDevOpenApiState, specProblem } from './openapi-dev-status.js';
37
+ import { contentStoreChanged } from './content-store-reload-integration.js';
38
+
39
+ /** Wait this long after the last change before regenerating - an editor's
40
+ * save can arrive as more than one write. */
41
+ export const REGENERATE_DELAY_MS = 200;
42
+
43
+ /** Which spec writedocs.json mounts at which path, as one string - null when
44
+ * the file doesn't parse (the preview reports that itself). */
45
+ export function openApiMounts(configText) {
46
+ try {
47
+ const groups = collectOpenApiGroups(JSON.parse(configText).navigation);
48
+ return JSON.stringify(groups.map((group) => [group.openapi.src, group.openapi.path]));
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ function mountedSpecs(contentDir) {
55
+ try {
56
+ return collectOpenApiGroups(JSON.parse(readConfigText(contentDir)).navigation).map((group) => path.resolve(contentDir, group.openapi.src));
57
+ } catch {
58
+ return [];
59
+ }
60
+ }
61
+
62
+ const sameFileKey = (file) => (process.platform === 'win32' ? path.resolve(file).toLowerCase() : path.resolve(file));
63
+
64
+ /** The watching itself, apart from Vite. `changed(file)` is called for every
65
+ * file that changed; when it's a watched spec, or writedocs.json with
66
+ * different mounts, `regenerate()` runs after `delayMs` - one run at a time,
67
+ * and once more if something changed during one. `onDone({ ok, result })`
68
+ * or `onDone({ ok: false, error })` follows each run. `files()` is what to
69
+ * watch: the specs generateApiPages() last read (`sources` at first), and
70
+ * the specs writedocs.json mounts even when they don't parse. */
71
+ export function createSpecWatch({ contentDir, sources = [], regenerate, onDone, delayMs = REGENERATE_DELAY_MS }) {
72
+ const configKey = sameFileKey(path.join(contentDir, 'writedocs.json'));
73
+ let watched = new Map();
74
+ const watch = (files) => {
75
+ watched = new Map([...files, ...mountedSpecs(contentDir)].map((file) => [sameFileKey(file), path.resolve(file)]));
76
+ };
77
+ watch(sources);
78
+ let mounts = openApiMounts(readConfigTextOrEmpty(contentDir));
79
+ let timer = null;
80
+ let running = null;
81
+ let again = false;
82
+
83
+ async function run() {
84
+ timer = null;
85
+ if (running) {
86
+ again = true;
87
+ return;
88
+ }
89
+ running = (async () => {
90
+ try {
91
+ const result = await regenerate();
92
+ watch(result.sources);
93
+ await onDone({ ok: true, result });
94
+ } catch (error) {
95
+ watch([...watched.values(), ...(typeof error?.source === 'string' ? [error.source] : [])]);
96
+ await onDone({ ok: false, error });
97
+ }
98
+ })();
99
+ await running;
100
+ running = null;
101
+ if (again) {
102
+ again = false;
103
+ schedule();
104
+ }
105
+ }
106
+ function schedule() {
107
+ clearTimeout(timer);
108
+ timer = setTimeout(run, delayMs);
109
+ }
110
+ return {
111
+ files: () => [...watched.values()],
112
+ changed(file) {
113
+ const key = sameFileKey(file);
114
+ if (key === configKey) {
115
+ const next = openApiMounts(readConfigTextOrEmpty(contentDir));
116
+ if (next === null || next === mounts) return false;
117
+ mounts = next;
118
+ } else if (!watched.has(key)) {
119
+ return false;
120
+ }
121
+ schedule();
122
+ return true;
123
+ },
124
+ /** Resolves when no run is waiting or under way (for tests). */
125
+ async idle() {
126
+ while (timer || running) await (running ?? new Promise((r) => setTimeout(r, delayMs)));
127
+ },
128
+ close() {
129
+ clearTimeout(timer);
130
+ timer = null;
131
+ },
132
+ };
133
+ }
134
+
135
+ function readConfigTextOrEmpty(contentDir) {
136
+ try {
137
+ return readConfigText(contentDir);
138
+ } catch {
139
+ return '';
140
+ }
141
+ }
142
+
143
+ /** generateApiPages() for a running preview: the same files, written in two
144
+ * steps with `refresh()` - a sync of the generated-docs/ collection - after
145
+ * each step that changed pages (see the top of this file). Returns what
146
+ * generateApiPages() returns. */
147
+ export async function writeInTwoSteps({ contentDir, refresh }) {
148
+ const { summary, files, roots } = await planApiPages({ contentDir });
149
+ const isPage = (file) => file.startsWith(roots[0] + path.sep);
150
+ const pages = files && new Map([...files].filter(([file]) => isPage(file)));
151
+ const first = writeGeneratedFiles([], pages);
152
+ if (first.written.length) await refresh();
153
+ const second = writeGeneratedFiles(roots, files, { keepEmptyFolders: true });
154
+ if (second.removed.some(isPage)) await refresh();
155
+ return { ...summary, written: [...first.written, ...second.written], removed: second.removed };
156
+ }
157
+
158
+ export function openapiReload({ contentDir, packageRoot }) {
159
+ return {
160
+ name: 'writedocs-openapi-reload',
161
+ hooks: {
162
+ 'astro:server:setup': ({ server, refreshContent }) => {
163
+ const generatedDocsDir = path.join(writedocsTempDir(contentDir), 'generated-docs');
164
+ const isPage = (file) => file.startsWith(generatedDocsDir + path.sep);
165
+ const reload = () => server.ws.send({ type: 'full-reload', path: '*' });
166
+ // The loader's name: content.config.ts's generatedDocs collection.
167
+ const refresh = () => refreshContent?.({ loaders: ['glob-loader'] });
168
+ const watch = createSpecWatch({
169
+ contentDir,
170
+ sources: readDevOpenApiState(contentDir).sources,
171
+ regenerate: () => writeInTwoSteps({ contentDir, refresh }),
172
+ onDone: async ({ ok, result, error }) => {
173
+ for (const file of watch.files()) server.watcher.add(file);
174
+ if (!ok) {
175
+ const problem = specProblem(error, contentDir);
176
+ writeDevOpenApiState(contentDir, { sources: watch.files(), problem });
177
+ report('error', problem.message, problem.where);
178
+ reload();
179
+ return;
180
+ }
181
+ writeDevOpenApiState(contentDir, { sources: result.sources, problem: null });
182
+ result.warnings.forEach((message) => report('warn', message));
183
+ if ([...result.written, ...result.removed].some(isPage)) contentStoreChanged(server, packageRoot);
184
+ else reload();
185
+ },
186
+ });
187
+ for (const file of watch.files()) server.watcher.add(file);
188
+ for (const event of ['add', 'change', 'unlink']) server.watcher.on(event, (file) => watch.changed(file));
189
+ server.httpServer?.once('close', () => watch.close());
190
+ },
191
+ },
192
+ };
193
+ }