@opentf/afw-docs 0.0.0-stage → 0.31.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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -2
  3. package/build/blog-posts-plugin.js +154 -0
  4. package/build/docs-nav-plugin.js +200 -0
  5. package/build/feed.js +176 -0
  6. package/build/frontmatter.js +45 -0
  7. package/build/host.js +54 -0
  8. package/build/index.js +13 -0
  9. package/build/last-updated-plugin.js +107 -0
  10. package/build/last-updated.js +40 -0
  11. package/build/llms.js +176 -0
  12. package/build/publish.js +29 -0
  13. package/build/reading-time.js +16 -0
  14. package/build/search.js +27 -0
  15. package/components/BlogLayout.jsx +104 -0
  16. package/components/Breadcrumbs.jsx +71 -0
  17. package/components/Callout.jsx +29 -0
  18. package/components/Card.jsx +21 -0
  19. package/components/Cards.jsx +11 -0
  20. package/components/CodeBlock.jsx +39 -0
  21. package/components/DocsLayout.jsx +106 -0
  22. package/components/FeedLinks.jsx +47 -0
  23. package/components/Footer.jsx +25 -0
  24. package/components/LastUpdated.jsx +20 -0
  25. package/components/NavIcon.jsx +34 -0
  26. package/components/Navbar.jsx +64 -0
  27. package/components/NavbarLink.jsx +40 -0
  28. package/components/Pagination.jsx +49 -0
  29. package/components/PostBanner.jsx +25 -0
  30. package/components/PostCard.jsx +24 -0
  31. package/components/PostList.jsx +25 -0
  32. package/components/PostMeta.jsx +37 -0
  33. package/components/ReadingTime.jsx +6 -0
  34. package/components/Search.jsx +191 -0
  35. package/components/SearchTrigger.jsx +32 -0
  36. package/components/Sidebar.jsx +199 -0
  37. package/components/SidebarNode.jsx +143 -0
  38. package/components/SidebarToggle.jsx +47 -0
  39. package/components/Steps.jsx +14 -0
  40. package/components/Table.jsx +10 -0
  41. package/components/Tabs.jsx +77 -0
  42. package/components/ThemeToggle.jsx +164 -0
  43. package/components/Toc.jsx +106 -0
  44. package/components/Tooltip.jsx +19 -0
  45. package/components/format.js +21 -0
  46. package/components/post-dates.js +21 -0
  47. package/components/sidebar-collapse.js +38 -0
  48. package/config.js +77 -0
  49. package/index.js +69 -0
  50. package/nav-virtual.js +18 -0
  51. package/package.json +79 -4
  52. package/posts-virtual.js +17 -0
  53. package/search.js +285 -0
  54. package/theme/index.css +1843 -0
  55. package/types/config.d.ts +39 -0
  56. package/types/index.d.ts +70 -0
  57. package/types/nav.d.ts +9 -0
  58. package/types/posts.d.ts +17 -0
  59. package/types/search.d.ts +28 -0
  60. package/types/updated.d.ts +4 -0
  61. package/updated-virtual.js +10 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Open Tech Foundation and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,142 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @opentf/afw-docs
4
+
5
+ ***Documentation and blog sites built as ordinary AFW apps***
6
+
7
+ [Docs](https://afw.opentechf.org/packages/afw-docs) | [API](https://afw.opentechf.org/api/afw-docs) | [Changelog](https://github.com/Open-Tech-Foundation/afw/blob/main/packages/afw-docs/CHANGELOG.md) | [GitHub](https://github.com/Open-Tech-Foundation/afw)
8
+
9
+ </div>
10
+
11
+ <div align="right">
12
+
13
+ *An [Open Tech Foundation](https://opentechf.org/) project*
14
+
15
+ </div>
16
+
17
+ > Write pages as MDX in `app/`. The theme supplies the navbar, sidebar, table of
18
+ > contents, breadcrumbs, search and prev/next links, and generates the navigation
19
+ > from your folders at build time. The [AFW website](https://afw.opentechf.org) is
20
+ > built with it.
21
+
22
+ ```jsx
23
+ // app/docs/layout.jsx
24
+ import { DocsLayout } from "@opentf/afw-docs";
25
+ import config from "../../afw.config.js";
26
+
27
+ export default function Layout(props) {
28
+ return <DocsLayout config={config.docs}>{props.children}</DocsLayout>;
29
+ }
30
+ ```
31
+
32
+ ```mdx
33
+ ---
34
+ title: Reactivity
35
+ description: Signal-based state.
36
+ ---
37
+
38
+ import { Callout } from "@opentf/afw-docs";
39
+
40
+ # Reactivity
41
+
42
+ <Callout type="tip">Mix components into Markdown freely.</Callout>
43
+ ```
44
+
45
+ Every folder under `app/` with a layout like this becomes its own section with its
46
+ own sidebar: `app/docs` serves `/docs` and `app/api` serves `/api`.
47
+
48
+ > [!NOTE]
49
+ > **Alpha.** Components, options and class names can change between minor
50
+ > versions; see the [changelog](https://github.com/Open-Tech-Foundation/afw/blob/main/packages/afw-docs/CHANGELOG.md).
51
+
52
+ ## Why afw-docs
53
+
54
+ | Need | How afw-docs meets it |
55
+ | --- | --- |
56
+ | 🧭 **Navigation from folders** | The sidebar, breadcrumbs and prev/next are generated from `app/`; `_meta.js` sets order and labels |
57
+ | 🔎 **Search without a service** | A static index built from the prerendered HTML by `afwc`, queried in the browser |
58
+ | ✍️ **MDX with components** | Callouts, tabs, steps, cards and code blocks with copy buttons, highlighted at build time |
59
+ | 📰 **Blog included** | Post lists, banners, reading time and RSS/Atom feeds |
60
+ | 🕒 **Last updated and edit links** | Dates from git history or frontmatter, linked to the source file |
61
+ | 🌗 **Themeable** | Light and dark modes driven by `--afw-*` CSS variables, in an overridable cascade layer |
62
+ | 🤖 **LLM-ready** | `llms.txt` and `llms-full.txt` generated at build |
63
+
64
+ ## Install
65
+
66
+ ```sh
67
+ pnpm add @opentf/afw-docs @opentf/afw
68
+ pnpm add -D @opentf/esdev-plugin-afw @opentf/afw-cli
69
+ ```
70
+
71
+ `esdev create my-docs --template=docs` generates a complete site. To add the theme
72
+ to an existing project, import its stylesheet and register the build plugins:
73
+
74
+ ```css
75
+ /* app/global.css */
76
+ @import "@opentf/afw-docs/theme";
77
+ ```
78
+
79
+ ```json
80
+ {
81
+ "plugins": [
82
+ { "module": "@opentf/esdev-plugin-afw", "options": { "mode": "ssg" } },
83
+ { "module": "@opentf/afw-docs/build", "export": "docsNavPlugin", "options": { "appDir": "app" } },
84
+ { "module": "@opentf/afw-docs/build", "export": "lastUpdatedPlugin", "options": { "appDir": "app" } },
85
+ { "module": "@opentf/afw-docs/build", "export": "blogPostsPlugin", "options": { "appDir": "app", "contentDir": "blog" } }
86
+ ]
87
+ }
88
+ ```
89
+
90
+ `appDir` is resolved from the directory esdev runs in.
91
+
92
+ ## Configure
93
+
94
+ ```js
95
+ // afw.config.js
96
+ import { defineDocsConfig } from "@opentf/afw-docs/config";
97
+
98
+ export default defineDocsConfig({
99
+ site: { url: "https://docs.example.com" },
100
+ docs: {
101
+ title: "My Project",
102
+ github: "https://github.com/me/my-project",
103
+ repoUrl: "https://github.com/me/my-project",
104
+ nav: [
105
+ { label: "Docs", href: "/docs" },
106
+ { label: "Blog", href: "/blog" },
107
+ ],
108
+ lastUpdated: true,
109
+ },
110
+ });
111
+ ```
112
+
113
+ ## Components
114
+
115
+ | Group | Components |
116
+ | --- | --- |
117
+ | **Layouts** | `DocsLayout`, `BlogLayout` |
118
+ | **Shell** | `Navbar`, `NavbarLink`, `Sidebar`, `SidebarToggle`, `Toc`, `Breadcrumbs`, `Pagination`, `Footer`, `LastUpdated`, `ThemeToggle`, `Search`, `SearchTrigger` |
119
+ | **Content** | `Callout`, `Tabs`, `Steps`, `CodeBlock`, `Table`, `Cards`, `Card`, `Tooltip`, `NavIcon` |
120
+ | **Blog** | `PostList`, `PostCard`, `PostBanner`, `PostMeta`, `ReadingTime` |
121
+
122
+ ## Entry points
123
+
124
+ | Import | Contents |
125
+ | --- | --- |
126
+ | `@opentf/afw-docs` | Every component above, plus `createSearch` |
127
+ | `@opentf/afw-docs/theme` | The default light/dark stylesheet |
128
+ | `@opentf/afw-docs/config` | `defineDocsConfig` and the config types |
129
+ | `@opentf/afw-docs/build` | `docsNavPlugin`, `blogPostsPlugin`, `lastUpdatedPlugin`, feed and `llms.txt` renderers |
130
+ | `@opentf/afw-docs/nav`, `/posts`, `/updated` | Generated navigation, post list and last-updated map |
131
+ | `@opentf/afw-docs/search` | Browser search: `createSearch`, `tokenize`, `excerptParts` |
132
+
133
+ ## Styling
134
+
135
+ The theme's own elements use `afwd-*` classes (`.afwd-sidebar`, `.afwd-callout-tip`),
136
+ and its colours come from `--afw-*` variables that switch on `[data-theme='dark']`.
137
+ All theme rules sit in the `afw-docs` cascade layer, so any rule in your own
138
+ stylesheet overrides them without raising specificity.
139
+
140
+ ## License
141
+
142
+ MIT — see [LICENSE](https://github.com/Open-Tech-Foundation/afw/blob/main/LICENSE).
@@ -0,0 +1,154 @@
1
+ // Build-time blog post index generator (a Rolldown plugin), the blog counterpart of
2
+ // docs-nav-plugin.js. It scans `app/<dir>` for post folders (`<slug>/page.{mdx,md}`),
3
+ // reads each post's frontmatter + computes its reading time, and resolves the virtual
4
+ // module `@opentf/afw-docs/posts` to the ordered post list. A pure build-time
5
+ // consumer of the file tree — no compiler stage, no runtime cost.
6
+ //
7
+ // Post shape: `{ slug, path, title, description?, date?, updated?, author?, tags?,
8
+ // readingTime, order? }`. Sorted newest-first by `date`; a numeric `order` (frontmatter)
9
+ // overrides. Drafts and future-dated posts are left out except under `esdev start`
10
+ // (see publish.js).
11
+
12
+ import { join } from "runtime:path";
13
+
14
+ import { exists, readEntries, readNames, readText } from "./host.js";
15
+
16
+ import { readFrontmatter } from "./frontmatter.js";
17
+ import { readingTime } from "./reading-time.js";
18
+ import { frontmatterUpdated, isUnpublished, showsUnpublished } from "./publish.js";
19
+
20
+ const VIRTUAL_ID = "@opentf/afw-docs/posts";
21
+ // No NUL sentinel: the bundler marks a module virtual explicitly, and a `\0` in
22
+ // a hook filter is an invalid regex — which silently matches *everything*.
23
+ const RESOLVED_ID = "afw-virtual:afw-blog-posts";
24
+ const PAGE_RE = /^page\.(mdx|md)$/;
25
+
26
+ /**
27
+ * @param {Object} opts
28
+ * @param {string} opts.appDir Absolute path to the project's `app/` directory.
29
+ * @param {string} [opts.contentDir] Blog content folder under app/ (default "blog").
30
+ * @param {Set<string>} [opts.exclude] Folder names to skip.
31
+ * @param {boolean} [opts.drafts] List drafts and scheduled posts (default: only under
32
+ * `esdev start`).
33
+ */
34
+ export function blogPostsPlugin({ appDir, contentDir = "blog", exclude = new Set(), drafts } = {}) {
35
+ const root = join(appDir, contentDir);
36
+ const base = "/" + contentDir;
37
+ return {
38
+ name: "afw-blog-posts",
39
+ resolve: {
40
+ filter: { id: VIRTUAL_ID },
41
+ handler: (source) => (source === VIRTUAL_ID ? { id: RESOLVED_ID, virtual: true } : null),
42
+ },
43
+ load: {
44
+ filter: { id: RESOLVED_ID },
45
+ async handler(id, ctx) {
46
+ if (id !== RESOLVED_ID) return null;
47
+ const watch = [];
48
+ const all = showsUnpublished(drafts, ctx);
49
+ const posts = (await exists(root)) ? await collectPosts(root, base, exclude, watch, all) : [];
50
+ // The post list is generated from these files, which nothing imports —
51
+ // declaring them is what rebuilds the chunk when a post's frontmatter changes.
52
+ return {
53
+ code: `export const posts = ${JSON.stringify(posts)};\nexport default posts;\n`,
54
+ dependsOn: watch,
55
+ };
56
+ },
57
+ },
58
+ };
59
+ }
60
+
61
+ /**
62
+ * Scan the blog content folder and return the ordered post list — the same array the
63
+ * `blogPostsPlugin` virtual module exposes, but callable directly (used by the feed
64
+ * generator at build time). Returns `[]` when the folder is absent.
65
+ *
66
+ * @param {Object} opts
67
+ * @param {string} opts.appDir
68
+ * @param {string} [opts.contentDir]
69
+ * @param {Set<string>} [opts.exclude]
70
+ * @param {boolean} [opts.drafts] Include drafts and scheduled posts (default false: this
71
+ * feeds production output).
72
+ */
73
+ export async function loadPosts({ appDir, contentDir = "blog", exclude = new Set(), drafts = false } = {}) {
74
+ const root = join(appDir, contentDir);
75
+ if (!(await exists(root))) return [];
76
+ return collectPosts(root, "/" + contentDir, exclude, [], drafts);
77
+ }
78
+
79
+ // Automatic post metadata describes concrete folders; generated parameters are
80
+ // unavailable during this scan and must not become card or feed URLs.
81
+ async function collectPosts(root, base, exclude, watch, drafts) {
82
+ const posts = [];
83
+ for (const entry of await readEntries(root)) {
84
+ if (
85
+ !entry.isDir ||
86
+ entry.name.startsWith(".") ||
87
+ entry.name.startsWith("_") ||
88
+ /\[[^\]]+\]/.test(entry.name) ||
89
+ exclude.has(entry.name)
90
+ ) {
91
+ continue;
92
+ }
93
+ const dir = join(root, entry.name);
94
+ const page = (await readNames(dir)).find((n) => PAGE_RE.test(n));
95
+ if (!page) continue;
96
+
97
+ const file = join(dir, page);
98
+ watch.push(file);
99
+ const source = await readText(file);
100
+ const fm = await readFrontmatter(file);
101
+ if (!drafts && isUnpublished(fm)) continue;
102
+ posts.push(
103
+ clean({
104
+ slug: entry.name,
105
+ path: `${base}/${entry.name}`,
106
+ title: fm.title ?? humanize(entry.name),
107
+ description: fm.description,
108
+ date: fm.date != null ? String(fm.date) : undefined,
109
+ // Frontmatter only, never git: a bulk commit (a rename, a reformat) touches
110
+ // every post without changing what any of them says.
111
+ updated: frontmatterUpdated(fm),
112
+ draft: drafts && isUnpublished(fm) ? true : undefined,
113
+ // Cover image (frontmatter `cover`) — shown on the post banner and the card.
114
+ cover: fm.cover,
115
+ author: fm.author,
116
+ authorAvatar: fm.author_avatar,
117
+ authorRole: fm.author_role,
118
+ // Frontmatter is flat scalars, so `tags: a, b` arrives as a string; normalize
119
+ // to a trimmed array. Components can render chips from it.
120
+ tags: typeof fm.tags === "string" ? splitTags(fm.tags) : undefined,
121
+ readingTime: readingTime(source),
122
+ order: typeof fm.order === "number" ? fm.order : undefined,
123
+ }),
124
+ );
125
+ }
126
+ return sortPosts(posts);
127
+ }
128
+
129
+ /** Newest-first by `date`; a numeric `order` wins when present; title breaks ties. */
130
+ function sortPosts(posts) {
131
+ return posts.sort((a, b) => {
132
+ if (a.order != null || b.order != null) {
133
+ return (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER);
134
+ }
135
+ if (a.date && b.date && a.date !== b.date) return a.date < b.date ? 1 : -1;
136
+ if (a.date && !b.date) return -1;
137
+ if (!a.date && b.date) return 1;
138
+ return a.title.localeCompare(b.title);
139
+ });
140
+ }
141
+
142
+ function splitTags(s) {
143
+ const tags = s.split(",").map((t) => t.trim()).filter(Boolean);
144
+ return tags.length ? tags : undefined;
145
+ }
146
+
147
+ function humanize(seg) {
148
+ return seg.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
149
+ }
150
+
151
+ function clean(node) {
152
+ for (const k of Object.keys(node)) if (node[k] === undefined) delete node[k];
153
+ return node;
154
+ }
@@ -0,0 +1,200 @@
1
+ // Build-time navigation generator (a bundler plugin).
2
+ //
3
+ // The sidebar / breadcrumbs / prev-next need the whole documentation tree, which
4
+ // only exists on disk at build time. This plugin scans `app/<dir>` for routes,
5
+ // reads each folder's `_meta.{js,json}` for ordering + labels and each page's
6
+ // frontmatter for titles, and resolves `@opentf/afw-docs/nav` to a generated module
7
+ // exporting the ordered tree. It is a pure build-time *consumer* of the file tree
8
+ // (ARCHITECTURE.md §6) — no new compiler stage, no runtime cost.
9
+ //
10
+ // Tree node shape: `{ title, path?, order?, items?: Node[] }`. A node with `path`
11
+ // is a link; a node with `items` is a (possibly also linked) group.
12
+
13
+ import { join, toFileURL } from "runtime:path";
14
+
15
+ import { exists, readEntries, readNames, readText } from "./host.js";
16
+ import { readFrontmatter } from "./frontmatter.js";
17
+ import { isUnpublished, showsUnpublished } from "./publish.js";
18
+
19
+ const VIRTUAL_ID = "@opentf/afw-docs/nav";
20
+ // No NUL sentinel: the bundler marks a module virtual explicitly, and a `\0` in
21
+ // a hook filter is an invalid regex — which silently matches *everything*.
22
+ const RESOLVED_ID = "afw-virtual:afw-docs-nav";
23
+ const PAGE_RE = /^page\.(mdx|md|[jt]sx)$/;
24
+ const MD_RE = /\.(mdx|md)$/;
25
+
26
+ // Folder scans know route patterns, not the parameter values a page generates.
27
+ // Omit the whole branch so descendants never inherit a placeholder URL.
28
+ function navDirectory(entry, exclude) {
29
+ return entry.isDir && !entry.name.startsWith(".") &&
30
+ !entry.name.startsWith("_") && !exclude.has(entry.name) &&
31
+ !/\[[^\]]+\]/.test(entry.name);
32
+ }
33
+
34
+ /**
35
+ * Generates `@opentf/afw-docs/nav` as a **section map** — `{ "/<dir>": tree }`, one entry
36
+ * per top-level folder under `app/`. Each folder is a potential `DocsLayout` section; the
37
+ * layout selects its own subtree by the current route, so any number of sections (`/docs`,
38
+ * `/api`, …) "just work" with no config — drop a folder in and give it a `DocsLayout`.
39
+ *
40
+ * @param {Object} opts
41
+ * @param {string} opts.appDir Absolute path to the project's `app/` directory.
42
+ * @param {Set<string>} [opts.exclude] Folder names to skip (mirrors route exclusions).
43
+ * @param {(file: string) => Promise<any>} [opts.importModule] How to read a `_meta.js`.
44
+ * The dev server passes a loader that re-evaluates the file after an edit; a plain
45
+ * `import()` cannot, because the runtime caches ESM by path for the process's life.
46
+ * @param {boolean} [opts.drafts] List draft pages (default: only under `esdev start`).
47
+ */
48
+ export function docsNavPlugin({ appDir, exclude = new Set(), importModule, drafts } = {}) {
49
+ return {
50
+ name: "afw-docs-nav",
51
+ resolve: {
52
+ filter: { id: VIRTUAL_ID },
53
+ handler: (source) => (source === VIRTUAL_ID ? { id: RESOLVED_ID, virtual: true } : null),
54
+ },
55
+ load: {
56
+ filter: { id: RESOLVED_ID },
57
+ async handler(id, hookCtx) {
58
+ if (id !== RESOLVED_ID) return null;
59
+ const ctx = { watch: [], importModule, drafts: showsUnpublished(drafts, hookCtx) };
60
+ const out = {};
61
+ for (const entry of await readEntries(appDir)) {
62
+ if (!navDirectory(entry, exclude)) continue;
63
+ const base = "/" + entry.name;
64
+ out[base] = await buildSection(join(appDir, entry.name), base, ctx, true, exclude);
65
+ }
66
+ // The files this tree was generated from. They are not imports, so nothing else
67
+ // ties them to this module — declaring them is what makes the dev server rebuild the
68
+ // chunk holding the sidebar when a page's frontmatter or a `_meta.*` changes.
69
+ return { code: `export default ${JSON.stringify(out)};\n`, dependsOn: ctx.watch };
70
+ },
71
+ },
72
+ };
73
+ }
74
+
75
+ /** Load a folder's `_meta` (ordering + labels). Supports `.js`/`.mjs`/`.json`. */
76
+ async function loadMeta(dir, ctx) {
77
+ for (const name of ["_meta.js", "_meta.mjs", "_meta.json"]) {
78
+ const p = join(dir, name);
79
+ if (!(await exists(p))) continue;
80
+ ctx.watch.push(p);
81
+ try {
82
+ if (name.endsWith(".json")) return JSON.parse(await readText(p));
83
+ // A query string does not bust the ESM cache (it is keyed by path and ignores
84
+ // `?t=`), so a host that needs live `_meta` edits supplies a loader that can
85
+ // re-read the file; without one this is a plain, once-per-process import.
86
+ const mod = await (ctx.importModule?.(p) ?? import(toFileURL(p).href));
87
+ return mod.default ?? mod;
88
+ } catch (e) {
89
+ console.warn(`⚠ [@opentf/afw-docs] could not load ${p}: ${e?.message ?? e}`);
90
+ }
91
+ return null;
92
+ }
93
+ return null;
94
+ }
95
+
96
+ /** The `page.*` file directly in `dir`, or null. */
97
+ async function pageFile(dir) {
98
+ for (const name of await readNames(dir)) {
99
+ if (PAGE_RE.test(name)) return join(dir, name);
100
+ }
101
+ return null;
102
+ }
103
+
104
+ function humanize(seg) {
105
+ return seg.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
106
+ }
107
+
108
+ /** Order child keys: those named in `_meta` first (in declared order), rest A→Z. */
109
+ function orderKeys(keys, meta) {
110
+ if (!meta) return keys.slice().sort();
111
+ const metaKeys = Array.isArray(meta) ? meta : Object.keys(meta);
112
+ const named = metaKeys.filter((k) => keys.includes(k));
113
+ const rest = keys.filter((k) => !metaKeys.includes(k)).sort();
114
+ return [...named, ...rest];
115
+ }
116
+
117
+ /** A label declared in `_meta` for `key`, or null. */
118
+ function metaLabel(meta, key) {
119
+ if (!meta || Array.isArray(meta)) return null;
120
+ const v = meta[key];
121
+ if (typeof v === "string") return v;
122
+ if (v && typeof v === "object") return v.title ?? v.label ?? null;
123
+ return null;
124
+ }
125
+
126
+ /**
127
+ * Build the ordered items of a section directory. Each subdirectory becomes a child
128
+ * node (a link and/or a group). At the docs root (`withIndex`), the root's own
129
+ * `page.*` is emitted as a standalone "Overview"-style entry; in nested groups the
130
+ * folder's own page is the group node's link (added by `buildNode`), so it is not
131
+ * repeated here. Order + labels come from `_meta`.
132
+ */
133
+ async function buildSection(dir, route, ctx, withIndex = false, exclude = new Set()) {
134
+ const meta = await loadMeta(dir, ctx);
135
+ const entries = await readEntries(dir);
136
+ const subdirs = entries
137
+ .filter((entry) => navDirectory(entry, exclude))
138
+ .map((e) => e.name);
139
+
140
+ const items = [];
141
+
142
+ // The docs root's own landing page (e.g. app/docs/page.mdx → /docs).
143
+ const indexFile = withIndex ? await pageFile(dir) : null;
144
+ const keys = subdirs.slice();
145
+ if (indexFile) keys.unshift("index");
146
+
147
+ let ordered = orderKeys(keys, meta);
148
+ // Default the landing page to the top unless `_meta` orders it.
149
+ const metaOrdersIndex = meta && !Array.isArray(meta) && "index" in meta;
150
+ if (indexFile && !metaOrdersIndex) {
151
+ ordered = ["index", ...ordered.filter((k) => k !== "index")];
152
+ }
153
+
154
+ for (const key of ordered) {
155
+ if (key === "index") {
156
+ ctx.watch.push(indexFile);
157
+ const fm = MD_RE.test(indexFile) ? await readFrontmatter(indexFile) : {};
158
+ items.push(
159
+ clean({
160
+ title: metaLabel(meta, "index") ?? fm.sidebar_label ?? fm.title ?? "Overview",
161
+ path: route || "/",
162
+ order: fm.order,
163
+ }),
164
+ );
165
+ continue;
166
+ }
167
+ const node = await buildNode(join(dir, key), `${route}/${key}`, key, meta, ctx, exclude);
168
+ if (node) items.push(node);
169
+ }
170
+ return items;
171
+ }
172
+
173
+ /** Build a single subdirectory node: its own link (if it has a page) + children. */
174
+ async function buildNode(dir, route, key, parentMeta, ctx, exclude) {
175
+ const pf = await pageFile(dir);
176
+ let fm = {};
177
+ if (pf) {
178
+ ctx.watch.push(pf);
179
+ if (MD_RE.test(pf)) fm = await readFrontmatter(pf);
180
+ }
181
+ const children = await buildSection(dir, route, ctx, false, exclude);
182
+ // An unpublished page is left out of the production nav; its children still show.
183
+ const page = pf && (ctx.drafts || !isUnpublished(fm)) ? pf : null;
184
+ // A directory that has neither a page nor children contributes nothing.
185
+ if (!page && children.length === 0) return null;
186
+
187
+ const title = metaLabel(parentMeta, key) ?? fm.sidebar_label ?? fm.title ?? humanize(key);
188
+ return clean({
189
+ title,
190
+ path: page ? route : undefined,
191
+ order: fm.order,
192
+ items: children.length ? children : undefined,
193
+ });
194
+ }
195
+
196
+ /** Drop undefined fields so the emitted JSON stays small. */
197
+ function clean(node) {
198
+ for (const k of Object.keys(node)) if (node[k] === undefined) delete node[k];
199
+ return node;
200
+ }