@writedocs/generator 0.16.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.
package/src/lib/config.ts CHANGED
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { EXCLUDED_TOP_LEVEL_DIRS, navPageId, draftsIncluded, findDraftPages, fileIdForPath } from './pages.js';
4
4
  import { withoutDrafts } from './drafts.js';
5
5
  import { isHidden } from './hidden-sections.js';
6
+ import { accessOf, isLocked } from './protected-sections.js';
6
7
  import { itemPage, childLevel, equivalentItem, resolveLandings as resolveLandingsJs } from './item-pages.js';
7
8
  import matter from 'gray-matter';
8
9
  import { writedocsTempDir } from './writedocs-temp-dir.js';
@@ -850,6 +851,7 @@ export function landingSelectors(landing: Landing, hrefForSlug: (slug: string) =
850
851
  href: 'href' in child ? child.href : hrefForSlug(firstSlugOf(child as Container) ?? 'index'),
851
852
  active: false,
852
853
  dropdown: dropdownMenuOf(child as Container, hrefForSlug),
854
+ ...(isLocked(child) ? { locked: true } : {}),
853
855
  };
854
856
  }),
855
857
  });
@@ -883,24 +885,28 @@ export function resolveGlobalDropdowns(navigation: NavigationConfig): DropdownIt
883
885
  * (returns null, with nothing that tries the next one), which is a real
884
886
  * case now that any container - not just a nested dropdown - can be a
885
887
  * bare external link (e.g. a `tabs` array whose first entry is
886
- * `{ tab: "Status", href: "..." }`). */
887
- function firstSlugAmong(items: Container[]): string | null {
888
+ * `{ tab: "Status", href: "..." }`).
889
+ * `publicOnly` (the site's `/`): protected items are skipped too
890
+ * (lib/protected-sections.js) - an option's own link still leads into its
891
+ * protected children, the way choosing it in a menu would. */
892
+ function firstSlugAmong(items: Container[], publicOnly = false): string | null {
888
893
  for (const item of items) {
889
894
  // A hidden item is reached only by its address - never by default.
890
895
  if (isHidden(item)) continue;
891
- const slug = firstSlugOf(item);
896
+ if (publicOnly && accessOf(item)) continue;
897
+ const slug = firstSlugOf(item, publicOnly);
892
898
  if (slug !== null) return slug;
893
899
  }
894
900
  return null;
895
901
  }
896
902
 
897
- export function firstSlugOf(node: Container): string | null {
903
+ export function firstSlugOf(node: Container, publicOnly = false): string | null {
898
904
  // An item with a `page` of its own opens there (lib/item-pages.js).
899
905
  const own = itemPage(node);
900
906
  if (own !== null) return own;
901
907
  if ('pages' in node) return flattenNav(node.pages)[0]?.slug ?? null;
902
908
  if ('href' in node) return null;
903
- if ('tabs' in node) return firstSlugAmong(node.tabs);
909
+ if ('tabs' in node) return firstSlugAmong(node.tabs, publicOnly);
904
910
  if ('versions' in node) {
905
911
  // Try the `default`-tagged version(s) first (matching the old
906
912
  // "preferred" pick), then fall through to the rest in order - same
@@ -908,11 +914,11 @@ export function firstSlugOf(node: Container): string | null {
908
914
  // extra preference pass in front of it.
909
915
  const defaults = node.versions.filter((v) => v.default);
910
916
  const rest = node.versions.filter((v) => !v.default);
911
- return firstSlugAmong([...defaults, ...rest]);
917
+ return firstSlugAmong([...defaults, ...rest], publicOnly);
912
918
  }
913
- if ('languages' in node) return firstSlugAmong(node.languages);
914
- if ('dropdowns' in node) return firstSlugAmong(node.dropdowns);
915
- if ('products' in node) return firstSlugAmong(node.products);
919
+ if ('languages' in node) return firstSlugAmong(node.languages, publicOnly);
920
+ if ('dropdowns' in node) return firstSlugAmong(node.dropdowns, publicOnly);
921
+ if ('products' in node) return firstSlugAmong(node.products, publicOnly);
916
922
  return null;
917
923
  }
918
924
 
@@ -985,10 +991,11 @@ export function equivalentPageIn(
985
991
  * the navigation happens to be a page literally named "index" (the
986
992
  * usual "docs/index.mdx is the homepage" convention). Mirrors
987
993
  * firstSlugOf()'s per-container descent, plus the flat-array root case
988
- * firstSlugOf() alone can't handle since a bare array isn't a Container. */
994
+ * firstSlugOf() alone can't handle since a bare array isn't a Container.
995
+ * Never a page in a hidden or a protected item. */
989
996
  export function firstSlugOfNavigation(navigation: NavigationConfig): string | null {
990
997
  if (Array.isArray(navigation)) return flattenNav(navigation)[0]?.slug ?? null;
991
- return firstSlugOf(navigation as Container);
998
+ return firstSlugOf(navigation as Container, true);
992
999
  }
993
1000
 
994
1001
  /** Whether `slug` is reachable anywhere underneath a container, however
@@ -1048,6 +1055,9 @@ export interface SelectorOption {
1048
1055
  // On an entry with a `submenu`: the entry's own `page`, if it has one -
1049
1056
  // clicking the entry opens it. Without one, clicking opens the flyout.
1050
1057
  pageHref?: string;
1058
+ // A protected item with `lock: true` (lib/protected-sections.js): a
1059
+ // padlock beside its name, wherever it's listed (LockMark.astro).
1060
+ locked?: boolean;
1051
1061
  }
1052
1062
 
1053
1063
  export interface Selector {
@@ -1086,6 +1096,7 @@ function dropdownMenuOf(
1086
1096
  icon: iconOf(d),
1087
1097
  href: 'href' in d ? d.href : hrefForSlug(firstSlugOf(d) ?? 'index'),
1088
1098
  active,
1099
+ ...(isLocked(d) ? { locked: true } : {}),
1089
1100
  };
1090
1101
  if (depth === 1 && 'dropdowns' in d) {
1091
1102
  const submenu = dropdownMenuOf(d, hrefForSlug, active ? below : [], depth + 1);
@@ -1143,6 +1154,7 @@ export function buildSelectors(
1143
1154
  href: 'href' in item ? item.href : hrefForSlug(targetSlug),
1144
1155
  active: isActive,
1145
1156
  dropdown: dropdownMenuOf(item, hrefForSlug, isActive ? path.slice(segIndex + 1) : []),
1157
+ ...(isLocked(item) ? { locked: true } : {}),
1146
1158
  };
1147
1159
  }),
1148
1160
  };
@@ -39,6 +39,7 @@ import { pageFrontmatterSchema, createJsonLocator } from './config-schema.js';
39
39
  import { parseOpenApiRef } from './openapi-ref.js';
40
40
  import { readText } from './config-file.js';
41
41
  import { collectOpenApiGroups, operationKeys } from './openapi-spec.js';
42
+ import { usesAccess, accessOf, firstAccessPath, ACCESS_NEEDS_PLATFORM } from './protected-sections.js';
42
43
 
43
44
  /** An issue: { file, line?, message, suggestion? } - `file` relative to the
44
45
  * content directory, POSIX slashes. */
@@ -451,15 +452,29 @@ export async function checkContent(contentDir, configText) {
451
452
  }
452
453
  // Every top-level item hidden, and no home page: `/` never redirects into a
453
454
  // hidden item (lib/hidden-sections.js), so the site's address has nothing.
455
+ // Nor into a protected one (lib/protected-sections.js).
454
456
  const nav = config.navigation;
455
457
  const topKey = nav && !Array.isArray(nav) ? ['tabs', 'versions', 'languages', 'dropdowns', 'products'].find((k) => Array.isArray(nav[k])) : null;
456
- if (topKey && nav[topKey].length && nav[topKey].every((item) => item?.hidden === true || 'href' in (item ?? {})) && !ids.has('index')) {
458
+ if (topKey && nav[topKey].length && nav[topKey].every((item) => item?.hidden === true || accessOf(item) || 'href' in (item ?? {})) && !ids.has('index')) {
459
+ const anyProtected = nav[topKey].some((item) => accessOf(item));
457
460
  warnings.push(
458
461
  issue(
459
462
  'writedocs.json',
460
463
  locate(['navigation', topKey])?.line,
461
- `Every item in navigation.${topKey} is hidden and there's no home page - the site's own address (/) shows "not found".`,
462
- 'Add an index.mdx at the project root for a home page, or leave one item not hidden.'
464
+ `Every item in navigation.${topKey} is hidden${anyProtected ? ' or protected' : ''} and there's no home page - the site's own address (/) shows "not found".`,
465
+ `Add an index.mdx at the project root for a home page, or leave one item not hidden${anyProtected ? ' and not protected' : ''}.`
466
+ )
467
+ );
468
+ }
469
+ // `access` is the WriteDocs platform's to enforce - anywhere else the
470
+ // pages are public (lib/protected-sections.js).
471
+ if (usesAccess(nav)) {
472
+ warnings.push(
473
+ issue(
474
+ 'writedocs.json',
475
+ locate(firstAccessPath(nav))?.line,
476
+ ACCESS_NEEDS_PLATFORM,
477
+ 'Publish the site on WriteDocs, where each access rule is set up - or, on another host, put a login in front of these pages (on Cloudflare, Cloudflare Access).'
463
478
  )
464
479
  );
465
480
  }
@@ -45,7 +45,9 @@ const CONTAINERS = {
45
45
 
46
46
  const HIDDEN = {
47
47
  hidden: 'Reachable only by its address: no tab, switcher or menu lists it, and inside it this level isn\'t shown. Its pages search only among themselves.',
48
- searchPublic: 'For a hidden item: its search also finds the site\'s public pages.',
48
+ searchPublic: 'For a hidden or protected item: its search also finds the site\'s public pages.',
49
+ access: 'The name of an access rule on the WriteDocs platform (lowercase letters, numbers and hyphens, up to 40): every page under this item is served only to readers the rule lets in. Only the platform protects them - on any other host they\'re public.',
50
+ lock: 'For a protected item (with `access`): a padlock next to its name, wherever it\'s listed.',
49
51
  page: 'A page of its own - an overview - that choosing this item opens, in place of its first page. Shown inside the item; in a sidebar too, it opens there.',
50
52
  };
51
53
 
@@ -9,6 +9,7 @@ import path from 'node:path';
9
9
  import { loadDocsConfig, normalizeEntryId, findAllPages, resolveSiteRoot, fileIdForEntry, contextMenuOptions } from './config';
10
10
  import { buildLlmsTree, renderLlmsFiles } from './llms.js';
11
11
  import { navigationPageOrder } from './pages.js';
12
+ import { protectedPages } from './protected-sections.js';
12
13
  import { writedocsTempDir } from './writedocs-temp-dir.js';
13
14
 
14
15
  type DocsEntry = CollectionEntry<'pages'> | CollectionEntry<'generatedDocs'>;
@@ -55,11 +56,15 @@ export async function llmsIndexFiles(): Promise<Map<string, string> | null> {
55
56
  const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
56
57
 
57
58
  const pages = new Map<string, { title: string; href: string; description?: string; slug: string }>();
59
+ // Protected pages (lib/protected-sections.js) are for the readers their
60
+ // access rule lets in - never listed in a public file.
61
+ const protectedRules = protectedPages(config.navigation);
58
62
  for (const entry of entries) {
59
63
  // A page that opted out of search-engine indexing (`seo.noindex`, also
60
64
  // left out of sitemap.xml) is left out here too, and a frontmatter `url`
61
65
  // page (Mintlify's external link) has no content of its own.
62
66
  if (entry.data.seo?.noindex || entry.data.url) continue;
67
+ if (protectedRules.has(fileIdForEntry(contentDir, packageRoot, entry))) continue;
63
68
  const slug = normalizeEntryId(entry.id);
64
69
  // The .md route when it exists ([...slug].md.ts - unless `contextMenu` is off,
65
70
  // and never for an OpenAPI page, which renders from the spec), else the
@@ -19,6 +19,7 @@ import {
19
19
  } from './config';
20
20
  import { pageMarkdown } from './openapi-markdown';
21
21
  import { orderByNavigation } from './llms.js';
22
+ import { protectedPages } from './protected-sections.js';
22
23
  import { writedocsTempDir } from './writedocs-temp-dir.js';
23
24
 
24
25
  type DocsEntry = CollectionEntry<'pages'> | CollectionEntry<'generatedDocs'>;
@@ -71,10 +72,13 @@ export async function mcpIndex(): Promise<McpIndex> {
71
72
  return place;
72
73
  };
73
74
 
75
+ const protectedRules = protectedPages(config.navigation);
74
76
  const docs = entries
75
77
  // Same pages llms.txt lists: not `noindex`, not a frontmatter `url`
76
- // (an external link, with no content of its own).
78
+ // (an external link, with no content of its own), not protected
79
+ // (lib/protected-sections.js).
77
80
  .filter((entry) => !entry.data.seo?.noindex && !entry.data.url)
81
+ .filter((entry) => !protectedRules.has(fileIdForEntry(contentDir, packageRoot, entry)))
78
82
  .map((entry) => {
79
83
  const slug = normalizeEntryId(entry.id);
80
84
  const fileId = fileIdForEntry(contentDir, packageRoot, entry);
@@ -0,0 +1,238 @@
1
+ // Protected navigation items (`"access": "<rule>"` on a tab, product,
2
+ // version, language or dropdown): every page under the item is served only
3
+ // to the readers its access rule lets in. The rule itself - a password or a
4
+ // list of emails - lives on the WriteDocs platform, never in the project:
5
+ // writedocs.json only names it. The innermost item's rule wins.
6
+ //
7
+ // What the build does with a protected page:
8
+ //
9
+ // - It's left out of everything public that lists pages or carries their
10
+ // text: sitemap.xml (astro.config.mjs), llms.txt and its child files
11
+ // (lib/llms-index.ts), llms-full.txt and mcp-index.json - and it gets
12
+ // `noindex` ([...slug].astro).
13
+ // - `/` never redirects into a protected item (firstSlugOf() in
14
+ // lib/config.ts), and a folder address leads to a public page when the
15
+ // folder has one; a folder with only protected pages under it redirects
16
+ // to one of them, and that redirect is protected too ([...slug].astro).
17
+ // - Its search is its own, like a hidden item's (lib/hidden-sections.js):
18
+ // searchSpaceOf() below gives it a space per rule, and the public search
19
+ // never finds it.
20
+ // - The build writes dist/.writedocs/access.json (accessMap() below): for
21
+ // each rule, every served path it protects. The platform reads it when it
22
+ // publishes and serves those paths only behind the rule's sign-in; the
23
+ // file itself is never served.
24
+ //
25
+ // Protection isn't visual: whether the item shows in the menus is `hidden`'s
26
+ // to say, and `lock` adds a padlock where it shows. Without the platform -
27
+ // a build hosted anywhere else - nothing is protected; `writedocs build`
28
+ // and `validate` say so (ACCESS_NEEDS_PLATFORM).
29
+ //
30
+ // Plain JavaScript, for scripts/protected-sections.test.js and the CLI.
31
+ import { CHILD_KINDS, itemPage } from './item-pages.js';
32
+ import { navPageId } from './pages.js';
33
+ import { isHidden, spaceOf } from './hidden-sections.js';
34
+
35
+ /** What `writedocs build` and `writedocs validate` say when a project uses
36
+ * `access`. */
37
+ export const ACCESS_NEEDS_PLATFORM = 'access needs the WriteDocs platform; on your own host these pages are public.';
38
+
39
+ /** What `writedocs dev` says when a project uses `access`. */
40
+ export const ACCESS_IN_DEV = 'access: nothing is protected in writedocs dev - every page opens without signing in.';
41
+
42
+ /** The access.json format's version - see docs/dev/docs/protected-sections.mdx. */
43
+ export const ACCESS_MAP_VERSION = 1;
44
+
45
+ /** Where the map goes, from the root of dist/ - outside the site's own
46
+ * folder with a `basePath`: the platform reserves /.writedocs/ and never
47
+ * serves it. */
48
+ export const ACCESS_MAP_FILE = '.writedocs/access.json';
49
+
50
+ /** A navigation item's access rule, or null. */
51
+ export function accessOf(item) {
52
+ return item && typeof item === 'object' && typeof item.access === 'string' ? item.access : null;
53
+ }
54
+
55
+ /** Whether a padlock shows on the item where it's listed. */
56
+ export function isLocked(item) {
57
+ return Boolean(accessOf(item) && item.lock === true);
58
+ }
59
+
60
+ /** The rule on a section's path - its innermost protected item's - or null. */
61
+ export function ruleOf(path = []) {
62
+ let rule = null;
63
+ for (const segment of path) rule = accessOf(segment.items[segment.index]) ?? rule;
64
+ return rule;
65
+ }
66
+
67
+ /** Each item of the navigation, with the rule that applies to it (its own or
68
+ * the closest one above it) - `global.dropdowns` aren't walked: the
69
+ * validator refuses `access` there. */
70
+ function walkItems(navigation, visit) {
71
+ const walk = (node, rule) => {
72
+ if (!node || typeof node !== 'object') return;
73
+ for (const [key] of CHILD_KINDS) {
74
+ if (!Array.isArray(node[key])) continue;
75
+ for (const item of node[key]) {
76
+ const inner = accessOf(item) ?? rule;
77
+ visit(item, inner);
78
+ walk(item, inner);
79
+ }
80
+ }
81
+ };
82
+ if (navigation && !Array.isArray(navigation)) walk(navigation, null);
83
+ }
84
+
85
+ /** Whether any item of the navigation names an access rule. */
86
+ export function usesAccess(navigation) {
87
+ let found = false;
88
+ walkItems(navigation, (item) => {
89
+ if (accessOf(item)) found = true;
90
+ });
91
+ return found;
92
+ }
93
+
94
+ /** The JSON path of the first `access` in the navigation - for a warning's
95
+ * line in writedocs.json - or null. */
96
+ export function firstAccessPath(navigation) {
97
+ const find = (node, path) => {
98
+ if (!node || typeof node !== 'object') return null;
99
+ for (const [key] of CHILD_KINDS) {
100
+ if (!Array.isArray(node[key])) continue;
101
+ for (let i = 0; i < node[key].length; i++) {
102
+ const itemPath = [...path, key, i];
103
+ if (accessOf(node[key][i])) return [...itemPath, 'access'];
104
+ const inner = find(node[key][i], itemPath);
105
+ if (inner) return inner;
106
+ }
107
+ }
108
+ return null;
109
+ };
110
+ return navigation && !Array.isArray(navigation) ? find(navigation, ['navigation']) : null;
111
+ }
112
+
113
+ /** The access rules the navigation names, in order, without repeats. */
114
+ export function accessRules(navigation) {
115
+ const rules = new Set();
116
+ walkItems(navigation, (item) => {
117
+ const rule = accessOf(item);
118
+ if (rule) rules.add(rule);
119
+ });
120
+ return [...rules];
121
+ }
122
+
123
+ /** Every protected page - Map<page id, rule> - by the id writedocs.json
124
+ * names it with (fileIdForEntry() in lib/config.ts): the pages in a
125
+ * protected item's sidebar, however deep, and its own `page`. A page listed
126
+ * under two items keeps the first rule found; a page under any rule is
127
+ * protected, wherever else it's listed. */
128
+ export function protectedPages(navigation) {
129
+ const pages = new Map();
130
+ const add = (id, rule) => {
131
+ const key = navPageId(id);
132
+ if (!pages.has(key)) pages.set(key, rule);
133
+ };
134
+ const collect = (list, rule) => {
135
+ for (const entry of list) {
136
+ if (typeof entry === 'string') add(entry, rule);
137
+ else if (entry && typeof entry === 'object' && !('href' in entry)) {
138
+ if (typeof entry.page === 'string') add(entry.page, rule);
139
+ if (Array.isArray(entry.pages)) collect(entry.pages, rule);
140
+ }
141
+ }
142
+ };
143
+ walkItems(navigation, (item, rule) => {
144
+ if (!rule) return;
145
+ const own = itemPage(item);
146
+ if (own !== null) add(own, rule);
147
+ if (Array.isArray(item.pages)) collect(item.pages, rule);
148
+ });
149
+ return pages;
150
+ }
151
+
152
+ /** The search space of a section - `{ id, searchPublic }` - or null for the
153
+ * public pages. Under a rule: one space per rule, `access.<rule>`, and,
154
+ * when the section is also inside a hidden item, one per hidden item in
155
+ * the rule, `access.<rule>.<hidden space id>` - so a hidden part keeps
156
+ * its search to itself (lib/hidden-sections.js), and a reader signed in to
157
+ * a rule never gets another rule's pages from a search. Without a rule,
158
+ * the hidden item's space, as before. `searchPublic` is the innermost
159
+ * hidden or protected item's. A "." can't be in a rule's name or a hidden
160
+ * space's id, so no two spaces share an id. `rule` defaults to the path's
161
+ * (ruleOf()); a page's own rule can be passed in. */
162
+ export function searchSpaceOf(path = [], rule = ruleOf(path)) {
163
+ const hidden = spaceOf(path);
164
+ if (!rule) return hidden;
165
+ let searchPublic = false;
166
+ for (const segment of path) {
167
+ const item = segment.items[segment.index];
168
+ if (isHidden(item) || accessOf(item)) searchPublic = item.searchPublic === true;
169
+ }
170
+ return { id: hidden ? `access.${rule}.${hidden.id}` : `access.${rule}`, searchPublic };
171
+ }
172
+
173
+ /** The rule whose pages a search space holds, or null for a public or
174
+ * hidden one. */
175
+ export function ruleOfSpace(spaceId) {
176
+ const match = /^access\.([a-z0-9-]+)(?:\.|$)/.exec(spaceId);
177
+ return match ? match[1] : null;
178
+ }
179
+
180
+ /**
181
+ * The map the platform protects a site by - what goes in
182
+ * dist/.writedocs/access.json:
183
+ *
184
+ * { "version": 1, "basePath": "/docs", "rules": { "<rule>": { "paths": [...], "prefixes": [...] } } }
185
+ *
186
+ * `paths` are exact paths as the serving sees them (the basePath in front);
187
+ * `prefixes` are folders (ending in "/") whose every file is the rule's.
188
+ * Built from:
189
+ * - `rules`: every rule writedocs.json names (accessRules()) - each one is
190
+ * in the map, even with nothing to protect (every page under it a draft),
191
+ * so the platform can tell the author a rule isn't set up;
192
+ * - `routes`: the protected addresses the build rendered, `{ slug, rule }`
193
+ * - pages, and the folder redirects that lead only to protected pages
194
+ * ([...slug].astro writes the list); slug "index" is the site's root;
195
+ * - `exists(relPath)`: whether the site folder has a file, for the copies
196
+ * made from a page - its Markdown (`<slug>.md`) and its link-preview
197
+ * image (`og/<slug>.png`);
198
+ * - `spaces`: the search spaces the build indexed (run-pagefind.js).
199
+ * Each page is listed with and without its trailing slash and as its
200
+ * index.html - every way a static host answers for it. Sorted, so the same
201
+ * site gives the same file.
202
+ */
203
+ export function accessMap({ rules: named = [], routes, spaces = [], exists = () => false, basePath = '' }) {
204
+ const rules = new Map();
205
+ const ruleEntry = (rule) => {
206
+ if (!rules.has(rule)) rules.set(rule, { paths: new Set(), prefixes: new Set() });
207
+ return rules.get(rule);
208
+ };
209
+ const at = (address) => `${basePath}${address}`;
210
+ named.forEach(ruleEntry);
211
+ for (const { slug, rule } of routes) {
212
+ const entry = ruleEntry(rule);
213
+ if (slug === 'index') {
214
+ entry.paths.add(at('/'));
215
+ if (basePath) entry.paths.add(basePath);
216
+ entry.paths.add(at('/index.html'));
217
+ } else {
218
+ entry.paths.add(at(`/${slug}/`));
219
+ entry.paths.add(at(`/${slug}`));
220
+ entry.paths.add(at(`/${slug}/index.html`));
221
+ }
222
+ for (const copy of [`${slug}.md`, `og/${slug}.png`]) {
223
+ if (exists(copy)) entry.paths.add(at(`/${copy}`));
224
+ }
225
+ }
226
+ for (const space of spaces) {
227
+ const rule = ruleOfSpace(space);
228
+ if (rule) ruleEntry(rule).prefixes.add(at(`/pagefind-spaces/${space}/`));
229
+ }
230
+ const sorted = [...rules.keys()].sort();
231
+ return {
232
+ version: ACCESS_MAP_VERSION,
233
+ basePath,
234
+ rules: Object.fromEntries(
235
+ sorted.map((rule) => [rule, { paths: [...rules.get(rule).paths].sort(), prefixes: [...rules.get(rule).prefixes].sort() }])
236
+ ),
237
+ };
238
+ }
@@ -77,6 +77,8 @@ import ApiReferencePanel from "../components/ApiReferencePanel.astro";
77
77
  import { searchScope, sectionTrail, ALL_SCOPES } from "../lib/search-scope.js";
78
78
  import { selectorPlacements } from "../lib/selector-placement.js";
79
79
  import { spaceOf } from "../lib/hidden-sections.js";
80
+ import { protectedPages, searchSpaceOf } from "../lib/protected-sections.js";
81
+ import { isNoindex } from "../lib/seo-tags.js";
80
82
  import { navigationPageOrder } from "../lib/pages.js";
81
83
  import { folderRedirects } from "../lib/folder-redirects.js";
82
84
  import { DRAFT_BANNER_HTML } from "../lib/drafts.js";
@@ -303,8 +305,12 @@ export async function getStaticPaths() {
303
305
  // (`/docs/creator/`) redirect to the first page under them
304
306
  // (lib/folder-redirects.js). Preferred in the reader's order: navigation
305
307
  // order, public sections before hidden ones, pages outside the
306
- // navigation last.
308
+ // navigation after them - and protected pages (lib/protected-sections.js)
309
+ // last, so a folder with any page anyone can read leads to one.
307
310
  const slugOf = (route: { params: { slug?: string } }) => route.params.slug ?? "index";
311
+ const protectedRules = protectedPages(config.navigation);
312
+ const ruleOfRoute = (route: { props: { entry?: DocsEntry } }) =>
313
+ route.props.entry ? (protectedRules.get(fileIdForEntry(contentDir, packageRoot, route.props.entry)) ?? null) : null;
308
314
  const inHiddenSection = sections.map((section) => spaceOf(section.path) !== null);
309
315
  const contentRoutes = pageRoutes.filter((route) => !("redirectTo" in route.props));
310
316
  // An item's own page counts where the navigation names it: before the
@@ -325,25 +331,44 @@ export async function getStaticPaths() {
325
331
  ...contentRoutes,
326
332
  ...landingRoutes.filter((route) => !("redirectTo" in route.props)),
327
333
  ] as ContentRoute[];
334
+ const isProtected = (route: ContentRoute) => ruleOfRoute(route) !== null;
328
335
  const folderTargets = [
329
336
  ...navContent
330
- .filter((route) => !inHiddenItem(route))
337
+ .filter((route) => !inHiddenItem(route) && !isProtected(route))
331
338
  .sort((a, b) => orderOf(a) - orderOf(b))
332
339
  .map(slugOf),
333
340
  ...navContent
334
- .filter(inHiddenItem)
341
+ .filter((route) => inHiddenItem(route) && !isProtected(route))
335
342
  .sort((a, b) => orderOf(a) - orderOf(b))
336
343
  .map(slugOf),
337
344
  ...hiddenRoutes.map(slugOf),
345
+ ...navContent
346
+ .filter(isProtected)
347
+ .sort((a, b) => orderOf(a) - orderOf(b))
348
+ .map(slugOf),
338
349
  ];
339
350
  const takenAddresses = new Set([
340
351
  ...[...pageRoutes, ...landingRoutes, ...hiddenRoutes].map(slugOf),
341
352
  ...(config.redirects ?? []).map((r) => r.source.replace(/^\/+|\/+$/g, "")),
342
353
  ]);
343
- const folderRoutes = [...folderRedirects(folderTargets, takenAddresses)].map(([folder, target]) => ({
344
- params: { slug: folder },
345
- props: { redirectTo: `/${target}/`, temporary: true },
346
- }));
354
+ // The protected addresses, `{ slug, rule }`: the pages, and a folder
355
+ // redirect that leads to one - its folder has no other page, and the
356
+ // redirect page names the page, so it's behind the same rule.
357
+ const protectedRoutes = navContent.flatMap((route) => {
358
+ const rule = ruleOfRoute(route);
359
+ return rule ? [{ slug: slugOf(route), rule }] : [];
360
+ });
361
+ const ruleBySlug = new Map(protectedRoutes.map((route) => [route.slug, route.rule]));
362
+ const folderRoutes = [...folderRedirects(folderTargets, takenAddresses)].map(([folder, target]) => {
363
+ const rule = ruleBySlug.get(target);
364
+ if (rule) protectedRoutes.push({ slug: folder, rule });
365
+ return { params: { slug: folder }, props: { redirectTo: `/${target}/`, temporary: true } };
366
+ });
367
+ // `writedocs build` names a file here; the build makes
368
+ // dist/.writedocs/access.json from it (lib/protected-sections.js,
369
+ // src/cli/build.js) - the og route hands its list over the same way.
370
+ const accessFile = process.env.WRITEDOCS_ACCESS_FILE;
371
+ if (accessFile) fs.writeFileSync(accessFile, JSON.stringify(protectedRoutes));
347
372
 
348
373
  return [...rootRedirect, ...pageRoutes, ...landingRoutes, ...hiddenRoutes, ...folderRoutes];
349
374
  }
@@ -475,6 +500,9 @@ const hrefForSlug = (slug: string) => {
475
500
  // and what every "is this the active page" comparison below needs, since
476
501
  // navTree/globalDropdowns are built from writedocs.json's file-id space.
477
502
  const currentFileId = fileIdForEntry(contentDir, packageRoot, entry);
503
+ // The access rule the page is behind, or null (lib/protected-sections.js).
504
+ const protectedRules = oncePerBuild("slug:protected", () => protectedPages(config.navigation));
505
+ const pageRule = protectedRules.get(currentFileId) ?? null;
478
506
  // A section's tree doesn't depend on which of its pages is open (NavTree.astro
479
507
  // marks the current one), so it's built once per section in a build.
480
508
  const navTree = oncePerBuild(`slug:nav:${landingIndex === undefined ? `s${sectionIndex}` : `l${landingIndex}`}`, () =>
@@ -514,9 +542,10 @@ const pageSearchScope = isHidden ? { key: ALL_SCOPES, label: "" } : searchScope(
514
542
  const pageSectionTrail = [entry.data.draft ? "Draft" : "", isHidden ? "" : sectionTrail(activeSection.path, breadcrumbs)]
515
543
  .filter(Boolean)
516
544
  .join(" · ");
517
- // A page under a hidden navigation item searches its own index, not the
518
- // site's (lib/hidden-sections.js, cli/run-pagefind.js).
519
- const pageSearchSpace = isHidden ? null : spaceOf(activeSection.path);
545
+ // A page under a hidden or a protected navigation item searches its own
546
+ // index, not the site's (lib/hidden-sections.js, lib/protected-sections.js,
547
+ // cli/run-pagefind.js) - a protected page by its rule.
548
+ const pageSearchSpace = isHidden ? null : searchSpaceOf(activeSection.path, pageRule);
520
549
  const languageSegment = isHidden ? undefined : activeSection.path.find((segment) => segment.kind === "language");
521
550
  const pageLang = languageSegment
522
551
  ? (languageSegment.items[languageSegment.index] as { language: string }).language
@@ -536,6 +565,12 @@ const globalDropdowns = buildGlobalDropdowns(
536
565
  // than recomputing it, since it already encodes the same
537
566
  // frontmatter-slug-override-aware routing logic.
538
567
  const pageSeo = mergeSeo(config.seo, entry.data.seo);
568
+ // A protected page (lib/protected-sections.js) is never indexed, whatever
569
+ // its own `seo` says - a `robots` that allows indexing gives way.
570
+ if (pageRule) {
571
+ if (!isNoindex(pageSeo)) pageSeo.robots = undefined;
572
+ pageSeo.noindex = true;
573
+ }
539
574
  // A page with no picture of its own for link previews gets the generated
540
575
  // card (lib/og-image.js, served by src/pages/og/[...slug].png.ts).
541
576
  if (wantsGeneratedCard(pageSeo, entry.data, config.seo)) pageSeo.ogImage = ogImagePath(normalizeEntryId(entry.id));
@@ -544,10 +579,14 @@ const currentPath = hrefForSlug(currentFileId);
544
579
  // lib/item-pages.js) - a hidden page belongs to no language level.
545
580
  const alternates = isHidden
546
581
  ? []
547
- : languageAlternates(activeSection.path, currentFileId, activeSection.pages, landing !== undefined).map((a) => ({
548
- lang: a.lang,
549
- href: hrefForSlug(a.slug),
550
- }));
582
+ : languageAlternates(activeSection.path, currentFileId, activeSection.pages, landing !== undefined)
583
+ // Not a protected page in another language: a search engine can't
584
+ // read it (a protected page itself lists none - it's noindex).
585
+ .filter((a) => !protectedRules.has(a.slug))
586
+ .map((a) => ({
587
+ lang: a.lang,
588
+ href: hrefForSlug(a.slug),
589
+ }));
551
590
  // The trail for the page's structured data (lib/json-ld.js): home, the
552
591
  // groups above the page that have a page of their own, the page.
553
592
  const structuredTrail = [
@@ -7,6 +7,7 @@ import { writedocsTempDir } from '../lib/writedocs-temp-dir.js';
7
7
  import { pageMarkdown } from '../lib/openapi-markdown';
8
8
  import { orderByNavigation } from '../lib/llms.js';
9
9
  import { readProjectText } from '../lib/config-file.js';
10
+ import { protectedPages } from '../lib/protected-sections.js';
10
11
 
11
12
  // The "everything, concatenated" half of the llms.txt pair - see
12
13
  // llms.txt.ts (right next to this file) for the lightweight index half,
@@ -47,10 +48,13 @@ export const GET: APIRoute = async () => {
47
48
  ]);
48
49
  const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
49
50
 
51
+ const protectedRules = protectedPages(config.navigation);
50
52
  const unordered = entries
51
53
  // Same noindex exclusion llms.txt.ts applies to its own listing -
52
54
  // see that file's comment.
53
55
  .filter((entry) => !entry.data.seo?.noindex)
56
+ // Same for a protected page (lib/protected-sections.js).
57
+ .filter((entry) => !protectedRules.has(fileIdForEntry(contentDir, packageRoot, entry)))
54
58
  // Same `url` exclusion as llms.txt.ts - a redirect, not a page.
55
59
  .filter((entry) => !entry.data.url)
56
60
  .map((entry: DocsEntry) => {
@@ -2,7 +2,8 @@ import { getCollection, type CollectionEntry } from 'astro:content';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import type { APIRoute } from 'astro';
5
- import { loadDocsConfig, normalizeEntryId, findAllPages, mergeSeo } from '../../lib/config';
5
+ import { loadDocsConfig, normalizeEntryId, findAllPages, mergeSeo, fileIdForEntry } from '../../lib/config';
6
+ import { protectedPages } from '../../lib/protected-sections.js';
6
7
  import { writedocsTempDir } from '../../lib/writedocs-temp-dir.js';
7
8
  import { ogImagePng } from '../../lib/og-image.js';
8
9
  import { ogCardSet, ogCardOptions } from '../../lib/og-cards.js';
@@ -36,9 +37,17 @@ export async function getStaticPaths() {
36
37
  ]);
37
38
  const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
38
39
 
40
+ // A protected page (lib/protected-sections.js) is noindex, and a noindex
41
+ // page gets no card - its link preview is the sign-in page's anyway.
42
+ const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
43
+ const protectedRules = protectedPages(config.navigation);
39
44
  const set = ogCardSet(
40
45
  config,
41
- entries.map((entry) => ({ id: normalizeEntryId(entry.id), data: entry.data, seo: mergeSeo(config.seo, entry.data.seo) })),
46
+ entries.map((entry) => {
47
+ const seo = mergeSeo(config.seo, entry.data.seo);
48
+ if (protectedRules.has(fileIdForEntry(contentDir, packageRoot, entry))) seo.noindex = true;
49
+ return { id: normalizeEntryId(entry.id), data: entry.data, seo };
50
+ }),
42
51
  contentDir
43
52
  );
44
53
  const listFile = process.env.WRITEDOCS_OG_CARDS_FILE;