@writedocs/generator 0.10.20 → 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 (52) hide show
  1. package/astro.config.mjs +32 -8
  2. package/package.json +1 -1
  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/run-pagefind.js +154 -148
  8. package/src/cli/write-mcp-files.js +103 -96
  9. package/src/cli/write-redirects-file.js +25 -8
  10. package/src/components/AppIcon.astro +51 -50
  11. package/src/components/Card.astro +193 -192
  12. package/src/components/CopyPageMenu.astro +374 -370
  13. package/src/components/Hint.astro +188 -187
  14. package/src/components/Icon.astro +72 -71
  15. package/src/components/Image.astro +3 -2
  16. package/src/components/Tile.astro +67 -66
  17. package/src/components/Video.astro +137 -136
  18. package/src/layout/BaseLayout.astro +21 -12
  19. package/src/layout/components/AnalyticsScripts.astro +6 -2
  20. package/src/layout/components/Breadcrumbs.astro +98 -97
  21. package/src/layout/components/ConsentBanner.astro +119 -118
  22. package/src/layout/components/MobileMenu.astro +229 -228
  23. package/src/layout/components/NavTree.astro +393 -392
  24. package/src/layout/components/Sidebar.astro +232 -231
  25. package/src/layout/components/SiteFooter.astro +87 -86
  26. package/src/layout/components/TopBar.astro +386 -385
  27. package/src/lib/agent-markdown.js +164 -162
  28. package/src/lib/asset-dimensions.js +89 -89
  29. package/src/lib/base-path.js +90 -0
  30. package/src/lib/config-schema.js +10 -0
  31. package/src/lib/config-schema.ts +17 -0
  32. package/src/lib/config.ts +1314 -1289
  33. package/src/lib/consent.js +108 -102
  34. package/src/lib/json-schema-descriptions.js +1 -0
  35. package/src/lib/link-check.js +7 -2
  36. package/src/lib/llms-index.ts +90 -88
  37. package/src/lib/mcp-dev-integration.js +65 -60
  38. package/src/lib/mcp-index.ts +102 -101
  39. package/src/lib/project-files-integration.js +2 -2
  40. package/src/lib/rehype-base-path.js +62 -0
  41. package/src/lib/robots-txt.js +21 -16
  42. package/src/lib/seo-tags.js +155 -140
  43. package/src/lib/site-base.ts +27 -0
  44. package/src/lib/styles-asset-integration.js +23 -10
  45. package/src/lib/wdignore-cases.json +195 -195
  46. package/src/lib/wdignore.js +177 -177
  47. package/src/pages/404.astro +63 -62
  48. package/src/pages/[...slug].astro +1604 -1597
  49. package/src/pages/[...slug].md.ts +93 -93
  50. package/src/pages/llms-full.txt.ts +88 -86
  51. package/src/scripts/search.ts +241 -237
  52. package/writedocs.schema.json +6 -0
package/astro.config.mjs CHANGED
@@ -39,12 +39,14 @@ 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
41
  import { canonicalPath } from './src/lib/canonical-path.js';
42
+ import { withBase, withoutBase } from './src/lib/base-path.js';
42
43
  import { folderAddresses } from './src/lib/folder-redirects.js';
43
44
  import { report } from './src/lib/cli-report.js';
44
45
  import { publishProjectFiles, generatedRobotsTxt } from './src/lib/project-files-integration.js';
45
46
  import { frontmatterNoindex, canonicalIsElsewhere } from './src/lib/seo-tags.js';
46
47
  import { readMovedApiPages } from './src/lib/moved-api-pages.js';
47
48
  import { rehypeImageLoading } from './src/lib/rehype-image-loading.js';
49
+ import { rehypeBasePath } from './src/lib/rehype-base-path.js';
48
50
  import { gitLastModified, newestDate } from './src/lib/last-modified.js';
49
51
  import { readSpecPaths } from './src/lib/project-files.js';
50
52
  import {
@@ -52,6 +54,8 @@ import {
52
54
  resolveCodeblockTheme,
53
55
  resolveCodeblockLangAlias,
54
56
  resolveSiteUrl,
57
+ resolveSiteOrigin,
58
+ resolveBasePath,
55
59
  normalizeEntryId,
56
60
  findAllPages,
57
61
  } from './src/lib/config.ts';
@@ -115,6 +119,10 @@ const contentPublicDir = path.join(contentDir, 'public');
115
119
  // config to be set and would otherwise throw, and a sitemap of
116
120
  // document-relative URLs isn't meaningful anyway.
117
121
  const siteUrl = resolveSiteUrl(docsConfig);
122
+ // writedocs.json's `basePath` ("" when unset) - see lib/base-path.js. Astro's
123
+ // own `base` gets it (bundled assets, the dev server's address), and so do
124
+ // the page scripts, as __WD_BASE__ (vite.define below).
125
+ const basePath = resolveBasePath(docsConfig);
118
126
  if (!siteUrl) {
119
127
  report(
120
128
  'info',
@@ -256,7 +264,10 @@ function singleSitemapFile() {
256
264
  // redirect from the old one the same way; a redirect the site wrote itself
257
265
  // for the same address comes later in the list, and wins.
258
266
  const movedApiPages = readMovedApiPages(contentDir);
259
- const redirectsConfig = Object.fromEntries([...movedApiPages, ...docsConfig.redirects].map((r) => [r.source, r.destination]));
267
+ // With a basePath, Astro serves a redirect's source under the base itself,
268
+ // but writes its destination as given - so a destination inside the site
269
+ // gets the base here (lib/base-path.js).
270
+ const redirectsConfig = Object.fromEntries([...movedApiPages, ...docsConfig.redirects].map((r) => [r.source, withBase(basePath, r.destination)]));
260
271
 
261
272
  /** Tailwind only scans the Vite root for class names - this package, not
262
273
  * the site being built, which is usually somewhere else entirely - so a
@@ -278,7 +289,10 @@ function contentTailwindSource() {
278
289
  }
279
290
 
280
291
  export default defineConfig({
281
- ...(siteUrl ? { site: siteUrl } : {}),
292
+ // The origin alone: Astro adds `base` to it itself (the sitemap's URLs).
293
+ ...(siteUrl ? { site: resolveSiteOrigin(docsConfig) } : {}),
294
+ // Only with a basePath: without one the config is exactly what it was.
295
+ ...(basePath ? { base: basePath } : {}),
282
296
  ...(Object.keys(redirectsConfig).length ? { redirects: redirectsConfig } : {}),
283
297
  // Astro's own dev-mode toolbar (the floating pill in the bottom center
284
298
  // of every page - inspect/audit/settings) is a tool for authoring
@@ -334,14 +348,16 @@ export default defineConfig({
334
348
  // @astrojs/sitemap é 45.000). Até aqui, tudo cabe num único
335
349
  // sitemap.xml - ver singleSitemapFile() abaixo.
336
350
  entryLimit: 50000,
351
+ // The plugin's URLs carry the base ("/docs/guides/a/") - the
352
+ // ids here don't.
337
353
  filter: (page) => {
338
- const pathname = new URL(page).pathname;
354
+ const pathname = withoutBase(basePath, new URL(page).pathname) ?? '/';
339
355
  const id = normalizeEntryId(pathname);
340
356
  return !noindexIds.has(id);
341
357
  },
342
358
  // <lastmod>, for the pages git has a date for.
343
359
  serialize: (item) => {
344
- const changed = lastModifiedById.get(normalizeEntryId(new URL(item.url).pathname));
360
+ const changed = lastModifiedById.get(normalizeEntryId(withoutBase(basePath, new URL(item.url).pathname) ?? '/'));
345
361
  return changed ? { ...item, lastmod: changed } : item;
346
362
  },
347
363
  }),
@@ -351,16 +367,16 @@ export default defineConfig({
351
367
  ]
352
368
  : []),
353
369
  // After the sitemap: the generated robots.txt names the sitemap file.
354
- generatedRobotsTxt({ siteUrl, seo: docsConfig.seo }),
370
+ generatedRobotsTxt({ siteUrl, seo: docsConfig.seo, basePath }),
355
371
  // Lets styles.favicon/styles.logo/styles.background.images/seo.ogImage/
356
372
  // styles.fonts.*.source resolve from anywhere in the project, not just
357
373
  // public/ - see collectConfiguredAssetPaths() (lib/config.ts) for the
358
374
  // field list and styles-asset-integration.js for how it's actually
359
375
  // served/copied.
360
- stylesAssetFallback(contentDir),
376
+ stylesAssetFallback(contentDir, { basePath }),
361
377
  // /mcp in `writedocs dev`, as the build's dist/_worker.js serves it -
362
378
  // see src/lib/mcp-dev-integration.js.
363
- mcpDevServer({ version: JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8')).version }),
379
+ mcpDevServer({ version: JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8')).version, basePath }),
364
380
  // writedocs dev: an edit to writedocs.json reloads the open tab.
365
381
  configReload({ configPath: path.join(contentDir, 'writedocs.json') }),
366
382
  ],
@@ -482,7 +498,10 @@ export default defineConfig({
482
498
  // neither plugin's output is visible to the other.
483
499
  // rehypeImageLoading: lazy loading and sizes for content images - see
484
500
  // lib/rehype-image-loading.js.
485
- rehypePlugins: [rehypeMermaid, rehypeKatex, [rehypeImageLoading, { contentDir }]],
501
+ // rehypeBasePath: the basePath in front of the content's own links and
502
+ // pictures (lib/rehype-base-path.js) - last, since rehypeImageLoading
503
+ // finds an image's file by the address as written.
504
+ rehypePlugins: [rehypeMermaid, rehypeKatex, [rehypeImageLoading, { contentDir }], [rehypeBasePath, { base: basePath }]],
486
505
  }),
487
506
  shikiConfig: {
488
507
  themes: codeblockTheme,
@@ -526,6 +545,11 @@ export default defineConfig({
526
545
  // working. See src/styles/global.css for the one @import that wires
527
546
  // Tailwind's utilities in.
528
547
  vite: {
548
+ // The base for page scripts and components: "" or "/docs". A constant
549
+ // rather than import.meta.env.BASE_URL ("/" with no base, "/docs" or
550
+ // "/docs/" with one), so `__WD_BASE__ + "/pagefind/..."` folds to the
551
+ // same string the bundle had before basePath existed.
552
+ define: { __WD_BASE__: JSON.stringify(basePath) },
529
553
  // The dev server only serves files under its workspace root by default.
530
554
  // A site's own snippets live in its content directory, and inline React
531
555
  // components moved out of pages (lib/mdx-inline-react.js) in writedocs'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedocs/generator",
3
- "version": "0.10.20",
3
+ "version": "0.11.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": {
@@ -0,0 +1,44 @@
1
+ // Where a build puts the site in dist/ (build.js). Without a basePath, at
2
+ // dist/ itself, as always. With one ("/docs", writedocs.json - see
3
+ // lib/base-path.js), every file the site serves goes to dist/docs/: a static
4
+ // server that serves dist/ at its root answers /docs/... with no rule of its
5
+ // own, and a proxy that passes /docs/* on with its path unchanged finds every
6
+ // file where its address says.
7
+ //
8
+ // A few files aren't the site's but its host's, and the host reads them at
9
+ // the root of what it serves, so they stay in dist/:
10
+ // 404.html the page a host shows for an address it doesn't have
11
+ // (Cloudflare Pages, the WriteDocs platform look for it there);
12
+ // _redirects the host's redirects - every path in the generated rules
13
+ // carries the base (write-redirects-file.js);
14
+ // _headers the host's response headers, when the project has one;
15
+ // _worker.js, _routes.json, .assetsignore
16
+ // the Cloudflare MCP server (write-mcp-files.js), which
17
+ // Cloudflare only runs from the root.
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+
21
+ /** The host's files - kept at the root of dist/, outside the basePath. */
22
+ export const ROOT_FILES = ['404.html', '_redirects', '_headers', '_worker.js', '_routes.json', '.assetsignore'];
23
+
24
+ /** The folder the site itself goes to: dist/ without a basePath,
25
+ * dist/docs/ for "/docs", dist/help/docs/ for "/help/docs". */
26
+ export function siteDirFor(distDir, basePath) {
27
+ const segments = (basePath ?? '').split('/').filter(Boolean);
28
+ return segments.length ? path.join(distDir, ...segments) : distDir;
29
+ }
30
+
31
+ /** Moves the host's files (ROOT_FILES) a build left in the site's folder up
32
+ * to the root of dist/. Nothing to do without a basePath. Returns the names
33
+ * moved. */
34
+ export function moveRootFiles(siteDir, distDir) {
35
+ if (path.resolve(siteDir) === path.resolve(distDir)) return [];
36
+ const moved = [];
37
+ for (const name of ROOT_FILES) {
38
+ const from = path.join(siteDir, name);
39
+ if (!fs.existsSync(from)) continue;
40
+ fs.renameSync(from, path.join(distDir, name));
41
+ moved.push(name);
42
+ }
43
+ return moved;
44
+ }
package/src/cli/build.js CHANGED
@@ -1,168 +1,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 } from '../lib/writedocs-temp-dir.js';
14
- import { log, step, plural, duration, displayPath, formatProblems, color, CliExit } from './output.js';
15
- import { describeError, builtRoute, authorWarning, verboseLine } from './astro-output.js';
16
- import { reportApiPages } from './api-pages-output.js';
17
-
18
- export async function runBuild({ contentDir, packageRoot, verbose = false }) {
19
- // One spelling of each folder throughout - see lib/canonical-path.js.
20
- contentDir = canonicalPath(contentDir);
21
- packageRoot = canonicalPath(packageRoot);
22
- const started = Date.now();
23
- preflightCheck(contentDir);
24
- writableInstallCheck(packageRoot);
25
-
26
- // Collected while building, printed together at the end - a warning in
27
- // the middle of a spinner is easy to miss.
28
- const warnings = [];
29
- const notes = [];
30
- const seen = new Set();
31
- const addWarning = (where, message) => {
32
- const key = `${where ?? ''}\n${message}`;
33
- if (seen.has(key)) return;
34
- seen.add(key);
35
- warnings.push({ where, message });
36
- };
37
-
38
- const api = await generateApiPages({ contentDir });
39
- sameDriveCheck(contentDir, packageRoot, { generatedPages: api.groups.length > 0 });
40
- reportApiPages(api);
41
- api.warnings.forEach((message) => addWarning(null, message));
42
-
43
- const building = step('Building pages');
44
- const buildStarted = Date.now();
45
- let pages = 0;
46
- let fatal = null;
47
- const rawTail = [];
48
- const { exited } = runAstro('build', {
49
- packageRoot,
50
- contentDir,
51
- onEvent(event) {
52
- if (verbose) {
53
- const line = verboseLine(event);
54
- if (line !== null) log.line(color.dim(line));
55
- }
56
- if (event.type === 'fatal') {
57
- fatal = event.error;
58
- return;
59
- }
60
- if (event.type === 'report') {
61
- if (event.level === 'warn') addWarning(event.where, event.message);
62
- else if (event.level === 'info' && !notes.includes(event.message)) notes.push(event.message);
63
- return;
64
- }
65
- if (event.type === 'raw') {
66
- rawTail.push(event.line);
67
- if (rawTail.length > 40) rawTail.shift();
68
- return;
69
- }
70
- const route = builtRoute(event);
71
- if (route) {
72
- if (route.endsWith('.html')) pages += 1;
73
- building.update(`Building pages ${color.dim(`(${pages})`)}`);
74
- return;
75
- }
76
- const warning = authorWarning(event, contentDir);
77
- if (warning) addWarning(null, warning);
78
- },
79
- });
80
- const code = await exited;
81
-
82
- if (fatal || code !== 0) {
83
- building.fail('Build failed');
84
- if (fatal) {
85
- const problem = describeError(fatal, contentDir, { root: packageRoot });
86
- log.line();
87
- log.line(formatProblems([{ where: problem.where, message: problem.message }]));
88
- if (problem.hint) log.line(`\n${color.dim(` Hint: ${problem.hint}`)}`);
89
- if (verbose && fatal.stack) log.line(`\n${color.dim(fatal.stack)}`);
90
- } else if (rawTail.length) {
91
- // No structured error (the worker itself crashed) - show what it printed.
92
- log.line();
93
- log.line(color.dim(rawTail.join('\n')));
94
- }
95
- log.line();
96
- log.line(color.dim('Run "writedocs validate" to list every problem in the project at once.'));
97
- throw new CliExit(1);
98
- }
99
- building.succeed(`Built ${plural(pages, 'page')} ${color.dim(`in ${duration(Date.now() - buildStarted)}`)}`);
100
-
101
- const distDir = path.join(contentDir, 'dist');
102
- // Astro just wrote its actual output to writedocsBuildStagingDir()
103
- // (astro.config.mjs's own `outDir`), not distDir directly - see that
104
- // function's own comment (writedocs-temp-dir.js) for why. fs.cpSync
105
- // (unlike the fs.rename() Astro uses internally to get *into* that
106
- // staging dir in the first place) copies across filesystem boundaries
107
- // without issue, so this is the one step that actually needs to bridge
108
- // packageRoot and contentDir potentially living on different devices.
109
- // distDir is cleared first so a rebuild doesn't leave a stale file
110
- // behind from a previous build that the new one no longer produces -
111
- // the same "the output directory reflects exactly this build, nothing
112
- // older" expectation `astro build` itself already guarantees when
113
- // writing directly into outDir.
114
- const stagingDir = writedocsBuildStagingDir(packageRoot, contentDir);
115
- fs.rmSync(distDir, { recursive: true, force: true });
116
- fs.cpSync(stagingDir, distDir, { recursive: true });
117
- fs.rmSync(stagingDir, { recursive: true, force: true });
118
- // Every page writedocs renders links the site's stylesheet. Builds have
119
- // come out without it on every page while reporting success (the package
120
- // folder spelled `c:`, fixed in lib/canonical-path.js) - so it's checked
121
- // here, and a build like that stops instead of being deployed unstyled.
122
- const unstyled = pagesWithoutStyles(distDir);
123
- if (unstyled.length) {
124
- log.error(`The build produced ${plural(unstyled.length, 'page')} without the site's styles - for example ${unstyled[0]}.`);
125
- 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.'));
126
- throw new CliExit(1);
127
- }
128
- // Astro's own writedocs.json `redirects` + the automatic "/" redirect only
129
- // ever produce client-side meta-refresh pages (see write-redirects-file.js)
130
- // - this turns those into real instant edge redirects on hosts that read
131
- // a `_redirects` file (Cloudflare Pages, Netlify), purely additively.
132
- writeRedirectsFile(distDir, contentDir);
133
- // Every other host follows Astro's redirect pages - rewritten so the
134
- // reader never sees one (rewrite-redirect-pages.js).
135
- const siteConfig = JSON.parse(readConfigText(contentDir));
136
- rewriteRedirectPages(distDir, { background: siteConfig.styles?.background?.colors });
137
- // The site's MCP server at /mcp: mcp-index.json is already in dist/ (an
138
- // Astro route); this adds the Cloudflare _worker.js that serves it - see
139
- // write-mcp-files.js for every host.
140
- const { version: writedocsVersion } = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8'));
141
- const mcp = writeMcpFiles(distDir, contentDir, writedocsVersion);
142
- if (mcp.written.length) notes.push('MCP server at /mcp - dist/_worker.js runs it on Cloudflare; mcp-index.json holds the pages.');
143
- if (mcp.skipped) addWarning(null, `No _worker.js for the MCP server: ${mcp.skipped}.`);
144
-
145
- const indexing = step('Indexing search');
146
- try {
147
- await runPagefind(distDir, { packageRoot });
148
- } catch (err) {
149
- indexing.fail('Search indexing failed');
150
- log.line();
151
- log.line(color.dim(err.message));
152
- throw new CliExit(1);
153
- }
154
- indexing.succeed('Indexed search');
155
-
156
- if (warnings.length) {
157
- log.line();
158
- log.warn(plural(warnings.length, 'warning'));
159
- log.line();
160
- log.line(formatProblems(warnings));
161
- }
162
- if (notes.length) {
163
- log.line();
164
- notes.forEach((note) => log.info(note));
165
- }
166
- log.line();
167
- log.success(`Done in ${duration(Date.now() - started)} ${color.dim('-')} site written to ${color.bold(displayPath(distDir))}`);
168
- }
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);
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,33 +1,41 @@
1
- // After a build: the pages writedocs rendered that came out without the
2
- // site's styles. Every page BaseLayout.astro renders carries
3
- // <meta name="generator" content="writedocs"> and links its stylesheet
4
- // (/_astro/*.css), or inlines it in a <style>. Other HTML in dist/ - a
5
- // redirect page, a file from public/ - isn't writedocs' to check.
6
- import fs from 'node:fs';
7
- import path from 'node:path';
8
-
9
- const MARKER = /<meta name="generator" content="writedocs"/;
10
- const STYLES = /<link[^>]+rel="stylesheet"[^>]+href="\/_astro\/[^"]+\.css"|<link[^>]+href="\/_astro\/[^"]+\.css"[^>]+rel="stylesheet"|<style[\s>]/;
11
-
12
- function htmlFiles(dir) {
13
- const out = [];
14
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
15
- const full = path.join(dir, entry.name);
16
- if (entry.isDirectory()) {
17
- if (entry.name !== '_astro' && entry.name !== 'pagefind') out.push(...htmlFiles(full));
18
- } else if (entry.name.endsWith('.html')) out.push(full);
19
- }
20
- return out;
21
- }
22
-
23
- /** Paths (relative to `distDir`, with forward slashes) of writedocs pages
24
- * with no stylesheet. */
25
- export function pagesWithoutStyles(distDir) {
26
- return htmlFiles(distDir)
27
- .filter((file) => {
28
- const html = fs.readFileSync(file, 'utf8');
29
- return MARKER.test(html) && !STYLES.test(html);
30
- })
31
- .map((file) => path.relative(distDir, file).split(path.sep).join('/'))
32
- .sort();
33
- }
1
+ // After a build: the pages writedocs rendered that came out without the
2
+ // site's styles. Every page BaseLayout.astro renders carries
3
+ // <meta name="generator" content="writedocs"> and links its stylesheet
4
+ // (/_astro/*.css - /docs/_astro/*.css under a basePath), or inlines it in a
5
+ // <style>. Other HTML in dist/ - a redirect page, a file from public/ -
6
+ // isn't writedocs' to check.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ const MARKER = /<meta name="generator" content="writedocs"/;
11
+ /** The stylesheet link (or <style>) of a page whose site has `basePath` -
12
+ * "" or "/docs", lib/base-path.js: only lowercase letters, digits, "-", "_"
13
+ * and "/", nothing to escape in a pattern. */
14
+ function stylesPattern(basePath = '') {
15
+ const css = `${basePath}/_astro/[^"]+\\.css`;
16
+ return new RegExp(`<link[^>]+rel="stylesheet"[^>]+href="${css}"|<link[^>]+href="${css}"[^>]+rel="stylesheet"|<style[\\s>]`);
17
+ }
18
+
19
+ function htmlFiles(dir) {
20
+ const out = [];
21
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
22
+ const full = path.join(dir, entry.name);
23
+ if (entry.isDirectory()) {
24
+ if (entry.name !== '_astro' && entry.name !== 'pagefind') out.push(...htmlFiles(full));
25
+ } else if (entry.name.endsWith('.html')) out.push(full);
26
+ }
27
+ return out;
28
+ }
29
+
30
+ /** Paths (relative to `distDir`, with forward slashes) of writedocs pages
31
+ * with no stylesheet. */
32
+ export function pagesWithoutStyles(distDir, { basePath = '' } = {}) {
33
+ const STYLES = stylesPattern(basePath);
34
+ return htmlFiles(distDir)
35
+ .filter((file) => {
36
+ const html = fs.readFileSync(file, 'utf8');
37
+ return MARKER.test(html) && !STYLES.test(html);
38
+ })
39
+ .map((file) => path.relative(distDir, file).split(path.sep).join('/'))
40
+ .sort();
41
+ }