@writedocs/generator 0.15.0 → 0.17.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 (38) hide show
  1. package/astro.config.mjs +8 -2
  2. package/package.json +1 -1
  3. package/packages/components/src/components/CodeGroup.astro +6 -6
  4. package/src/cli/build.js +39 -4
  5. package/src/cli/dev.js +16 -0
  6. package/src/cli/rewrite-redirect-pages.js +8 -6
  7. package/src/cli/run-pagefind.js +24 -11
  8. package/src/cli/write-mcp-files.js +4 -1
  9. package/src/cli/write-redirects-file.js +9 -4
  10. package/src/content.config.ts +21 -1
  11. package/src/layout/BaseLayout.astro +38 -49
  12. package/src/layout/components/LockMark.astro +28 -0
  13. package/src/layout/components/MobileMenu.astro +13 -5
  14. package/src/layout/components/Sidebar.astro +3 -2
  15. package/src/layout/components/TopBar.astro +17 -4
  16. package/src/lib/appearance.js +64 -0
  17. package/src/lib/asset-dimensions.js +2 -1
  18. package/src/lib/bom.js +20 -0
  19. package/src/lib/config-file.js +21 -8
  20. package/src/lib/config-schema.js +55 -10
  21. package/src/lib/config-schema.ts +78 -18
  22. package/src/lib/config.ts +23 -11
  23. package/src/lib/content-check.js +54 -4
  24. package/src/lib/content-store-prune.js +44 -0
  25. package/src/lib/json-schema-descriptions.js +7 -2
  26. package/src/lib/llms-index.ts +5 -0
  27. package/src/lib/mcp-index.ts +5 -1
  28. package/src/lib/mintlify-convert.js +11 -1
  29. package/src/lib/pages.js +5 -3
  30. package/src/lib/protected-sections.js +238 -0
  31. package/src/lib/wdignore-cases.json +9 -2
  32. package/src/lib/wdignore.js +5 -0
  33. package/src/lib/writedocs-legacy-convert.js +1 -1
  34. package/src/pages/[...slug].astro +53 -14
  35. package/src/pages/llms-full.txt.ts +10 -3
  36. package/src/pages/llms.txt.ts +4 -4
  37. package/src/pages/og/[...slug].png.ts +11 -2
  38. package/writedocs.schema.json +478 -70
package/astro.config.mjs CHANGED
@@ -44,6 +44,8 @@ import { rehypeImageLoading } from './src/lib/rehype-image-loading.js';
44
44
  import { rehypeBasePath } from './src/lib/rehype-base-path.js';
45
45
  import { gitLastModified, newestDate } from './src/lib/last-modified.js';
46
46
  import { readSpecPaths } from './src/lib/project-files.js';
47
+ import { protectedPages } from './src/lib/protected-sections.js';
48
+ import { fileIdForPath } from './src/lib/pages.js';
47
49
  import {
48
50
  loadDocsConfig,
49
51
  resolveCodeblockTheme,
@@ -166,6 +168,9 @@ function collectNoindexIds(rootContentDir) {
166
168
  const pageIds = [];
167
169
  // When each page last changed, for <lastmod> - see lib/last-modified.js.
168
170
  const fileDates = gitLastModified(rootContentDir);
171
+ // A protected page (lib/protected-sections.js) is noindex, whatever its
172
+ // frontmatter says - and never listed in a public file.
173
+ const protectedRules = protectedPages(docsConfig.navigation);
169
174
 
170
175
  for (const relativeId of findAllPages(rootContentDir)) {
171
176
  const file = path.join(rootContentDir, relativeId);
@@ -183,7 +188,8 @@ function collectNoindexIds(rootContentDir) {
183
188
  // canonical URL is another address (the sitemap lists canonical ones).
184
189
  const canonical = data?.seo?.canonical ?? data?.canonical;
185
190
  const pagePath = pageId === 'index' ? '/' : `/${pageId}/`;
186
- if (!frontmatterNoindex(data) && !data?.url && !canonicalIsElsewhere(siteUrl, pagePath, canonical)) continue;
191
+ const isProtected = protectedRules.has(fileIdForPath(relativeId));
192
+ if (!isProtected && !frontmatterNoindex(data) && !data?.url && !canonicalIsElsewhere(siteUrl, pagePath, canonical)) continue;
187
193
  ids.add(pageId);
188
194
  }
189
195
  // Generated OpenAPI stub pages always set an explicit `slug` (see
@@ -197,7 +203,7 @@ function collectNoindexIds(rootContentDir) {
197
203
  // A generated API page changes when a spec does. Which spec it came
198
204
  // from isn't recorded on the page, so it gets the newest of them.
199
205
  if (data?.slug && specsChanged) lastModifiedById.set(normalizeEntryId(data.slug), specsChanged);
200
- if (frontmatterNoindex(data) && data.slug) ids.add(normalizeEntryId(data.slug));
206
+ if ((frontmatterNoindex(data) || protectedRules.has(normalizeEntryId(data?.slug ?? ''))) && data.slug) ids.add(normalizeEntryId(data.slug));
201
207
  }
202
208
  if (!rootIsPage) ids.add('index');
203
209
  // Folder addresses with no page of their own redirect to one under them
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedocs/generator",
3
- "version": "0.15.0",
3
+ "version": "0.17.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": {
@@ -124,12 +124,12 @@ const { dropdown = false } = Astro.props as Props;
124
124
  border-radius: 0;
125
125
  background: none;
126
126
  }
127
- /* No-JS / too-small-to-tab fallback only - once initCodeGroups() above
128
- hides every block but the active one, there's never two adjacent
129
- *visible* blocks left for this to space apart, so it's inert in the
130
- normal tabbed case. Without JS, every block stays visible and
131
- stacked, each with its own title bar. */
132
- .wd-codegroup > .wd-code-block + .wd-code-block {
127
+ /* No-JS / too-small-to-tab fallback only: without JS every block stays
128
+ visible and stacked, each with its own title bar. Scoped off tabbed
129
+ groups because hiding a block (display: none) doesn't stop `+` from
130
+ matching - every tab after the first would show this gap between the
131
+ tab strip and its code panel. */
132
+ .wd-codegroup:not(.wd-codegroup-tabbed) > .wd-code-block + .wd-code-block {
133
133
  margin-top: 0.5rem;
134
134
  }
135
135
  /* 2rem tall, like a block's title bar, with room on the right for the
package/src/cli/build.js CHANGED
@@ -20,6 +20,7 @@ import { reportApiPages } from './api-pages-output.js';
20
20
  import { findDraftPages } from '../lib/pages.js';
21
21
  import { draftWarnings } from '../lib/drafts.js';
22
22
  import { createJsonLocator } from '../lib/config-schema.js';
23
+ import { usesAccess, accessRules, accessMap, ACCESS_MAP_FILE, ACCESS_NEEDS_PLATFORM } from '../lib/protected-sections.js';
23
24
 
24
25
  /** `drafts` (`writedocs build --drafts`): draft pages are part of the site -
25
26
  * marked, noindex, out of the sitemap, llms.txt and the MCP index, the way
@@ -72,12 +73,17 @@ export async function runBuild({ contentDir, packageRoot, verbose = false, draft
72
73
  const ogCardsFile = path.join(writedocsTempDir(contentDir), 'og-cards.json');
73
74
  fs.mkdirSync(path.dirname(ogCardsFile), { recursive: true });
74
75
  fs.rmSync(ogCardsFile, { force: true });
76
+ // The protected addresses ([...slug].astro lists them here, as
77
+ // `{ slug, rule }` - lib/protected-sections.js). Removed first for the same
78
+ // reason.
79
+ const accessFile = path.join(writedocsTempDir(contentDir), 'access-routes.json');
80
+ fs.rmSync(accessFile, { force: true });
75
81
  const { exited } = runAstro('build', {
76
82
  packageRoot,
77
83
  contentDir,
78
84
  // WRITEDOCS_DRAFTS: draftsIncluded() in lib/pages.js - set either way, so
79
85
  // one left in the shell's environment can't decide it.
80
- env: { WRITEDOCS_OG_CARDS_FILE: ogCardsFile, WRITEDOCS_DRAFTS: drafts ? '1' : '' },
86
+ env: { WRITEDOCS_OG_CARDS_FILE: ogCardsFile, WRITEDOCS_ACCESS_FILE: accessFile, WRITEDOCS_DRAFTS: drafts ? '1' : '' },
81
87
  onEvent(event) {
82
88
  if (verbose) {
83
89
  const line = verboseLine(event);
@@ -136,6 +142,10 @@ export async function runBuild({ contentDir, packageRoot, verbose = false, draft
136
142
  // Without one, siteDir is distDir, and every step below is what it was.
137
143
  const basePath = normalizeBasePath(siteConfig.basePath);
138
144
  const siteDir = siteDirFor(distDir, basePath);
145
+ // Protected sections are protected by the WriteDocs platform only
146
+ // (lib/protected-sections.js) - said every time, so nobody hosting the
147
+ // build elsewhere takes them for private.
148
+ if (usesAccess(siteConfig.navigation)) addWarning(null, ACCESS_NEEDS_PLATFORM);
139
149
  // Astro just wrote its actual output to writedocsBuildStagingDir()
140
150
  // (astro.config.mjs's own `outDir`), not distDir directly - see that
141
151
  // function's own comment (writedocs-temp-dir.js) for why. fs.cpSync
@@ -185,10 +195,14 @@ export async function runBuild({ contentDir, packageRoot, verbose = false, draft
185
195
  // ever produce client-side meta-refresh pages (see write-redirects-file.js)
186
196
  // - this turns those into real instant edge redirects on hosts that read
187
197
  // a `_redirects` file (Cloudflare Pages, Netlify), purely additively.
188
- writeRedirectsFile(siteDir, contentDir, { outDir: distDir, basePath });
198
+ // A folder redirect that leads to a protected page stays a page, behind
199
+ // its rule - not an edge redirect anyone can follow.
200
+ const protectedRoutes = fs.existsSync(accessFile) ? JSON.parse(fs.readFileSync(accessFile, 'utf8')) : [];
201
+ const protectedFolders = new Set(protectedRoutes.map((route) => `/${route.slug}/`));
202
+ writeRedirectsFile(siteDir, contentDir, { outDir: distDir, basePath, protectedFolders });
189
203
  // Every other host follows Astro's redirect pages - rewritten so the
190
204
  // reader never sees one (rewrite-redirect-pages.js).
191
- rewriteRedirectPages(siteDir, { background: siteConfig.styles?.background?.colors });
205
+ rewriteRedirectPages(siteDir, { background: siteConfig.styles?.background?.colors, appearance: siteConfig.styles?.appearance });
192
206
  // The site's MCP server at /mcp: mcp-index.json is already in dist/ (an
193
207
  // Astro route); this adds the Cloudflare _worker.js that serves it - see
194
208
  // write-mcp-files.js for every host.
@@ -198,8 +212,9 @@ export async function runBuild({ contentDir, packageRoot, verbose = false, draft
198
212
  if (mcp.skipped) addWarning(null, `No _worker.js for the MCP server: ${mcp.skipped}.`);
199
213
 
200
214
  const indexing = step('Indexing search');
215
+ let searchSpaces = [];
201
216
  try {
202
- await runPagefind(siteDir, { packageRoot });
217
+ ({ spaces: searchSpaces } = await runPagefind(siteDir, { packageRoot }));
203
218
  } catch (err) {
204
219
  indexing.fail('Search indexing failed');
205
220
  log.line();
@@ -208,6 +223,26 @@ export async function runBuild({ contentDir, packageRoot, verbose = false, draft
208
223
  }
209
224
  indexing.succeed('Indexed search');
210
225
 
226
+ // The map the WriteDocs platform protects the site by: each access rule
227
+ // and every path it serves only to the rule's readers
228
+ // (lib/protected-sections.js, docs/dev/docs/protected-sections.mdx). At
229
+ // the root of dist/, outside a basePath's folder - the platform never
230
+ // serves /.writedocs/. Without `access` in writedocs.json, no file, and
231
+ // dist/ is what it was.
232
+ if (usesAccess(siteConfig.navigation)) {
233
+ const map = accessMap({
234
+ rules: accessRules(siteConfig.navigation),
235
+ routes: protectedRoutes,
236
+ spaces: searchSpaces,
237
+ basePath,
238
+ exists: (rel) => fs.existsSync(path.join(siteDir, ...rel.split('/'))),
239
+ });
240
+ const mapFile = path.join(distDir, ...ACCESS_MAP_FILE.split('/'));
241
+ fs.mkdirSync(path.dirname(mapFile), { recursive: true });
242
+ fs.writeFileSync(mapFile, `${JSON.stringify(map, null, 2)}
243
+ `);
244
+ }
245
+
211
246
  if (warnings.length) {
212
247
  log.line();
213
248
  log.warn(plural(warnings.length, 'warning'));
package/src/cli/dev.js CHANGED
@@ -10,6 +10,7 @@ import { showUpdateNotice } from './update-check.js';
10
10
  import { shouldOpenBrowser, openBrowser } from './open-browser.js';
11
11
  import { watchPageList } from './page-list-watch.js';
12
12
  import { readConfigText } from '../lib/config-file.js';
13
+ import { usesAccess, ACCESS_IN_DEV } from '../lib/protected-sections.js';
13
14
  import { normalizeBasePath } from '../lib/base-path.js';
14
15
  import { writeDevOpenApiState } from '../lib/openapi-dev-status.js';
15
16
 
@@ -143,6 +144,12 @@ export async function runDev({ contentDir, packageRoot, port, verbose = false, o
143
144
  log.line();
144
145
  log.line(color.dim(' Edit any page and the preview updates. Press Ctrl+C to stop.'));
145
146
  log.line();
147
+ // Protected sections (lib/protected-sections.js) are the
148
+ // platform's to protect - here every page opens.
149
+ if (configUsesAccess(contentDir)) {
150
+ log.info(ACCESS_IN_DEV);
151
+ log.line();
152
+ }
146
153
  // `dev` runs until Ctrl+C - the notice goes under the ready screen,
147
154
  // not after the command like everywhere else.
148
155
  showUpdateNotice();
@@ -267,3 +274,12 @@ export async function runDev({ contentDir, packageRoot, port, verbose = false, o
267
274
  }
268
275
  throw new CliExit(code || 1);
269
276
  }
277
+
278
+ /** Whether writedocs.json names an access rule - false when it can't be read. */
279
+ function configUsesAccess(contentDir) {
280
+ try {
281
+ return usesAccess(JSON.parse(readConfigText(contentDir)).navigation);
282
+ } catch {
283
+ return false;
284
+ }
285
+ }
@@ -13,6 +13,7 @@
13
13
  // screen. The meta refresh stays for browsers without JavaScript.
14
14
  import fs from 'node:fs';
15
15
  import path from 'node:path';
16
+ import { themeScript, serverTheme } from '../lib/appearance.js';
16
17
 
17
18
  // Any delay: Astro waits 2 seconds on a 302's page (the automatic "/"), none on a 301's.
18
19
  const REFRESH = /<meta http-equiv="refresh" content="\d+;\s*url=([^"]*)"\s*\/?>/i;
@@ -34,15 +35,16 @@ function cssColor(value, fallback) {
34
35
  }
35
36
 
36
37
  /** The page for a redirect to `target`. */
37
- export function redirectPageHtml({ target, canonical = null, background = {} }) {
38
+ export function redirectPageHtml({ target, canonical = null, background = {}, appearance }) {
38
39
  const light = cssColor(background.light, DEFAULT_LIGHT);
39
40
  const dark = cssColor(background.dark, DEFAULT_DARK);
40
41
  // Inside <script>: a JSON string, with "<" escaped so a target can't end the script.
41
42
  const js = JSON.stringify(target).replace(/</g, '\\u003c');
42
43
  const attr = encodeAttr(target);
44
+ const fixed = serverTheme(appearance);
43
45
  return [
44
46
  '<!doctype html>',
45
- '<html lang="en">',
47
+ fixed ? `<html lang="en" data-theme="${fixed}">` : '<html lang="en">',
46
48
  '<head>',
47
49
  '<meta charset="utf-8">',
48
50
  `<script>location.replace(${js} + location.search + location.hash)</script>`,
@@ -51,8 +53,8 @@ export function redirectPageHtml({ target, canonical = null, background = {} })
51
53
  '<meta name="robots" content="noindex">',
52
54
  canonical ? `<link rel="canonical" href="${encodeAttr(canonical)}">` : '',
53
55
  '<title>Redirecting…</title>',
54
- // Same theme choice as every page (BaseLayout.astro): the stored one, else the system's.
55
- "<script>try{var t=localStorage.getItem('wd-theme');if(t!=='light'&&t!=='dark')t=matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';document.documentElement.dataset.theme=t}catch(e){}</script>",
56
+ // The same theme choice as every page (BaseLayout.astro) - src/lib/appearance.js.
57
+ `<script>${themeScript(appearance)}</script>`,
56
58
  `<style>html{background:${light};color-scheme:light}html[data-theme=dark]{background:${dark};color-scheme:dark}@media (prefers-color-scheme:dark){html:not([data-theme]){background:${dark};color-scheme:dark}}body{margin:0}a{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}</style>`,
57
59
  '</head>',
58
60
  `<body><a href="${attr}">Continue to ${attr}</a></body>`,
@@ -62,7 +64,7 @@ export function redirectPageHtml({ target, canonical = null, background = {} })
62
64
  }
63
65
 
64
66
  /** Rewrites every Astro redirect page under `distDir`. Returns how many. */
65
- export function rewriteRedirectPages(distDir, { background } = {}) {
67
+ export function rewriteRedirectPages(distDir, { background, appearance } = {}) {
66
68
  let count = 0;
67
69
  const walk = (dir) => {
68
70
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
@@ -76,7 +78,7 @@ export function rewriteRedirectPages(distDir, { background } = {}) {
76
78
  const refresh = REFRESH.exec(html);
77
79
  if (!refresh || !ASTRO_REDIRECT.test(html)) continue;
78
80
  const canonical = CANONICAL.exec(html);
79
- fs.writeFileSync(full, redirectPageHtml({ target: decodeAttr(refresh[1]), canonical: canonical ? decodeAttr(canonical[1]) : null, background }));
81
+ fs.writeFileSync(full, redirectPageHtml({ target: decodeAttr(refresh[1]), canonical: canonical ? decodeAttr(canonical[1]) : null, background, appearance }));
80
82
  count++;
81
83
  }
82
84
  };
@@ -60,19 +60,30 @@ function resolvePagefindBin(packageRoot) {
60
60
  * result (/docs/pagefind/ -> "/docs/a/"). Adding the base here too gave
61
61
  * results with it twice.
62
62
  */
63
+ /**
64
+ * Returns the ids of the search spaces it wrote, each in
65
+ * pagefind-spaces/<id>/ - the build lists a protected one's folder in
66
+ * dist/.writedocs/access.json (lib/protected-sections.js).
67
+ */
63
68
  export async function runPagefind(siteDir, { packageRoot }) {
64
69
  const groups = searchSpaces(siteDir);
65
- if (groups) return indexBySpace(siteDir, packageRoot, groups);
66
- return indexWholeSite(siteDir, packageRoot);
70
+ if (groups) {
71
+ await indexBySpace(siteDir, packageRoot, groups);
72
+ return { spaces: [...groups.spaces.keys()] };
73
+ }
74
+ await indexWholeSite(siteDir, packageRoot);
75
+ return { spaces: [] };
67
76
  }
68
77
 
69
- // Pages under a hidden navigation item name their search space in their
70
- // markup ([...slug].astro, lib/hidden-sections.js).
78
+ // Pages under a hidden or a protected navigation item name their search
79
+ // space in their markup ([...slug].astro, lib/hidden-sections.js,
80
+ // lib/protected-sections.js).
71
81
  const SPACE = /data-wd-search-space="([^"]+)"/;
72
82
  const SEARCH_PUBLIC = /data-wd-search-public="true"/;
73
83
 
74
84
  /** The site's pages by search space - `{ public, spaces }` - or null when
75
- * no page is in a hidden space (the whole site is one index, as ever).
85
+ * no page is in a hidden or protected space (the whole site is one index,
86
+ * as ever).
76
87
  * Only pages Pagefind would index: those with a data-pagefind-body. A
77
88
  * page is `{ rel }`, its path in the site with forward slashes.
78
89
  * Exported for scripts/search-spaces.test.js. */
@@ -109,11 +120,13 @@ export function searchSpaces(siteDir) {
109
120
  return spaces.size ? { public: publicPages, spaces } : null;
110
121
  }
111
122
 
112
- /** One index for the public pages (dist/pagefind/) and one per hidden
113
- * space (dist/pagefind-spaces/<id>/) - so the public search never finds a
114
- * hidden page, and a hidden space's search finds only its own pages, plus
115
- * the public ones when it sets `searchPublic`. src/scripts/search.ts loads
116
- * the index of the page's space. */
123
+ /** One index for the public pages (dist/pagefind/) and one per hidden or
124
+ * protected space (dist/pagefind-spaces/<id>/) - so the public search never
125
+ * finds a hidden or protected page, and a space's search finds only its own
126
+ * pages, plus the public ones when it sets `searchPublic`. A protected
127
+ * space holds one access rule's pages only (searchSpaceOf() in
128
+ * lib/protected-sections.js), so its folder is behind that rule.
129
+ * src/scripts/search.ts loads the index of the page's space. */
117
130
  async function indexBySpace(siteDir, packageRoot, groups) {
118
131
  const pagefind = await import(pathToFileURL(path.join(findPagefindDir(packageRoot), 'lib', 'index.js')).href);
119
132
  const check = (result, what) => {
@@ -129,7 +142,7 @@ async function indexBySpace(siteDir, packageRoot, groups) {
129
142
  await write(groups.public, path.join(siteDir, 'pagefind'), 'public pages');
130
143
  for (const [id, space] of groups.spaces) {
131
144
  const pages = space.searchPublic ? [...space.pages, ...groups.public] : space.pages;
132
- await write(pages, path.join(siteDir, 'pagefind-spaces', id), `hidden space ${id}`);
145
+ await write(pages, path.join(siteDir, 'pagefind-spaces', id), `search space ${id}`);
133
146
  }
134
147
  } finally {
135
148
  await pagefind.close();
@@ -26,6 +26,7 @@
26
26
  import fs from 'node:fs';
27
27
  import path from 'node:path';
28
28
  import { fileURLToPath } from 'node:url';
29
+ import { readText } from '../lib/config-file.js';
29
30
 
30
31
  const SERVER_SOURCE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'mcp', 'server.js');
31
32
  const IGNORED_BY_WORKERS = ['_worker.js', '_routes.json'];
@@ -92,7 +93,9 @@ export function writeMcpFiles(distDir, contentDir, version, { siteDir = distDir,
92
93
  fs.writeFileSync(path.join(distDir, '_routes.json'), JSON.stringify({ version: 1, include: [`${basePath}/mcp`, `${basePath}/mcp/`], exclude: [] }, null, 2) + '\n');
93
94
 
94
95
  const ignorePath = path.join(distDir, '.assetsignore');
95
- const existing = fs.existsSync(ignorePath) ? fs.readFileSync(ignorePath, 'utf-8') : '';
96
+ // A project's own public/.assetsignore, without a byte order mark
97
+ // (lib/bom.js).
98
+ const existing = fs.existsSync(ignorePath) ? readText(ignorePath) : '';
96
99
  const lines = existing.split(/\r?\n/).map((l) => l.trim());
97
100
  const missing = IGNORED_BY_WORKERS.filter((name) => !lines.includes(name));
98
101
  if (missing.length) {
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { readConfigText } from '../lib/config-file.js';
3
+ import { readConfigText, readText } from '../lib/config-file.js';
4
4
  import { readMovedApiPages } from '../lib/moved-api-pages.js';
5
5
  import { withBase } from '../lib/base-path.js';
6
6
 
@@ -41,7 +41,10 @@ import { withBase } from '../lib/base-path.js';
41
41
  // the rules name, source and destination - the host matches the full path
42
42
  // it was asked for - and adds `/ -> /docs/` for whoever opens the root of
43
43
  // the address directly.
44
- export function writeRedirectsFile(distDir, contentDir, { outDir = distDir, basePath = '' } = {}) {
44
+ /** `protectedFolders` - folder addresses ("/partners/") whose redirect leads
45
+ * to a protected page (lib/protected-sections.js): left out here, so the
46
+ * redirect stays a page behind the page's access rule. */
47
+ export function writeRedirectsFile(distDir, contentDir, { outDir = distDir, basePath = '', protectedFolders = new Set() } = {}) {
45
48
  const writedocsJson = JSON.parse(readConfigText(contentDir));
46
49
  const redirects = writedocsJson.redirects ?? [];
47
50
  const lines = [];
@@ -100,6 +103,7 @@ export function writeRedirectsFile(distDir, contentDir, { outDir = distDir, base
100
103
  // automatic folder redirects. (Read before rewrite-redirect-pages.js makes
101
104
  // every redirect page go at once.)
102
105
  for (const { url, target } of temporaryRedirectPages(distDir)) {
106
+ if (protectedFolders.has(url)) continue;
103
107
  lines.push(`${at(url)} ${target} 302`, `${at(url).replace(/\/$/, '')} ${target} 302`);
104
108
  }
105
109
 
@@ -121,8 +125,9 @@ export function writeRedirectsFile(distDir, contentDir, { outDir = distDir, base
121
125
  const redirectsPath = path.join(outDir, '_redirects');
122
126
  // A hand-written public/_redirects is already copied into dist by Astro
123
127
  // by this point - preserve it (and its priority: first match wins) by
124
- // appending after it rather than overwriting.
125
- const existing = fs.existsSync(redirectsPath) ? fs.readFileSync(redirectsPath, 'utf8').replace(/\s*$/, '\n\n') : '';
128
+ // appending after it rather than overwriting. Without a byte order mark,
129
+ // which would sit in front of its first rule (lib/bom.js).
130
+ const existing = fs.existsSync(redirectsPath) ? readText(redirectsPath).replace(/\s*$/, '\n\n') : '';
126
131
  fs.writeFileSync(redirectsPath, existing + generated);
127
132
  }
128
133
 
@@ -8,6 +8,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
8
8
  import { pageFrontmatterSchema, findAllPages } from './lib/config';
9
9
  import { titleFromPath } from './lib/pages.js';
10
10
  import { writedocsTempDir } from './lib/writedocs-temp-dir.js';
11
+ import { staleEntryIds } from './lib/content-store-prune.js';
11
12
 
12
13
  const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
13
14
 
@@ -63,10 +64,16 @@ function skipIfMissing(inner: Loader): Loader {
63
64
  // Left empty: the last spec taken out of writedocs.json while
64
65
  // `writedocs dev` runs (the folder stays then). glob() would only warn
65
66
  // about no files and keep the pages it had.
66
- if (!fs.readdirSync(generatedDocsBase, { recursive: true }).some((file) => /\.mdx?$/i.test(String(file)))) {
67
+ const files = fs
68
+ .readdirSync(generatedDocsBase, { recursive: true })
69
+ .map(String)
70
+ .filter((file) => /\.mdx?$/i.test(file))
71
+ .map((file) => path.join(fileURLToPath(generatedDocsBase), file));
72
+ if (files.length === 0) {
67
73
  for (const id of context.store.keys()) context.store.delete(id);
68
74
  return;
69
75
  }
76
+ forgetMovedFiles(context, files);
70
77
  return inner.load({ ...withTitleFallback(context), watcher: undefined });
71
78
  },
72
79
  };
@@ -92,6 +99,18 @@ const schemaDigest = createHash('sha256')
92
99
  .slice(0, 16);
93
100
 
94
101
  type LoaderContext = Parameters<Loader['load']>[0];
102
+
103
+ // A page's stored entry is kept, old `filePath` and all, while its id and
104
+ // text stay the same - and a page with a `slug` keeps both when it moves to
105
+ // another folder. Entries whose file isn't one of the pages about to be
106
+ // synced are deleted first, so glob() reads those pages again from where
107
+ // they are now. Without this, the build failed on the page's old path, and
108
+ // `writedocs dev` on every page - see lib/content-store-prune.js.
109
+ function forgetMovedFiles(context: LoaderContext, files: string[]) {
110
+ const root = fileURLToPath(context.config.root);
111
+ for (const id of staleEntryIds(context.store.entries(), root, files)) context.store.delete(id);
112
+ }
113
+
95
114
  function withTitleFallback(context: LoaderContext): LoaderContext {
96
115
  return {
97
116
  ...context,
@@ -186,6 +205,7 @@ function livePages(dir: string, base: URL): Loader {
186
205
  for (const id of store.keys()) store.delete(id);
187
206
  return;
188
207
  }
208
+ forgetMovedFiles(context, files.map((file) => path.join(dir, file)));
189
209
  await glob({ pattern: files, base }).load({ ...withTitleFallback(context), watcher: undefined });
190
210
  }
191
211
 
@@ -88,7 +88,9 @@ import { htmlDirective } from "../lib/agent-directive.js";
88
88
  import { contextMenuOptions } from "../lib/config";
89
89
  import { jsonLd, serializeJsonLd } from "../lib/json-ld.js";
90
90
  import { consentOptions } from "../lib/consent.js";
91
+ import { themeScript, serverTheme } from "../lib/appearance.js";
91
92
  import { oncePerBuild } from "../lib/build-memo.js";
93
+ import { stripBom } from "../lib/bom.js";
92
94
  // writedocs.json's `basePath`: every site address written below goes
93
95
  // through siteHref() - see the components package's lib/site-base.ts.
94
96
  import { BASE, siteHref } from "../../packages/components/src/lib/site-base";
@@ -411,11 +413,19 @@ const rootAssets = findRootAssets(contentDir);
411
413
  // "docs/theme.css") - split and rejoin with nodePath.join rather than
412
414
  // handing the raw string straight to it, so a nested asset resolves
413
415
  // correctly on every OS this might run on, not just POSIX ones.
416
+ //
417
+ // Without a byte order mark (lib/bom.js): inlined, it would be the first
418
+ // character of the <style>, and the stylesheet's first rule would match
419
+ // nothing. Read right here, with lib/bom.js's dependency-free stripBom():
420
+ // calling a lib/pages.js helper from this frontmatter instead changed how
421
+ // the build splits its chunks - every page then linked BaseLayout.css
422
+ // before its own stylesheet, a different cascade (found comparing dist/
423
+ // with 0.15.0's). scripts/bom.test.js checks both reads go through it.
414
424
  const rootCssContents = oncePerBuild("root-css-contents", () => rootAssets.css.map((name) =>
415
- fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8"),
425
+ stripBom(fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8")),
416
426
  ));
417
427
  const rootJsContents = oncePerBuild("root-js-contents", () => rootAssets.js.map((name) =>
418
- fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8"),
428
+ stripBom(fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8")),
419
429
  ));
420
430
  // public/*.css and public/*.js auto-load too, but as <link>/<script src>
421
431
  // pointing at their already-public URL (see findRootAssets()'s own
@@ -501,7 +511,7 @@ const fontExtraCss = [fontFaceCss, fontFallbackCss, fontWeightCss].filter(Boolea
501
511
  ---
502
512
 
503
513
  <!doctype html>
504
- <html lang={lang}>
514
+ <html lang={lang} data-theme={serverTheme(config.styles.appearance)}>
505
515
  <head>
506
516
  <meta charset="UTF-8" />
507
517
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
@@ -558,52 +568,31 @@ const fontExtraCss = [fontFaceCss, fontFallbackCss, fontWeightCss].filter(Boolea
558
568
  consent={consent}
559
569
  gatedScripts={[...config.scripts.head, ...config.scripts.body].filter(gated)}
560
570
  />
561
- <script is:inline>
562
- // Sets [data-theme] and [data-banner-dismissed] on <html> before
563
- // first paint, so the page never flashes the wrong mode or an
564
- // already-dismissed banner. Preference order for theme: an explicit
565
- // prior choice (localStorage), then the OS-level preference,
566
- // defaulting to light. The click handlers that update both live in
567
- // src/scripts/theme-toggle.ts and src/scripts/banner.ts.
568
- //
569
- // Also re-run on `astro:after-swap` (ClientRouter, see BaseLayout's
570
- // own import of it below), not just the initial load - Astro's
571
- // client-side navigation swaps <html>'s attributes wholesale to
572
- // match the newly-fetched page's raw server-rendered markup (see
573
- // swapRootAttributes() in astro/dist/transitions/swap-functions.js),
574
- // which has neither of these dataset attributes baked in since
575
- // they're pure client-side runtime state, not something the server
576
- // ever renders. Without re-running this after every swap, a
577
- // dismissed banner (or a chosen dark theme) would silently come
578
- // back on the very next navigation - both attributes get wiped, not
579
- // just reset to their default, so this has to unconditionally
580
- // reapply them from localStorage every time, exactly as it does on
581
- // first load. `astro:after-swap` fires synchronously right after
582
- // that swap and before the browser's next paint, so this still
583
- // prevents any visible flash on client-side navigations too.
584
- function wdApplyStoredPreferences() {
585
- try {
586
- var stored = localStorage.getItem("wd-theme");
587
- var theme =
588
- stored === "light" || stored === "dark"
589
- ? stored
590
- : window.matchMedia("(prefers-color-scheme: dark)").matches
591
- ? "dark"
592
- : "light";
593
- document.documentElement.dataset.theme = theme;
594
- } catch (e) {
595
- document.documentElement.dataset.theme = "light";
596
- }
597
- try {
598
- document.documentElement.dataset.bannerDismissed =
599
- localStorage.getItem("wd-banner-dismissed") === "true" ? "true" : "false";
600
- } catch (e) {
601
- document.documentElement.dataset.bannerDismissed = "false";
602
- }
603
- }
604
- wdApplyStoredPreferences();
605
- document.addEventListener("astro:after-swap", wdApplyStoredPreferences);
606
- </script>
571
+ {/* Sets [data-theme] and [data-banner-dismissed] on <html> before
572
+ first paint, so the page never flashes the wrong mode or an
573
+ already-dismissed banner. The theme comes from themeScript()
574
+ (src/lib/appearance.js): the reader's toggle choice (unless
575
+ `styles.appearance.strict`), then `styles.appearance.default`, then
576
+ the OS setting. The click handlers that update both live in
577
+ src/scripts/theme-toggle.ts and src/scripts/banner.ts.
578
+
579
+ Also re-run on `astro:after-swap` (ClientRouter, see BaseLayout's
580
+ own import of it below), not just the initial load - Astro's
581
+ client-side navigation swaps <html>'s attributes wholesale to
582
+ match the newly-fetched page's raw server-rendered markup (see
583
+ swapRootAttributes() in astro/dist/transitions/swap-functions.js),
584
+ which has no banner state and at most serverTheme()'s fixed
585
+ default - never the reader's own choice. Without re-running this
586
+ after every swap, a dismissed banner (or a chosen theme) would
587
+ silently come back on the very next navigation, so this has to
588
+ reapply them every time, exactly as it does on first load.
589
+ `astro:after-swap` fires synchronously right after that swap and
590
+ before the browser's next paint, so this still prevents any
591
+ visible flash on client-side navigations too. */}
592
+ <script
593
+ is:inline
594
+ set:html={`function wdApplyStoredPreferences(){${themeScript(config.styles.appearance)}try{document.documentElement.dataset.bannerDismissed=localStorage.getItem("wd-banner-dismissed")==="true"?"true":"false"}catch(e){document.documentElement.dataset.bannerDismissed="false"}}wdApplyStoredPreferences();document.addEventListener("astro:after-swap",wdApplyStoredPreferences);`}
595
+ />
607
596
  <script>
608
597
  // Preserves the sidebar's own scroll position across a ClientRouter
609
598
  // navigation - see src/scripts/sidebar-scroll.ts for why this is
@@ -0,0 +1,28 @@
1
+ ---
2
+ // The padlock beside a protected navigation item's name - one with
3
+ // `"lock": true` next to its `access` rule (lib/protected-sections.js) -
4
+ // wherever the item is listed: the tabs, a tab's menu, the switchers in the
5
+ // top bar and the sidebar, and the mobile menu. Renders nothing otherwise.
6
+ //
7
+ // Lucide's "lock", the icon set the generator already has, drawn inline with
8
+ // its size in a style attribute - a rule in the site's stylesheet would be on
9
+ // every site, and a site without `access` builds byte for byte as it did
10
+ // before. role="img" and aria-label put "Requires sign-in" in the link's
11
+ // accessible name; <title> shows it on hover.
12
+ import { iconSvg } from '../../lib/config';
13
+
14
+ interface Props {
15
+ locked?: boolean;
16
+ // Inside a line of text rather than a flex row with its own gap: a space
17
+ // before it.
18
+ inline?: boolean;
19
+ }
20
+ const LABEL = 'Requires sign-in';
21
+ const svg = Astro.props.locked ? iconSvg('lock') : null;
22
+ const margin = Astro.props.inline ? 'margin-inline-start:.35em;' : '';
23
+ const html = svg?.replace(
24
+ /^<svg ([^>]*)>/,
25
+ `<svg $1 class="wd-lock" role="img" aria-label="${LABEL}" width="12" height="12" style="${margin}width:.8em;height:.8em;flex-shrink:0;opacity:.7;vertical-align:-.05em"><title>${LABEL}</title>`
26
+ );
27
+ ---
28
+ {html && <Fragment set:html={html} />}