@writedocs/generator 0.10.19 → 0.11.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.
Files changed (59) hide show
  1. package/astro.config.mjs +32 -8
  2. package/package.json +96 -93
  3. package/src/cli/base-path-layout.js +44 -0
  4. package/src/cli/build.js +177 -168
  5. package/src/cli/check-built-styles.js +41 -33
  6. package/src/cli/dev.js +261 -244
  7. package/src/cli/generate-api-pages.js +9 -5
  8. package/src/cli/page-list-watch.js +69 -66
  9. package/src/cli/run-pagefind.js +154 -148
  10. package/src/cli/write-mcp-files.js +103 -96
  11. package/src/cli/write-redirects-file.js +25 -8
  12. package/src/components/AppIcon.astro +51 -50
  13. package/src/components/Card.astro +193 -192
  14. package/src/components/CopyPageMenu.astro +374 -370
  15. package/src/components/Hint.astro +188 -187
  16. package/src/components/Icon.astro +72 -71
  17. package/src/components/Image.astro +165 -164
  18. package/src/components/Tile.astro +67 -66
  19. package/src/components/Video.astro +137 -136
  20. package/src/layout/BaseLayout.astro +21 -12
  21. package/src/layout/components/AnalyticsScripts.astro +6 -2
  22. package/src/layout/components/Breadcrumbs.astro +98 -97
  23. package/src/layout/components/ConsentBanner.astro +119 -118
  24. package/src/layout/components/MobileMenu.astro +229 -228
  25. package/src/layout/components/NavTree.astro +393 -392
  26. package/src/layout/components/Sidebar.astro +232 -231
  27. package/src/layout/components/SiteFooter.astro +87 -86
  28. package/src/layout/components/TopBar.astro +386 -385
  29. package/src/lib/agent-markdown.js +164 -162
  30. package/src/lib/asset-dimensions.js +89 -0
  31. package/src/lib/base-path.js +90 -0
  32. package/src/lib/config-schema.js +10 -0
  33. package/src/lib/config-schema.ts +17 -0
  34. package/src/lib/config.ts +1314 -1289
  35. package/src/lib/consent.js +108 -102
  36. package/src/lib/image-size.js +152 -140
  37. package/src/lib/json-schema-descriptions.js +1 -0
  38. package/src/lib/link-check.js +42 -4
  39. package/src/lib/llms-index.ts +90 -88
  40. package/src/lib/mcp-dev-integration.js +65 -60
  41. package/src/lib/mcp-index.ts +102 -101
  42. package/src/lib/pages.js +312 -304
  43. package/src/lib/project-files-integration.js +116 -61
  44. package/src/lib/project-files.js +137 -126
  45. package/src/lib/project-ignore.js +46 -0
  46. package/src/lib/rehype-base-path.js +62 -0
  47. package/src/lib/rehype-image-loading.js +71 -71
  48. package/src/lib/robots-txt.js +21 -16
  49. package/src/lib/seo-tags.js +155 -140
  50. package/src/lib/site-base.ts +27 -0
  51. package/src/lib/styles-asset-integration.js +58 -12
  52. package/src/lib/wdignore-cases.json +195 -0
  53. package/src/lib/wdignore.js +177 -0
  54. package/src/pages/404.astro +63 -62
  55. package/src/pages/[...slug].astro +1604 -1597
  56. package/src/pages/[...slug].md.ts +93 -93
  57. package/src/pages/llms-full.txt.ts +88 -86
  58. package/src/scripts/search.ts +241 -237
  59. package/writedocs.schema.json +6 -0
package/src/lib/pages.js CHANGED
@@ -1,304 +1,312 @@
1
- // Which files in a content directory are pages. Plain JavaScript, not
2
- // TypeScript, so `writedocs validate` can load it with plain Node (Node
3
- // refuses to strip types under node_modules - see lib/icons.js's comment);
4
- // lib/config.ts re-exports findAllPages() for everything inside Astro.
5
- import fs from 'node:fs';
6
- import path from 'node:path';
7
- import matter from 'gray-matter';
8
- import { readConfigText } from './config-file.js';
9
- import { oncePerBuild } from './build-memo.js';
10
-
11
- // Top-level folders of a content directory that are never scanned for
12
- // pages - build output, dependencies, and static assets. Any folder whose
13
- // name starts with a dot (.git, .github, .claude, .mintlify, ...) is
14
- // skipped too, at any depth - see findAllPages().
15
- export const EXCLUDED_TOP_LEVEL_DIRS = new Set(['node_modules', 'dist', '.astro', '.writedocs', 'public', '.git']);
16
-
17
- /** A page's title when its frontmatter has none - Mintlify's rule, so a
18
- * migrated page that relied on it keeps the same title: the file name
19
- * without its extension, dashes and underscores as spaces, first letter
20
- * capitalized. `guides/getting-started.mdx` -> "Getting started". A
21
- * folder's index page is named for the folder (`api/index.mdx` -> "Api"),
22
- * and the site's own index.mdx is "Home" - "Index" names neither. */
23
- export function titleFromPath(filePath) {
24
- const parts = String(filePath).split(/[\\/]/).filter(Boolean);
25
- let base = (parts.pop() ?? '').replace(/\.mdx?$/i, '');
26
- if (base.toLowerCase() === 'index') {
27
- if (parts.length === 0) return 'Home';
28
- base = parts.pop();
29
- }
30
- const words = base.replace(/[-_]+/g, ' ').trim();
31
- return words ? words.charAt(0).toUpperCase() + words.slice(1) : 'Untitled';
32
- }
33
-
34
- /** Mintlify's .mintignore, if the content directory has one: gitignore-
35
- * style patterns for files and folders that aren't published. Supports
36
- * comments, blank lines, `*`, `**`, `?`, a leading `/` (anchored to the
37
- * content directory) and a trailing `/` (folders only); negation (`!`)
38
- * isn't supported and such lines are skipped. Returns (relPath, isDir) =>
39
- * boolean. */
40
- function readIgnoreFile(contentDir) {
41
- let text;
42
- try {
43
- text = fs.readFileSync(path.join(contentDir, '.mintignore'), 'utf-8');
44
- } catch {
45
- return () => false;
46
- }
47
- const rules = text
48
- .split(/\r?\n/)
49
- .map((l) => l.trim())
50
- .filter((l) => l && !l.startsWith('#') && !l.startsWith('!'))
51
- .map((pattern) => {
52
- const dirOnly = pattern.endsWith('/');
53
- let p = pattern.replace(/\/+$/, '');
54
- const anchored = p.startsWith('/') || p.includes('/');
55
- p = p.replace(/^\/+/, '');
56
- const source = p
57
- .split(/(\*\*\/?|\*|\?)/)
58
- .map((part) =>
59
- part === '**/' || part === '**' ? '(?:.*/)?' : part === '*' ? '[^/]*' : part === '?' ? '[^/]' : part.replace(/[.+^${}()|[\]\\]/g, '\\$&')
60
- )
61
- .join('');
62
- const re = new RegExp(anchored ? `^${source}$` : `(?:^|/)${source}$`);
63
- return { re, dirOnly };
64
- });
65
- return (rel, isDir) => rules.some((r) => (!r.dirOnly || isDir) && r.re.test(rel));
66
- }
67
-
68
- /** Page ids writedocs.json's navigation lists (strings in arrays, and
69
- * groups' `page`) - read straight from the file, since this runs before
70
- * (and independently of) config validation. Empty when there's no
71
- * readable writedocs.json. */
72
- /** The page id a navigation entry names. "guides/index" and "guides" are
73
- * the same page: a folder's index.mdx has the folder's id (fileIdForPath()
74
- * below), and Mintlify projects write it either way. The root "index"
75
- * stays as it is. */
76
- export function navPageId(id) {
77
- return id.endsWith('/index') ? id.slice(0, -'/index'.length) : id;
78
- }
79
-
80
- /** Every page id a `navigation` lists, in the order a reader meets them -
81
- * top to bottom, each group's own `page` before its `pages` - without
82
- * repeats. */
83
- export function navigationPageOrder(navigation) {
84
- const ids = new Set();
85
- (function walk(node) {
86
- if (Array.isArray(node)) node.forEach((item) => (typeof item === 'string' ? ids.add(navPageId(item)) : walk(item)));
87
- else if (node && typeof node === 'object') {
88
- if (typeof node.page === 'string') ids.add(navPageId(node.page));
89
- for (const [key, value] of Object.entries(node)) {
90
- if (key !== 'page' && key !== 'openapi' && key !== 'href') walk(value);
91
- }
92
- }
93
- })(navigation);
94
- return [...ids];
95
- }
96
-
97
- function navigationPageIds(contentDir) {
98
- let config;
99
- try {
100
- config = JSON.parse(readConfigText(contentDir));
101
- } catch {
102
- return new Set();
103
- }
104
- return new Set(navigationPageOrder(config.navigation));
105
- }
106
-
107
- /** Recursively finds every .md/.mdx file under `contentDir` that is a page:
108
- * one with a frontmatter block, or one writedocs.json's navigation lists
109
- * (a Mintlify page needs no frontmatter at all - see titleFromPath()).
110
- * Skips EXCLUDED_TOP_LEVEL_DIRS, every dot-folder at any depth, and
111
- * anything a .mintignore file lists. docs/ is scanned exactly like any
112
- * other folder, no special-casing. Returns POSIX-relative paths (from
113
- * `contentDir`) suitable to hand straight to Astro's `glob()` loader as a
114
- * literal `pattern` array - see content.config.ts's `pages` collection,
115
- * and [...slug].astro, which needs the identical list to decide whether
116
- * calling `getCollection('pages')` is worth doing at all. Also reused by
117
- * astro.config.mjs's noindex/sitemap scan and by `writedocs validate`, so
118
- * all of them see exactly the same file set. Synchronous. In a build the
119
- * project is scanned once and every later call gets that list
120
- * (lib/build-memo.js) - a page that scanned it again made the build N x N;
121
- * everywhere else (`writedocs dev`, `validate`) every call scans afresh,
122
- * so a page added or removed is seen. */
123
- export function findAllPages(contentDir) {
124
- // A copy, so a caller that changes its list doesn't change everyone's.
125
- return oncePerBuild(`pages:${contentDir}`, () => scanAllPages(contentDir)).slice();
126
- }
127
-
128
- function scanAllPages(contentDir) {
129
- const results = [];
130
- const ignored = readIgnoreFile(contentDir);
131
- const listed = navigationPageIds(contentDir);
132
- function walk(dir, relBase) {
133
- let entries;
134
- try {
135
- entries = fs.readdirSync(dir, { withFileTypes: true });
136
- } catch {
137
- return;
138
- }
139
- for (const entry of entries) {
140
- const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
141
- const abs = path.join(dir, entry.name);
142
- if (entry.isDirectory()) {
143
- if (relBase === '' && EXCLUDED_TOP_LEVEL_DIRS.has(entry.name)) continue;
144
- if (entry.name.startsWith('.')) continue;
145
- if (ignored(rel, true)) continue;
146
- walk(abs, rel);
147
- continue;
148
- }
149
- if (!entry.isFile() || !/\.mdx?$/i.test(entry.name)) continue;
150
- if (ignored(rel, false)) continue;
151
- let raw;
152
- try {
153
- raw = fs.readFileSync(abs, 'utf-8');
154
- } catch {
155
- continue;
156
- }
157
- let data;
158
- try {
159
- ({ data } = matter(raw));
160
- } catch {
161
- // Frontmatter that isn't valid YAML: still a page (it opens a
162
- // frontmatter block), so the error surfaces with this file's name -
163
- // from `writedocs validate`, or Astro's own loader in the build -
164
- // instead of as a bare YAML error thrown from here.
165
- if (/^---\r?\n/.test(raw)) results.push(rel);
166
- continue;
167
- }
168
- if (Object.keys(data).length === 0 && !listed.has(fileIdForPath(rel))) continue; // not a page
169
- results.push(rel);
170
- }
171
- }
172
- walk(contentDir, '');
173
- return results;
174
- }
175
-
176
- /** The id writedocs.json's navigation refers to a page by: its path from
177
- * the content directory, without the extension or a trailing `/index`
178
- * (same algorithm as fileIdForEntry() in lib/config.ts). */
179
- export function fileIdForPath(relativePath) {
180
- return relativePath.replace(/\.mdx?$/i, '').replace(/\/index$/, '');
181
- }
182
-
183
- /** Any `.css`/`.js` file anywhere in the project - root or any subfolder,
184
- * `public/` included - auto-loaded site-wide with zero `writedocs.json`
185
- * config, on top of (not instead of) the explicit `scripts` field
186
- * (bannerSchema and friends, above). Drop a file in, it loads;
187
- * there's no field naming which ones to use, matching the same "just
188
- * works" convention `docs/`'s own file discovery already follows (see
189
- * findAllPages() above / `content-pipeline.mdx`) - a site author already
190
- * drops content files in and expects them found, rather than also
191
- * listing every one in writedocs.json.
192
- *
193
- * Two separate walks, because `public/` needs different treatment than
194
- * everywhere else:
195
- *
196
- * - `css`/`js`: every `.css`/`.js` file outside `public/` (root, `docs/`,
197
- * `snippets/`, any custom folder) - reused as the walk-with-exclusions
198
- * shape from findAllPages() above, and its exact `EXCLUDED_TOP_LEVEL_DIRS`
199
- * set (skipped only at the project root, same as there), so `dist/`,
200
- * `node_modules/`, `.astro/`, `.writedocs/`, `.git/`, and (for this
201
- * half only - see below) `public/` are never walked into. BaseLayout.astro
202
- * reads each one's raw content and inlines it as a `<style>`/
203
- * `<script is:inline>` tag.
204
- * - `publicCss`/`publicJs`: every `.css`/`.js` file *inside* `public/`,
205
- * walked separately (starting from `<contentDir>/public` rather than
206
- * `contentDir` itself, so the same `EXCLUDED_TOP_LEVEL_DIRS` check
207
- * doesn't apply here - there's no `public/public/` or `public/dist/`
208
- * convention to guard against). Returned as public-URL-rooted hrefs
209
- * (a leading `/`, no `public` segment - `public/custom.css` becomes
210
- * `/custom.css`) rather than content-dir-relative paths, since these
211
- * files are already served as static assets at exactly that URL once
212
- * Astro copies `public/` into the build output. BaseLayout.astro
213
- * renders these as ordinary `<link rel="stylesheet">`/`<script src>`
214
- * tags pointing at that URL instead of inlining their content -
215
- * inlining would duplicate every byte (once in the page's own HTML,
216
- * once more as the independently-fetchable static file at that same
217
- * URL) for no benefit, where a `<link>`/`<script src>` gets normal
218
- * browser caching across pages instead of repeating the content on
219
- * every single page's markup.
220
- *
221
- * Both halves are broader than they might sound - a stray `.js` file
222
- * kept in `docs/`, `snippets/`, or `public/` for an unrelated reason
223
- * (a snippet's own local helper, an image gallery's lightbox script
224
- * someone dropped in `public/` to reference from a raw `<script src>`
225
- * in an .mdx file, say) gets auto-injected sitewide the same as a
226
- * deliberate one; there's no separate "this one's just tooling" signal
227
- * to opt out of the convention short of renaming its extension.
228
- *
229
- * Both `css`/`js` and `publicCss`/`publicJs` are sorted alphabetically
230
- * by their respective path for deterministic load order across rebuilds
231
- * - filesystem readdir order isn't guaranteed portable across OSes or
232
- * directory-walk order otherwise.
233
- *
234
- * `css`/`js` return POSIX-separated paths relative to `contentDir`, not
235
- * absolute paths or file contents - BaseLayout.astro (the sole caller)
236
- * resolves and reads each one's content itself, right before inlining
237
- * it, so a file's content is always current as of that specific
238
- * request/build rather than cached here across a `writedocs dev`
239
- * session. `publicCss`/`publicJs` return the public-URL hrefs described
240
- * above - nothing to read, Astro's own static-file serving/copy already
241
- * handles those. */
242
- export function findRootAssets(contentDir) {
243
- // Once per build (lib/build-memo.js); on every call in `writedocs dev`.
244
- return oncePerBuild(`root-assets:${contentDir}`, () => scanRootAssets(contentDir));
245
- }
246
-
247
- function scanRootAssets(contentDir) {
248
- const css = [];
249
- const js = [];
250
- function walk(dir, relBase) {
251
- let entries;
252
- try {
253
- entries = fs.readdirSync(dir, { withFileTypes: true });
254
- } catch {
255
- return;
256
- }
257
- for (const entry of entries) {
258
- const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
259
- const abs = path.join(dir, entry.name);
260
- if (entry.isDirectory()) {
261
- if (relBase === '' && EXCLUDED_TOP_LEVEL_DIRS.has(entry.name)) continue;
262
- // Dot-folders (.github, .claude, .husky, .vscode, ...) hold tooling,
263
- // never site assets - the same rule findAllPages() applies to pages.
264
- // Without it, a CI script under .github/ ran on every page.
265
- if (entry.name.startsWith('.')) continue;
266
- walk(abs, rel);
267
- continue;
268
- }
269
- if (!entry.isFile() || entry.name.startsWith('.')) continue; // .eslintrc.js and friends
270
- if (/\.css$/i.test(entry.name)) css.push(rel);
271
- else if (/\.js$/i.test(entry.name)) js.push(rel);
272
- }
273
- }
274
- walk(contentDir, '');
275
- css.sort();
276
- js.sort();
277
-
278
- const publicCss = [];
279
- const publicJs = [];
280
- function walkPublic(dir, relBase) {
281
- let entries;
282
- try {
283
- entries = fs.readdirSync(dir, { withFileTypes: true });
284
- } catch {
285
- return;
286
- }
287
- for (const entry of entries) {
288
- const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
289
- const abs = path.join(dir, entry.name);
290
- if (entry.isDirectory()) {
291
- walkPublic(abs, rel);
292
- continue;
293
- }
294
- if (!entry.isFile()) continue;
295
- if (/\.css$/i.test(entry.name)) publicCss.push(`/${rel}`);
296
- else if (/\.js$/i.test(entry.name)) publicJs.push(`/${rel}`);
297
- }
298
- }
299
- walkPublic(path.join(contentDir, 'public'), '');
300
- publicCss.sort();
301
- publicJs.sort();
302
-
303
- return { css, js, publicCss, publicJs };
304
- }
1
+ // Which files in a content directory are pages. Plain JavaScript, not
2
+ // TypeScript, so `writedocs validate` can load it with plain Node (Node
3
+ // refuses to strip types under node_modules - see lib/icons.js's comment);
4
+ // lib/config.ts re-exports findAllPages() for everything inside Astro.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import matter from 'gray-matter';
8
+ import { readConfigText } from './config-file.js';
9
+ import { oncePerBuild } from './build-memo.js';
10
+ import { projectIgnore } from './project-ignore.js';
11
+
12
+ // Top-level folders of a content directory that are never scanned for
13
+ // pages - build output, dependencies, and static assets. Any folder whose
14
+ // name starts with a dot (.git, .github, .claude, .mintlify, ...) is
15
+ // skipped too, at any depth - see findAllPages().
16
+ export const EXCLUDED_TOP_LEVEL_DIRS = new Set(['node_modules', 'dist', '.astro', '.writedocs', 'public', '.git']);
17
+
18
+ /** A page's title when its frontmatter has none - Mintlify's rule, so a
19
+ * migrated page that relied on it keeps the same title: the file name
20
+ * without its extension, dashes and underscores as spaces, first letter
21
+ * capitalized. `guides/getting-started.mdx` -> "Getting started". A
22
+ * folder's index page is named for the folder (`api/index.mdx` -> "Api"),
23
+ * and the site's own index.mdx is "Home" - "Index" names neither. */
24
+ export function titleFromPath(filePath) {
25
+ const parts = String(filePath).split(/[\\/]/).filter(Boolean);
26
+ let base = (parts.pop() ?? '').replace(/\.mdx?$/i, '');
27
+ if (base.toLowerCase() === 'index') {
28
+ if (parts.length === 0) return 'Home';
29
+ base = parts.pop();
30
+ }
31
+ const words = base.replace(/[-_]+/g, ' ').trim();
32
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : 'Untitled';
33
+ }
34
+
35
+ /** Mintlify's .mintignore, if the content directory has one: gitignore-
36
+ * style patterns for files and folders that aren't published. Supports
37
+ * comments, blank lines, `*`, `**`, `?`, a leading `/` (anchored to the
38
+ * content directory) and a trailing `/` (folders only); negation (`!`)
39
+ * isn't supported and such lines are skipped. Returns (relPath, isDir) =>
40
+ * boolean. */
41
+ function readIgnoreFile(contentDir) {
42
+ let text;
43
+ try {
44
+ text = fs.readFileSync(path.join(contentDir, '.mintignore'), 'utf-8');
45
+ } catch {
46
+ return () => false;
47
+ }
48
+ const rules = text
49
+ .split(/\r?\n/)
50
+ .map((l) => l.trim())
51
+ .filter((l) => l && !l.startsWith('#') && !l.startsWith('!'))
52
+ .map((pattern) => {
53
+ const dirOnly = pattern.endsWith('/');
54
+ let p = pattern.replace(/\/+$/, '');
55
+ const anchored = p.startsWith('/') || p.includes('/');
56
+ p = p.replace(/^\/+/, '');
57
+ const source = p
58
+ .split(/(\*\*\/?|\*|\?)/)
59
+ .map((part) =>
60
+ part === '**/' || part === '**' ? '(?:.*/)?' : part === '*' ? '[^/]*' : part === '?' ? '[^/]' : part.replace(/[.+^${}()|[\]\\]/g, '\\$&')
61
+ )
62
+ .join('');
63
+ const re = new RegExp(anchored ? `^${source}$` : `(?:^|/)${source}$`);
64
+ return { re, dirOnly };
65
+ });
66
+ return (rel, isDir) => rules.some((r) => (!r.dirOnly || isDir) && r.re.test(rel));
67
+ }
68
+
69
+ /** Page ids writedocs.json's navigation lists (strings in arrays, and
70
+ * groups' `page`) - read straight from the file, since this runs before
71
+ * (and independently of) config validation. Empty when there's no
72
+ * readable writedocs.json. */
73
+ /** The page id a navigation entry names. "guides/index" and "guides" are
74
+ * the same page: a folder's index.mdx has the folder's id (fileIdForPath()
75
+ * below), and Mintlify projects write it either way. The root "index"
76
+ * stays as it is. */
77
+ export function navPageId(id) {
78
+ return id.endsWith('/index') ? id.slice(0, -'/index'.length) : id;
79
+ }
80
+
81
+ /** Every page id a `navigation` lists, in the order a reader meets them -
82
+ * top to bottom, each group's own `page` before its `pages` - without
83
+ * repeats. */
84
+ export function navigationPageOrder(navigation) {
85
+ const ids = new Set();
86
+ (function walk(node) {
87
+ if (Array.isArray(node)) node.forEach((item) => (typeof item === 'string' ? ids.add(navPageId(item)) : walk(item)));
88
+ else if (node && typeof node === 'object') {
89
+ if (typeof node.page === 'string') ids.add(navPageId(node.page));
90
+ for (const [key, value] of Object.entries(node)) {
91
+ if (key !== 'page' && key !== 'openapi' && key !== 'href') walk(value);
92
+ }
93
+ }
94
+ })(navigation);
95
+ return [...ids];
96
+ }
97
+
98
+ function navigationPageIds(contentDir) {
99
+ let config;
100
+ try {
101
+ config = JSON.parse(readConfigText(contentDir));
102
+ } catch {
103
+ return new Set();
104
+ }
105
+ return new Set(navigationPageOrder(config.navigation));
106
+ }
107
+
108
+ /** Recursively finds every .md/.mdx file under `contentDir` that is a page:
109
+ * one with a frontmatter block, or one writedocs.json's navigation lists
110
+ * (a Mintlify page needs no frontmatter at all - see titleFromPath()).
111
+ * Skips EXCLUDED_TOP_LEVEL_DIRS, every dot-folder at any depth, whatever
112
+ * the project's ignore rules leave out (lib/wdignore.js: the default
113
+ * exclusions and its `.wdignore`) and anything a .mintignore file lists. docs/ is scanned exactly like any
114
+ * other folder, no special-casing. Returns POSIX-relative paths (from
115
+ * `contentDir`) suitable to hand straight to Astro's `glob()` loader as a
116
+ * literal `pattern` array - see content.config.ts's `pages` collection,
117
+ * and [...slug].astro, which needs the identical list to decide whether
118
+ * calling `getCollection('pages')` is worth doing at all. Also reused by
119
+ * astro.config.mjs's noindex/sitemap scan and by `writedocs validate`, so
120
+ * all of them see exactly the same file set. Synchronous. In a build the
121
+ * project is scanned once and every later call gets that list
122
+ * (lib/build-memo.js) - a page that scanned it again made the build N x N;
123
+ * everywhere else (`writedocs dev`, `validate`) every call scans afresh,
124
+ * so a page added or removed is seen. */
125
+ export function findAllPages(contentDir) {
126
+ // A copy, so a caller that changes its list doesn't change everyone's.
127
+ return oncePerBuild(`pages:${contentDir}`, () => scanAllPages(contentDir)).slice();
128
+ }
129
+
130
+ function scanAllPages(contentDir) {
131
+ const results = [];
132
+ const ignored = readIgnoreFile(contentDir);
133
+ const rules = projectIgnore(contentDir);
134
+ const listed = navigationPageIds(contentDir);
135
+ function walk(dir, relBase) {
136
+ let entries;
137
+ try {
138
+ entries = fs.readdirSync(dir, { withFileTypes: true });
139
+ } catch {
140
+ return;
141
+ }
142
+ for (const entry of entries) {
143
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
144
+ const abs = path.join(dir, entry.name);
145
+ if (entry.isDirectory()) {
146
+ if (relBase === '' && EXCLUDED_TOP_LEVEL_DIRS.has(entry.name)) continue;
147
+ if (entry.name.startsWith('.')) continue;
148
+ if (ignored(rel, true) || rules.ignores(rel, true)) continue;
149
+ walk(abs, rel);
150
+ continue;
151
+ }
152
+ if (!entry.isFile() || !/\.mdx?$/i.test(entry.name)) continue;
153
+ if (ignored(rel, false) || rules.ignores(rel)) continue;
154
+ let raw;
155
+ try {
156
+ raw = fs.readFileSync(abs, 'utf-8');
157
+ } catch {
158
+ continue;
159
+ }
160
+ let data;
161
+ try {
162
+ ({ data } = matter(raw));
163
+ } catch {
164
+ // Frontmatter that isn't valid YAML: still a page (it opens a
165
+ // frontmatter block), so the error surfaces with this file's name -
166
+ // from `writedocs validate`, or Astro's own loader in the build -
167
+ // instead of as a bare YAML error thrown from here.
168
+ if (/^---\r?\n/.test(raw)) results.push(rel);
169
+ continue;
170
+ }
171
+ if (Object.keys(data).length === 0 && !listed.has(fileIdForPath(rel))) continue; // not a page
172
+ results.push(rel);
173
+ }
174
+ }
175
+ walk(contentDir, '');
176
+ return results;
177
+ }
178
+
179
+ /** The id writedocs.json's navigation refers to a page by: its path from
180
+ * the content directory, without the extension or a trailing `/index`
181
+ * (same algorithm as fileIdForEntry() in lib/config.ts). */
182
+ export function fileIdForPath(relativePath) {
183
+ return relativePath.replace(/\.mdx?$/i, '').replace(/\/index$/, '');
184
+ }
185
+
186
+ /** Any `.css`/`.js` file anywhere in the project - root or any subfolder,
187
+ * `public/` included - auto-loaded site-wide with zero `writedocs.json`
188
+ * config, on top of (not instead of) the explicit `scripts` field
189
+ * (bannerSchema and friends, above). Drop a file in, it loads;
190
+ * there's no field naming which ones to use, matching the same "just
191
+ * works" convention `docs/`'s own file discovery already follows (see
192
+ * findAllPages() above / `content-pipeline.mdx`) - a site author already
193
+ * drops content files in and expects them found, rather than also
194
+ * listing every one in writedocs.json.
195
+ *
196
+ * Two separate walks, because `public/` needs different treatment than
197
+ * everywhere else:
198
+ *
199
+ * - `css`/`js`: every `.css`/`.js` file outside `public/` (root, `docs/`,
200
+ * `snippets/`, any custom folder) - reused as the walk-with-exclusions
201
+ * shape from findAllPages() above, and its exact `EXCLUDED_TOP_LEVEL_DIRS`
202
+ * set (skipped only at the project root, same as there), so `dist/`,
203
+ * `node_modules/`, `.astro/`, `.writedocs/`, `.git/`, and (for this
204
+ * half only - see below) `public/` are never walked into. BaseLayout.astro
205
+ * reads each one's raw content and inlines it as a `<style>`/
206
+ * `<script is:inline>` tag.
207
+ * - `publicCss`/`publicJs`: every `.css`/`.js` file *inside* `public/`,
208
+ * walked separately (starting from `<contentDir>/public` rather than
209
+ * `contentDir` itself, so the same `EXCLUDED_TOP_LEVEL_DIRS` check
210
+ * doesn't apply here - there's no `public/public/` or `public/dist/`
211
+ * convention to guard against). Returned as public-URL-rooted hrefs
212
+ * (a leading `/`, no `public` segment - `public/custom.css` becomes
213
+ * `/custom.css`) rather than content-dir-relative paths, since these
214
+ * files are already served as static assets at exactly that URL once
215
+ * Astro copies `public/` into the build output. BaseLayout.astro
216
+ * renders these as ordinary `<link rel="stylesheet">`/`<script src>`
217
+ * tags pointing at that URL instead of inlining their content -
218
+ * inlining would duplicate every byte (once in the page's own HTML,
219
+ * once more as the independently-fetchable static file at that same
220
+ * URL) for no benefit, where a `<link>`/`<script src>` gets normal
221
+ * browser caching across pages instead of repeating the content on
222
+ * every single page's markup.
223
+ *
224
+ * Both halves are broader than they might sound - a stray `.js` file
225
+ * kept in `docs/`, `snippets/`, or `public/` for an unrelated reason
226
+ * (a snippet's own local helper, an image gallery's lightbox script
227
+ * someone dropped in `public/` to reference from a raw `<script src>`
228
+ * in an .mdx file, say) gets auto-injected sitewide the same as a
229
+ * deliberate one; there's no separate "this one's just tooling" signal
230
+ * to opt out of the convention short of renaming its extension.
231
+ *
232
+ * Both `css`/`js` and `publicCss`/`publicJs` are sorted alphabetically
233
+ * by their respective path for deterministic load order across rebuilds
234
+ * - filesystem readdir order isn't guaranteed portable across OSes or
235
+ * directory-walk order otherwise.
236
+ *
237
+ * `css`/`js` return POSIX-separated paths relative to `contentDir`, not
238
+ * absolute paths or file contents - BaseLayout.astro (the sole caller)
239
+ * resolves and reads each one's content itself, right before inlining
240
+ * it, so a file's content is always current as of that specific
241
+ * request/build rather than cached here across a `writedocs dev`
242
+ * session. `publicCss`/`publicJs` return the public-URL hrefs described
243
+ * above - nothing to read, Astro's own static-file serving/copy already
244
+ * handles those. */
245
+ export function findRootAssets(contentDir) {
246
+ // Once per build (lib/build-memo.js); on every call in `writedocs dev`.
247
+ return oncePerBuild(`root-assets:${contentDir}`, () => scanRootAssets(contentDir));
248
+ }
249
+
250
+ function scanRootAssets(contentDir) {
251
+ // What the project's ignore rules leave out (lib/wdignore.js) is never
252
+ // loaded into the pages either - in public/ too.
253
+ const rules = projectIgnore(contentDir);
254
+ const css = [];
255
+ const js = [];
256
+ function walk(dir, relBase) {
257
+ let entries;
258
+ try {
259
+ entries = fs.readdirSync(dir, { withFileTypes: true });
260
+ } catch {
261
+ return;
262
+ }
263
+ for (const entry of entries) {
264
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
265
+ const abs = path.join(dir, entry.name);
266
+ if (entry.isDirectory()) {
267
+ if (relBase === '' && EXCLUDED_TOP_LEVEL_DIRS.has(entry.name)) continue;
268
+ // Dot-folders (.github, .claude, .husky, .vscode, ...) hold tooling,
269
+ // never site assets - the same rule findAllPages() applies to pages.
270
+ // Without it, a CI script under .github/ ran on every page.
271
+ if (entry.name.startsWith('.')) continue;
272
+ if (rules.ignores(rel, true)) continue;
273
+ walk(abs, rel);
274
+ continue;
275
+ }
276
+ if (!entry.isFile() || entry.name.startsWith('.')) continue; // .eslintrc.js and friends
277
+ if (rules.ignores(rel)) continue;
278
+ if (/\.css$/i.test(entry.name)) css.push(rel);
279
+ else if (/\.js$/i.test(entry.name)) js.push(rel);
280
+ }
281
+ }
282
+ walk(contentDir, '');
283
+ css.sort();
284
+ js.sort();
285
+
286
+ const publicCss = [];
287
+ const publicJs = [];
288
+ function walkPublic(dir, relBase) {
289
+ let entries;
290
+ try {
291
+ entries = fs.readdirSync(dir, { withFileTypes: true });
292
+ } catch {
293
+ return;
294
+ }
295
+ for (const entry of entries) {
296
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
297
+ const abs = path.join(dir, entry.name);
298
+ if (entry.isDirectory()) {
299
+ walkPublic(abs, rel);
300
+ continue;
301
+ }
302
+ if (!entry.isFile() || rules.ignores(`public/${rel}`)) continue;
303
+ if (/\.css$/i.test(entry.name)) publicCss.push(`/${rel}`);
304
+ else if (/\.js$/i.test(entry.name)) publicJs.push(`/${rel}`);
305
+ }
306
+ }
307
+ walkPublic(path.join(contentDir, 'public'), '');
308
+ publicCss.sort();
309
+ publicJs.sort();
310
+
311
+ return { css, js, publicCss, publicJs };
312
+ }