@writedocs/generator 0.13.4 → 0.14.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 (89) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +359 -356
  4. package/package.json +99 -99
  5. package/src/cli/base-path-layout.js +44 -44
  6. package/src/cli/build-auth.js +135 -135
  7. package/src/cli/build.js +223 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +124 -124
  10. package/src/cli/dev.js +269 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +509 -507
  13. package/src/cli/og-image-worker.js +20 -20
  14. package/src/cli/og-images.js +70 -70
  15. package/src/cli/page-list-watch.js +71 -69
  16. package/src/cli/run-astro.js +97 -97
  17. package/src/cli/run-pagefind.js +154 -154
  18. package/src/cli/write-mcp-files.js +103 -103
  19. package/src/cli/write-redirects-file.js +158 -158
  20. package/src/components/ApiReferencePanel.astro +1792 -1792
  21. package/src/components/AppIcon.astro +51 -51
  22. package/src/components/Card.astro +193 -193
  23. package/src/components/CodeGroup.astro +63 -39
  24. package/src/components/CopyPageMenu.astro +374 -374
  25. package/src/components/Hint.astro +188 -188
  26. package/src/components/Icon.astro +72 -72
  27. package/src/components/Image.astro +165 -165
  28. package/src/components/Tile.astro +67 -67
  29. package/src/components/Video.astro +137 -137
  30. package/src/content.config.ts +219 -203
  31. package/src/layout/BaseLayout.astro +908 -908
  32. package/src/layout/components/AnalyticsScripts.astro +49 -49
  33. package/src/layout/components/Breadcrumbs.astro +98 -98
  34. package/src/layout/components/ConsentBanner.astro +119 -119
  35. package/src/layout/components/MobileMenu.astro +225 -225
  36. package/src/layout/components/NavTree.astro +422 -408
  37. package/src/layout/components/Sidebar.astro +232 -232
  38. package/src/layout/components/SiteFooter.astro +87 -87
  39. package/src/layout/components/TopBar.astro +386 -386
  40. package/src/layout/styles/base.css +332 -326
  41. package/src/layout/styles/mobile-menu.css +285 -285
  42. package/src/lib/agent-markdown.js +164 -164
  43. package/src/lib/asset-dimensions.js +89 -89
  44. package/src/lib/base-path.js +90 -90
  45. package/src/lib/cli-report.js +22 -22
  46. package/src/lib/code-line-numbers.js +13 -0
  47. package/src/lib/config-schema.js +12 -1
  48. package/src/lib/config-schema.ts +2523 -2509
  49. package/src/lib/config.ts +1331 -1316
  50. package/src/lib/consent.js +108 -108
  51. package/src/lib/content-check.js +4 -1
  52. package/src/lib/content-store-reload-integration.js +101 -101
  53. package/src/lib/drafts.js +186 -0
  54. package/src/lib/icon-data-dev.js +53 -53
  55. package/src/lib/image-size.js +152 -152
  56. package/src/lib/json-schema-descriptions.js +228 -228
  57. package/src/lib/link-check.js +553 -544
  58. package/src/lib/llms-index.ts +90 -90
  59. package/src/lib/mcp-dev-integration.js +65 -65
  60. package/src/lib/mcp-index.ts +102 -102
  61. package/src/lib/mintlify-convert.js +605 -605
  62. package/src/lib/moved-api-pages.js +49 -49
  63. package/src/lib/og-cards.js +33 -33
  64. package/src/lib/og-image.js +235 -235
  65. package/src/lib/openapi-dev-status.js +80 -80
  66. package/src/lib/openapi-reload-integration.js +193 -193
  67. package/src/lib/pages.js +346 -312
  68. package/src/lib/project-files-integration.js +116 -116
  69. package/src/lib/project-files.js +137 -137
  70. package/src/lib/rehype-base-path.js +62 -62
  71. package/src/lib/rehype-image-loading.js +71 -71
  72. package/src/lib/robots-txt.js +21 -21
  73. package/src/lib/search-scope.js +44 -44
  74. package/src/lib/selector-placement.js +50 -50
  75. package/src/lib/seo-tags.js +157 -155
  76. package/src/lib/shiki-code-block.js +7 -1
  77. package/src/lib/site-base.ts +27 -27
  78. package/src/lib/styles-asset-integration.js +291 -291
  79. package/src/lib/wdignore-cases.json +195 -195
  80. package/src/lib/wdignore.js +177 -177
  81. package/src/pages/404.astro +63 -63
  82. package/src/pages/[...slug].astro +1773 -1608
  83. package/src/pages/[...slug].md.ts +93 -93
  84. package/src/pages/llms-full.txt.ts +88 -88
  85. package/src/pages/og/[...slug].png.ts +63 -63
  86. package/src/scripts/mobile-menu.ts +80 -80
  87. package/src/scripts/search.ts +245 -245
  88. package/src/scripts/sidebar-scroll.ts +61 -61
  89. package/src/styles/global.css +40 -40
package/src/lib/config.ts CHANGED
@@ -1,1316 +1,1331 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { EXCLUDED_TOP_LEVEL_DIRS, navPageId } from './pages.js';
4
- import { isHidden } from './hidden-sections.js';
5
- import { itemPage, childLevel, equivalentItem, resolveLandings as resolveLandingsJs } from './item-pages.js';
6
- import matter from 'gray-matter';
7
- import { writedocsTempDir } from './writedocs-temp-dir.js';
8
- import { readableTextOn } from './color.js';
9
- import { oncePerBuild } from './build-memo.js';
10
- import { normalizeBasePath, siteUrlFor, siteOriginFor } from './base-path.js';
11
- import {
12
- formatValidationIssues,
13
- validateDocsConfig,
14
- type DocsConfig,
15
- type DropdownItem,
16
- type FontVariant,
17
- type LanguageItem,
18
- type NavChildren,
19
- type NavItem,
20
- type NavigationConfig,
21
- type ProductItem,
22
- type TabItem,
23
- type VersionItem,
24
- } from './config-schema.ts';
25
-
26
- // O schema do writedocs.json mora em ./config-schema.ts desde a extracao (E11):
27
- // aquele modulo importa so `zod`, sem nada de node:fs, pra que a plataforma
28
- // possa importa-lo por `@writedocs/generator/config-schema`. Este reexport
29
- // mantem a superficie deste arquivo exatamente como era - quem importa
30
- // `docsConfigSchema`, `DocsConfig`, `seoFieldsSchema`, `mergeSeo` etc. de
31
- // './config.js' continua importando do mesmo lugar, sem mudar uma linha.
32
- //
33
- // `.ts` e nao o `./config-schema.js` gerado, de proposito - e a unica coisa no
34
- // repositorio que ainda aponta pra fonte, e o bin/ e o `exports` apontam pro
35
- // `.js`. O motivo e que este reexport carrega 24 `export type`/`interface`
36
- // (DocsConfig, NavItem, Selector, GlobalDropdownView, ContextMenuConfig...) que
37
- // uma duzia de .astro consome como `import type { X } from '../lib/config'`, e
38
- // o esbuild apaga todos eles: o `.js` gerado exporta exatamente 5 simbolos de
39
- // runtime. Este repositorio nao tem tsconfig.json nem o typescript instalado,
40
- // entao (a) nada configura o mapeamento `.js` -> `.ts` que faria os tipos
41
- // voltarem e (b) nao existe typecheck que reclamasse - a troca so apagaria os
42
- // tipos em silencio. Aqui tudo passa pelo transform do Astro/Vite, que le `.ts`
43
- // nativamente, entao o `.js` nao resolve problema nenhum deste lado.
44
- //
45
- // O custo aceito e que o tarball leva as duas copias e um build do Astro pode
46
- // carregar as duas (o `.ts` por aqui, o `.js` por quem importa o subpath) - duas
47
- // instancias do schema, inofensivas porque nada compara identidade de schema.
48
- export * from './config-schema.ts';
49
-
50
- /** Normalizes writedocs.json's `domain` into a full origin with no trailing
51
- * slash (e.g. "docs.example.com" -> "https://docs.example.com"), or null
52
- * if the site hasn't set one. The single source of truth for "does this
53
- * site have a real deployed URL" - astro.config.mjs (sitemap
54
- * registration), BaseLayout.astro (canonical/OG/Twitter URLs), and
55
- * resolveAbsoluteUrl() below all call this rather than reading
56
- * config.domain directly, so the http(s):// normalization only happens
57
- * in one place.
58
- *
59
- * With a `basePath` it's the site's root, not just the origin -
60
- * "https://empresa.com/docs" - so every absolute URL built as siteUrl + a
61
- * site address ("/guides/a/") comes out under the base: canonical, og:url,
62
- * hreflang, structured data, llms.txt, mcp-index.json, the .md links.
63
- * resolveSiteOrigin() is the origin alone, for Astro's own `site`. */
64
- export function resolveSiteUrl(config: Pick<DocsConfig, 'domain' | 'basePath'>): string | null {
65
- return siteUrlFor(config.domain, resolveBasePath(config));
66
- }
67
-
68
- /** The `domain` as a full origin ("https://docs.example.com"), or null -
69
- * without the basePath. */
70
- export function resolveSiteOrigin(config: Pick<DocsConfig, 'domain'>): string | null {
71
- return siteOriginFor(config.domain);
72
- }
73
-
74
- /** writedocs.json's `basePath` as the base every address takes: "" with no
75
- * base, else "/docs" - see lib/base-path.js. */
76
- export function resolveBasePath(config: Pick<DocsConfig, 'basePath'>): string {
77
- return normalizeBasePath(config.basePath);
78
- }
79
-
80
- /** What goes in front of a site address to make the address a reader uses:
81
- * the siteUrl with a `domain`, else the base alone ("/docs", or "" at the
82
- * root) - for links that are absolute when they can be (llms.txt,
83
- * mcp-index.json). */
84
- export function resolveSiteRoot(config: Pick<DocsConfig, 'domain' | 'basePath'>): string {
85
- return resolveSiteUrl(config) ?? resolveBasePath(config);
86
- }
87
-
88
- /** Resolves a possibly-relative asset path (e.g. `seo.ogImage: "/card.png"`)
89
- * against the site's own domain into an absolute URL - social crawlers
90
- * (Facebook/Twitter/Slack unfurls) generally require an absolute
91
- * og:image/twitter:image URL, a same-origin relative path isn't reliably
92
- * respected. Returns the value unchanged if it's already absolute, or if
93
- * there's no siteUrl to resolve it against (a relative path is still
94
- * better than nothing in that case - most social crawlers do at least
95
- * attempt to fetch it relative to the page they scraped). */
96
- export function resolveAbsoluteUrl(siteUrl: string | null, value: string): string {
97
- if (/^https?:\/\//i.test(value)) return value;
98
- if (!siteUrl) return value;
99
- return `${siteUrl}${value.startsWith('/') ? '' : '/'}${value}`;
100
- }
101
-
102
- /** The resolved (never-undefined) Shiki theme names for light/dark code
103
- * blocks - shared by astro.config.mjs (sitewide MDX code-fence
104
- * highlighting) and ApiReferencePanel.astro (the API playground's own
105
- * separate <Code/> usages, which don't inherit markdown.shikiConfig at
106
- * all - see astro.config.mjs's own comment on that) so both read the
107
- * same writedocs.json field and fall back to the same defaults instead of
108
- * each hardcoding its own copy. */
109
- export function resolveCodeblockTheme(config: DocsConfig): { light: string; dark: string } {
110
- return {
111
- light: config.styles.codeblocks?.light ?? 'github-light',
112
- dark: config.styles.codeblocks?.dark ?? 'github-dark',
113
- };
114
- }
115
-
116
- // mdx is a real, bundled Shiki grammar (@shikijs/langs' mdx.mjs - it does
117
- // exist, this isn't a "Shiki doesn't know this language" situation), but in
118
- // practice it tokenizes ```mdx fences into one single run per line with no
119
- // internal token boundaries at all - every character, JSX tag or not,
120
- // lands in the exact same TextMate scope and renders in the theme's plain
121
- // foreground color. Confirmed directly against real built output: every
122
- // span in a ```mdx block's compiled HTML carries the identical inline
123
- // color, none of the tag/attribute/string distinction a JS or JSX fence
124
- // gets. Aliasing to jsx - a close structural match for the JSX-heavy
125
- // snippets these fences are actually used for in this codebase's own docs
126
- // (`<Callout>`, `<Card>`, etc.) - actually highlights the tags/attributes,
127
- // at the cost of not distinctly coloring the markdown-prose portions
128
- // interleaved between them (jsx's grammar doesn't know about those) - a
129
- // worthwhile trade given the alternative is no color at all. See
130
- // astro.config.mjs's own shikiConfig.langAlias for where this actually
131
- // gets used. */
132
- const DEFAULT_CODEBLOCK_LANG_ALIAS: Record<string, string> = { mdx: 'jsx' };
133
-
134
- /** The resolved fence-language alias map - the built-in mdx -> jsx default
135
- * above, merged with (not replaced by) whatever a site adds under its own
136
- * writedocs.json styles.codeblocks.langAlias, so a site can extend this list
137
- * without having to redeclare the built-in entry to keep it. Same
138
- * "shared resolver, not each consumer re-deriving its own defaults"
139
- * pattern resolveCodeblockTheme() right above already establishes -
140
- * though today only astro.config.mjs actually consumes this one, unlike
141
- * that one, since ApiReferencePanel.astro's own <Code/> usages never
142
- * render a `mdx`-tagged snippet (API operation samples are curl/js/
143
- * python/etc., not MDX markup) to begin with. */
144
- export function resolveCodeblockLangAlias(config: DocsConfig): Record<string, string> {
145
- return { ...DEFAULT_CODEBLOCK_LANG_ALIAS, ...config.styles.codeblocks?.langAlias };
146
- }
147
-
148
- const DEFAULT_FONT_FAMILY = 'Inter';
149
-
150
- export interface ResolvedFonts {
151
- base: FontVariant;
152
- heading: FontVariant | null;
153
- body: FontVariant | null;
154
- }
155
-
156
- /** Resolves writedocs.json's `styles.fonts` into the three font declarations
157
- * BaseLayout.astro actually needs to render: `base` (the site-wide
158
- * default - every element gets this unless `heading`/`body` narrows it
159
- * further), and `heading`/`body`, each `null` when not independently
160
- * configured (letting BaseLayout fall back to `base` for whichever side
161
- * wasn't overridden, rather than this function silently copying `base`
162
- * into both and losing the distinction between "explicitly set to the
163
- * same font" and "just inheriting the default"). The one hardcoded
164
- * default in this whole feature lives right here: no `styles.fonts` at
165
- * all resolves to plain Inter, loaded for real (a Google Fonts `<link>`,
166
- * not just a name in a fallback stack that only renders correctly for a
167
- * reader who happens to already have Inter installed - see base.css's
168
- * old `font-family` rule, which was exactly that, before this feature
169
- * existed). */
170
- export function resolveFonts(config: DocsConfig): ResolvedFonts {
171
- const fonts = config.styles.fonts;
172
- const base: FontVariant = fonts
173
- ? { family: fonts.family, weight: fonts.weight, source: fonts.source, format: fonts.format }
174
- : { family: DEFAULT_FONT_FAMILY };
175
- return { base, heading: fonts?.heading ?? null, body: fonts?.body ?? null };
176
- }
177
-
178
- /** The Google Fonts CSS2 API URL for every font in `fonts` that isn't a
179
- * `source`-based (local/externally-hosted) font - `null` if there's
180
- * nothing to load this way at all (every configured font has its own
181
- * `source`). One request covers every family needed (`&family=` repeated
182
- * per unique family+weight pair, deduped so the same pair - e.g. `base`
183
- * and `body` both left at the site default - isn't requested twice)
184
- * rather than a separate `<link>` per font. `display=swap` avoids an
185
- * invisible-text flash while the font file loads (renders in the
186
- * fallback stack immediately, swaps once the real font is ready) -
187
- * Google's own recommended default for exactly this use case. */
188
- export function googleFontsHref(fonts: ResolvedFonts): string | null {
189
- const entries = [fonts.base, fonts.heading, fonts.body].filter(
190
- (f): f is FontVariant => f !== null && !f.source
191
- );
192
- if (entries.length === 0) return null;
193
- const seen = new Set<string>();
194
- const params: string[] = [];
195
- for (const f of entries) {
196
- const key = `${f.family}|${f.weight ?? ''}`;
197
- if (seen.has(key)) continue;
198
- seen.add(key);
199
- const familyParam = f.family.trim().replace(/\s+/g, '+');
200
- params.push(f.weight ? `family=${familyParam}:wght@${f.weight}` : `family=${familyParam}`);
201
- }
202
- return `https://fonts.googleapis.com/css2?${params.join('&')}&display=swap`;
203
- }
204
-
205
- /** A `@font-face` rule for one `source`-based font (local project path or
206
- * externally-hosted URL), or `''` for a Google Font (no `source` - see
207
- * googleFontsHref() above, the other half of font loading). `weight`
208
- * becomes the rule's `font-weight` *descriptor* here - it tells the
209
- * browser which weight this specific file represents, so a `font-weight`
210
- * CSS value requested elsewhere (BaseLayout.astro's own
211
- * `wdFontWeightHeading`/`wdFontWeightBody`, see its comment) picks the
212
- * real matching file instead of synthetically ("faux") bolding/
213
- * thinning a mismatched one. This function only ever produces the
214
- * `@font-face` rule itself - actually applying `font-weight` to any
215
- * element (h1-h6, body) is BaseLayout's job, not this one's. */
216
- export function fontFaceRule(font: FontVariant | null): string {
217
- if (!font || !font.source) return '';
218
- const weightDecl = font.weight !== undefined ? ` font-weight: ${font.weight};` : '';
219
- return `@font-face { font-family: '${font.family}'; src: url('${font.source}') format('${font.format ?? 'woff2'}'); font-display: swap;${weightDecl} }`;
220
- }
221
-
222
- /** Splits one side of `styles.navbar` (the string-or-object union
223
- * navbarColorValueSchema allows) into its two parts, filling in the
224
- * fallback background when the field is unset at all. `accent` stays
225
- * `undefined` - not defaulted here - for both the bare-string case and
226
- * the object case where a site set `background` without `accent`;
227
- * BaseLayout.astro is what turns that `undefined` into "fall back to
228
- * --wd-primary" for the accent CSS var. There's no `foreground` here at
229
- * all to resolve - the navbar's text/icon color is never read from
230
- * writedocs.json, see `navbar`'s own schema comment (stylesSchema) for why. */
231
- export function resolveNavbarColor(
232
- value: string | { background: string; accent?: string } | undefined,
233
- fallbackBackground: string
234
- ): { background: string; accent: string | undefined } {
235
- if (!value) return { background: fallbackBackground, accent: undefined };
236
- if (typeof value === 'string') return { background: value, accent: undefined };
237
- return { background: value.background, accent: value.accent };
238
- }
239
-
240
- /** Picks black or white text for `hexColor` - white unless white falls
241
- * below 3:1 on it (readableTextOn() in lib/color.js), the same rule and
242
- * WCAG math `writedocs a11y` checks with, so the check measures what the
243
- * site renders. (This used a BT.601 brightness threshold.) Also
244
- * gives `--wd-on-primary`, the text on step numbers, the info banner and
245
- * the API playground's buttons. Used two ways in BaseLayout.astro: for `--wd-navbar-accent-text`
246
- * (the active tab's own fill used to always be `var(--wd-primary)` with
247
- * hardcoded `color: #fff`, which only actually read fine because every
248
- * default/example primary color so far has been dark/saturated enough
249
- * for white text; once a site's navbar accent can be *any* color -
250
- * `styles.navbar.light.accent`, falling back to `styles.colors.primary`
251
- * when unset, see resolveNavbarColor() above - that assumption can't
252
- * hold unconditionally), and for `--wd-navbar-foreground` itself once
253
- * `styles.navbar` is configured at all (the navbar's plain text/icon
254
- * color - see `navbar`'s own schema comment for why that's always
255
- * computed, never a writedocs.json value). Malformed input (not a
256
- * `#rgb`/`#rrggbb` hex) falls back to white rather than throwing - same "don't
257
- * fail a build over a cosmetic color value" posture every other color
258
- * field here takes (none of them validate hex syntax either). */
259
- export function contrastTextColor(hexColor: string): '#000000' | '#ffffff' {
260
- return readableTextOn(hexColor) as '#000000' | '#ffffff';
261
- }
262
-
263
- /** Whether an href points off-site - has an explicit scheme (`https:`,
264
- * `mailto:`, `tel:`, ...) or is protocol-relative (`//...`) - versus a
265
- * same-site path, which this codebase always produces as a single
266
- * leading slash (hrefForSlug() in [...slug].astro). Used everywhere a
267
- * nav link is rendered to decide whether it should open in a new tab;
268
- * deliberately a plain string check rather than a schema-level flag,
269
- * so it applies uniformly to every href source (topbar.links, a
270
- * switcher/tab pill pointing at a bare `href` container, a global
271
- * dropdown's own link, a sidebar link leaf) without threading an
272
- * `external` field through every one of those call sites. */
273
- export function isExternalHref(href: string): boolean {
274
- return /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith('//');
275
- }
276
-
277
- // ---------------------------------------------------------------------
278
- // Icons - writedocs.json's `icon` fields (TabItem, DropdownItem, ProductItem,
279
- // Card) are plain strings with no schema-level distinction between "an
280
- // emoji, paste it verbatim" and "an icon-set name, look it up". Resolved
281
- // here rather than validated in the schema, since both are valid uses of
282
- // the same string field and the right rendering only becomes obvious once
283
- // you look at the value's shape.
284
- // ---------------------------------------------------------------------
285
-
286
- export type IconResolution =
287
- | { kind: 'iconify'; name: string } // ready for astro-icon/components' <Icon name=... />
288
- | { kind: 'image'; src: string } // an image URL or site path, rendered as <img>
289
- | { kind: 'text'; value: string }; // literal text/emoji, rendered as-is
290
-
291
- // The implementation lives in lib/icons.js - plain JavaScript, because
292
- // `writedocs validate` loads it with plain Node (see that file's comment).
293
- export { resolveIcon, iconExists, iconSvg } from './icons.js';
294
-
295
- // ---------------------------------------------------------------------
296
- // OpenAPI navigation expansion - turns a group's `openapi: { src, path }`
297
- // shorthand into a concrete `{ group, pages }` (one sub-group per tag),
298
- // using the per-spec manifest generate-api-pages.js writes to
299
- // writedocsTempDir()'s openapi/<path>/manifest.json before Astro starts (both
300
- // `writedocs dev` and `writedocs build` run it first - see
301
- // src/cli/dev.js, src/cli/build.js). Applied once, here in
302
- // loadDocsConfig(), so every other function in this file
303
- // (resolveSections, flattenNav, buildNavTree, ...) only ever sees plain
304
- // page-slug strings and ordinary `{ group, pages }` nodes, and never
305
- // needs to know the `openapi` group shorthand exists. A writedocs.json can
306
- // have any number of these groups, each pointing at its own spec and
307
- // mounted under its own `path` - generate-api-pages.js namespaces each
308
- // spec's manifest/operations under that same `path`, so there's no
309
- // cross-spec collision as long as every group uses a distinct `path`.
310
- // ---------------------------------------------------------------------
311
-
312
- export interface OpenApiManifestEntry {
313
- slug: string;
314
- method: string;
315
- path: string;
316
- tags: string[];
317
- title: string;
318
- generated: boolean;
319
- }
320
-
321
- /** `specPath` is the owning group's own `openapi.path` (e.g. "/api") -
322
- * generate-api-pages.js writes each spec's manifest under a directory
323
- * named after that same value, so this only ever needs to know which
324
- * group is asking, not anything about the spec's contents itself. */
325
- function loadOpenApiManifest(contentDir: string, specPath: string): OpenApiManifestEntry[] | null {
326
- const normalized = specPath.replace(/^\/+|\/+$/g, '');
327
- const manifestPath = path.join(writedocsTempDir(contentDir), 'openapi', normalized, 'manifest.json');
328
- if (!fs.existsSync(manifestPath)) return null;
329
- try {
330
- return JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
331
- } catch {
332
- return null; // stale/partial write from an interrupted previous run - treat as absent
333
- }
334
- }
335
-
336
- /** Expands one group's `openapi: { src, path }` into the `pages` array
337
- * it stands in for - one sub-group per tag (in first-seen order),
338
- * untagged operations collected into a trailing "Other" group. Returns
339
- * an empty array (an empty, harmless group) rather than throwing if the
340
- * manifest is missing - generate-api-pages.js always runs before this
341
- * does (see src/cli/dev.js/build.js), so a missing manifest here means
342
- * generation hasn't happened yet rather than a user error worth
343
- * crashing the dev server over. */
344
- function expandOpenApiGroupPages(openapiRef: { src: string; path: string }, contentDir: string): NavItem[] {
345
- const manifest = loadOpenApiManifest(contentDir, openapiRef.path);
346
- if (!manifest) return [];
347
-
348
- const seenTags: string[] = [];
349
- const byTag = new Map<string, string[]>();
350
- const untagged: string[] = [];
351
- for (const op of manifest) {
352
- const tag = op.tags[0];
353
- if (!tag) {
354
- untagged.push(op.slug);
355
- continue;
356
- }
357
- if (!byTag.has(tag)) {
358
- byTag.set(tag, []);
359
- seenTags.push(tag);
360
- }
361
- byTag.get(tag)!.push(op.slug);
362
- }
363
- const groups: NavItem[] = seenTags.map((tag) => ({ group: tag, pages: byTag.get(tag)! }));
364
- return untagged.length > 0 ? [...groups, { group: 'Other', pages: untagged }] : groups;
365
- }
366
-
367
- function expandOpenApiInPages(pages: NavItem[], contentDir: string): NavItem[] {
368
- return pages.map((item): NavItem => {
369
- if (typeof item === 'string') return item;
370
- if ('href' in item) return item;
371
- if ('openapi' in item) {
372
- // A group using the { group, openapi: { src, path } } shorthand -
373
- // replace it with a real { group, pages } node built from that
374
- // spec's own manifest, so nothing downstream needs to know the
375
- // shorthand ever existed.
376
- return { group: item.group, pages: expandOpenApiGroupPages(item.openapi, contentDir) };
377
- }
378
- // An ordinary { group, page?, pages } - recurse into its own pages,
379
- // since an openapi-group can be nested inside a hand-authored group
380
- // too (e.g. wrapping it to add hand-written pages alongside the
381
- // auto-generated ones).
382
- return { ...item, pages: expandOpenApiInPages(item.pages, contentDir) };
383
- });
384
- }
385
-
386
- /** Mirrors walkSections()'s traversal (tabs/versions/languages/
387
- * dropdowns/products, each bottoming out at `pages`), but rewrites
388
- * rather than collects - every `pages` array anywhere in the tree gets
389
- * run through expandOpenApiInPages(). */
390
- function expandOpenApiInContainer(node: NavChildren, contentDir: string): NavChildren {
391
- if ('pages' in node) return { pages: expandOpenApiInPages(node.pages, contentDir) };
392
- if ('href' in node) return node;
393
- if ('tabs' in node) {
394
- return { tabs: node.tabs.map((t) => ({ ...t, ...expandOpenApiInContainer(t, contentDir) })) };
395
- }
396
- if ('versions' in node) {
397
- return { versions: node.versions.map((v) => ({ ...v, ...expandOpenApiInContainer(v, contentDir) })) };
398
- }
399
- if ('languages' in node) {
400
- return { languages: node.languages.map((l) => ({ ...l, ...expandOpenApiInContainer(l, contentDir) })) };
401
- }
402
- if ('dropdowns' in node) {
403
- return { dropdowns: node.dropdowns.map((d) => ({ ...d, ...expandOpenApiInContainer(d, contentDir) })) };
404
- }
405
- if ('products' in node) {
406
- return { products: node.products.map((p) => ({ ...p, ...expandOpenApiInContainer(p, contentDir) })) };
407
- }
408
- return node;
409
- }
410
-
411
- function expandOpenApiInNavigation(navigation: NavigationConfig, contentDir: string): NavigationConfig {
412
- if (Array.isArray(navigation)) return expandOpenApiInPages(navigation, contentDir);
413
- const expanded = { ...navigation, ...expandOpenApiInContainer(navigation as Container, contentDir) };
414
- if (navigation.global?.dropdowns) {
415
- expanded.global = {
416
- dropdowns: navigation.global.dropdowns.map(
417
- (d) => ({ ...d, ...expandOpenApiInContainer(d, contentDir) }) as DropdownItem
418
- ),
419
- };
420
- }
421
- return expanded as NavigationConfig;
422
- }
423
-
424
- export function loadDocsConfig(contentDir: string): DocsConfig {
425
- // Read and validated once per build, not once per page (lib/build-memo.js):
426
- // every caller there gets the same object, so none of them may change it.
427
- // In `writedocs dev` it's read again on every call, and an edit shows up.
428
- return oncePerBuild(`config:${contentDir}`, () => readDocsConfig(contentDir));
429
- }
430
-
431
- function readDocsConfig(contentDir: string): DocsConfig {
432
- const configPath = path.join(contentDir, 'writedocs.json');
433
- if (!fs.existsSync(configPath)) {
434
- throw new Error(
435
- `[writedocs] writedocs.json not found at ${configPath}. Run "writedocs init" to scaffold one.`
436
- );
437
- }
438
- // A validacao em si (JSON.parse incluso) vive em validateDocsConfig
439
- // (./config-schema.ts), o mesmo ponto de entrada que o `writedocs validate` e
440
- // a plataforma usam - e o que garante que os tres reportem exatamente os
441
- // mesmos problemas, com as mesmas palavras.
442
- //
443
- // As duas formas de falhar continuam saindo daqui EXATAMENTE como saiam antes
444
- // desta extracao:
445
- // - JSON quebrado: relanca o proprio SyntaxError do JSON.parse (mesmo tipo,
446
- // mesma mensagem que o runtime produz);
447
- // - schema invalido: o mesmo Error, com o mesmo texto, montado a partir do
448
- // mesmo formatador que a CLI usa.
449
- const result = validateDocsConfig(fs.readFileSync(configPath, 'utf-8'));
450
- if (!result.ok) {
451
- if (result.parseError) throw result.parseError;
452
- throw new Error(
453
- `[writedocs] writedocs.json failed validation:\n${formatValidationIssues(result.issues, { total: result.issuesTotal, truncated: result.issuesTruncated })}`
454
- );
455
- }
456
- // A no-op pass over ordinary navigation trees (no openapi groups) -
457
- // always run, rather than gated behind a global manifest check, since
458
- // there's no longer a single global spec to check for.
459
- result.data.navigation = withPageIds(expandOpenApiInNavigation(result.data.navigation, contentDir));
460
- return result.data;
461
- }
462
-
463
- /** The navigation with every page entry as its page id - "guides/index"
464
- * becomes "guides" (navPageId() in lib/pages.js), so everything that
465
- * matches entries against pages (routes, the sidebar, prev/next, llms.txt,
466
- * the MCP index) finds a folder's index.mdx however writedocs.json names it. */
467
- function withPageIds<T>(node: T): T {
468
- if (Array.isArray(node)) return node.map((item) => (typeof item === 'string' ? navPageId(item) : withPageIds(item))) as T;
469
- if (node && typeof node === 'object') {
470
- return Object.fromEntries(
471
- Object.entries(node).map(([key, value]) => [
472
- key,
473
- key === 'page' && typeof value === 'string' ? navPageId(value) : key === 'href' || key === 'openapi' ? value : withPageIds(value),
474
- ])
475
- ) as T;
476
- }
477
- return node;
478
- }
479
-
480
- // --- Locating a page by file id, independent of its effective slug -----
481
- //
482
- // writedocs.json's `pages` arrays, and every helper above/below that walks
483
- // them (flattenNav, firstSlugOf, containerContainsSlug, buildNavTree, ...),
484
- // always identify a page by its file id - its path relative to the
485
- // content directory (project root), extension stripped, with a trailing
486
- // `/index` segment dropped (matching Astro's own default id computation -
487
- // see the `/index` note below) - regardless of how that page ends up
488
- // being served. docs/ is not special: a file at `docs/guides/x.mdx` has
489
- // file id `docs/guides/x`, the exact same rule applied to a file
490
- // anywhere else in the project.
491
- //
492
- // A page's actual URL is a separate question, and Astro's own glob()
493
- // content loader already has a first-class answer for it: if a page's
494
- // frontmatter sets `slug`, `entry.id` (and therefore the route Astro
495
- // builds for it) becomes that value verbatim instead of the file-path
496
- // default - see astro/dist/content/loaders/glob.js's generateIdDefault:
497
- // `if (data.slug) return data.slug`. content.config.ts's `slug` schema
498
- // field is deliberately the same field Astro already recognizes, so
499
- // nothing here needs to reimplement the override or track it separately -
500
- // it only needs a way to find a page BY file id (to resolve writedocs.json's
501
- // references) even once `entry.id` no longer equals it.
502
- //
503
- // --- Page discovery -------------------------------------------------
504
- //
505
- // Any .md/.mdx file anywhere under the content directory becomes a page
506
- // candidate the moment it has *any* frontmatter block at all - docs/ has
507
- // no special status here, it's just a folder like any other (a
508
- // conventional, recommended place to put most pages, not a requirement).
509
- // content.config.ts's `pages` collection is the same docsSchema applied
510
- // to exactly this file set. A file with zero frontmatter (no `---` block
511
- // whatsoever) is never a page candidate - a snippet (see
512
- // docs/dev/docs/snippets.mdx) typically has none, which is what lets it
513
- // live anywhere without tripping schema validation. A file that *does*
514
- // open a frontmatter block but is missing a required field (`title`)
515
- // still fails validation exactly as before - only "no frontmatter at
516
- // all" is new; a genuine mistake (frontmatter present, title forgotten)
517
- // stays a loud build error rather than being silently treated as
518
- // non-page content.
519
- //
520
- // A handful of directories are never scanned regardless of what's in
521
- // them - build output, dependencies, and writedocs' own working
522
- // directories, none of which a site author would ever intend as page
523
- // content. Only excluded at the content directory's own top level (a
524
- // hand-authored `guides/dist-notes.mdx` isn't mistaken for the build
525
- // output directory `dist/` just because a folder two levels down happens
526
- // to also be named `dist`).
527
- // EXCLUDED_TOP_LEVEL_DIRS and findAllPages() live in lib/pages.js - plain
528
- // JavaScript, so `writedocs validate` can find a site's pages with plain Node.
529
- export { findAllPages } from './pages.js';
530
-
531
- // findRootAssets() lives in lib/pages.js - plain JavaScript, so it can be
532
- // tested with plain Node, next to findAllPages() whose exclusions it shares.
533
- export { findRootAssets } from './pages.js';
534
-
535
- /** The root-relative URL paths (leading `/`, e.g. `/images/hero.svg`)
536
- * referenced by the writedocs.json/styles fields that point at a static asset
537
- * *by URL* rather than embedding it inline: `styles.favicon`,
538
- * `styles.logo` (both the plain-string and `{light, dark}` object forms),
539
- * `styles.background.images.{light,dark}`, and `seo.ogImage`. External
540
- * URLs (anything not starting with `/` - `https://...`, mainly) are
541
- * filtered out, since those need no local file resolution at all.
542
- * Deduped, since e.g. `logo.light` and `background.images.light`
543
- * coincidentally pointing at the same file shouldn't resolve/copy it
544
- * twice.
545
- *
546
- * Used by `stylesAssetFallback()` (`styles-asset-integration.js`,
547
- * imported from `astro.config.mjs`) to let every one of these resolve
548
- * from *anywhere* in the project, not just `public/` - previously,
549
- * `public/` was the one place `styles.background.images` (etc.) had to
550
- * live, since Astro's own `publicDir` copy is the only thing that ever
551
- * served them; everywhere else in this codebase's own "drop a file
552
- * anywhere, it's found" convention (`findRootAssets()` in lib/pages.js,
553
- * `findAllPages()` for content) already worked project-wide. See that
554
- * integration's own comment for the actual resolution mechanism (a dev-time
555
- * middleware plus a post-build copy step, not a duplicated `publicDir`)
556
- * and why a straight copy-into-`public/`-on-disk approach was rejected.
557
- *
558
- * Logo light/dark resolution here deliberately mirrors BaseLayout.astro's
559
- * own `logoLight`/`logoDark` derivation exactly (a plain-string `logo`
560
- * counts as both light and dark) - two independent implementations of
561
- * that same union-unwrapping would only be one accidental edit away from
562
- * disagreeing with each other. `footer.logo` (footerSchema) gets the
563
- * same treatment, independently of `styles.logo` - both are collected
564
- * unconditionally here (not just whichever one BaseLayout.astro would
565
- * actually end up using for a given page), since this function has no
566
- * page context to know which page modes render a footer at all; an
567
- * unreferenced path collected here that never actually renders anywhere
568
- * is harmless (nothing copies/resolves a file that's never requested),
569
- * but a real footer.logo file silently 404ing because this function
570
- * didn't know to resolve it is exactly the bug this comment is warning
571
- * future edits away from repeating.
572
- *
573
- * Per-page frontmatter `seo.ogImage` overrides are deliberately out of
574
- * scope - those aren't visible from a `DocsConfig` alone (they live in
575
- * each page's own frontmatter, merged in per-request by [...slug].astro/
576
- * BaseLayout.astro), and resolving every page's own override would need
577
- * a full content scan this function has no reason to also become. A
578
- * page overriding `seo.ogImage` to something outside `public/` still
579
- * needs to put it there for now. */
580
- export function collectConfiguredAssetPaths(config: DocsConfig): string[] {
581
- const logo = config.styles.logo;
582
- const logoLight = typeof logo === 'string' ? logo : logo?.light;
583
- const logoDark = typeof logo === 'string' ? logo : logo?.dark;
584
- const footerLogo = config.footer.logo;
585
- const footerLogoLight = typeof footerLogo === 'string' ? footerLogo : footerLogo?.light;
586
- const footerLogoDark = typeof footerLogo === 'string' ? footerLogo : footerLogo?.dark;
587
- const fonts = config.styles.fonts;
588
- const raw: (string | undefined)[] = [
589
- config.styles.favicon,
590
- logoLight,
591
- logoDark,
592
- footerLogoLight,
593
- footerLogoDark,
594
- config.styles.background?.images?.light,
595
- config.styles.background?.images?.dark,
596
- config.seo?.ogImage,
597
- // A `styles.fonts` `source` is only ever handled here when it's a
598
- // project-relative path (the `p.startsWith('/')` filter below already
599
- // excludes both Google Font names, which never start with "/", and a
600
- // full https:// external font URL, which the browser fetches directly
601
- // - neither needs resolving/copying through this pipeline at all).
602
- fonts?.source,
603
- fonts?.heading?.source,
604
- fonts?.body?.source,
605
- ];
606
- const paths = raw.filter((p): p is string => Boolean(p) && p.startsWith('/'));
607
- return Array.from(new Set(paths));
608
- }
609
-
610
- export interface DocsEntryLike {
611
- id: string;
612
- filePath?: string;
613
- }
614
-
615
- /** Recovers a content entry's writedocs.json-facing file id (its path
616
- * relative to the content directory, extension stripped, trailing
617
- * `/index` dropped), independent of any frontmatter `slug` override -
618
- * `entry.filePath` is always root-relative and POSIX-separated (how
619
- * Astro's content layer records it, relative to whatever `--root` Astro
620
- * itself was invoked with - see run-astro.js), so both it and the
621
- * content directory are resolved to absolute paths before comparing,
622
- * rather than string-matching a prefix that could be relative,
623
- * absolute, or platform-separated inconsistently.
624
- *
625
- * The trailing-`/index`-drop mirrors Astro's own default id computation
626
- * exactly (`getContentEntryIdAndSlug()` in astro/dist/content/
627
- * utils.js: segments are joined then `.replace(/\/index$/, '')`) -
628
- * without it, a nested index file like `docs/guides/index.mdx` (Astro's
629
- * own default id: "docs/guides") would recover the wrong file id here
630
- * ("docs/guides/index"), and a writedocs.json reference written to match the
631
- * page's real URL would fail to resolve. A single-segment `index.mdx`
632
- * at the content root is unaffected either way - the regex requires a
633
- * preceding `/`, which a bare "index" doesn't have (matching Astro's
634
- * own behavior: a root-level index.mdx keeps file id "index", not "").
635
- *
636
- * Full per-segment slugification (github-slugger, applied by Astro to
637
- * every path segment) is deliberately *not* replicated here - every
638
- * filename in this codebase's own fixtures and every filename this
639
- * function needs to have handled correctly is already slug-safe
640
- * (lowercase, hyphenated, no spaces/unicode), so slugification is
641
- * always a no-op in practice; only the `/index`-stripping behavior is
642
- * reproduced, since that's the one part of Astro's algorithm this
643
- * change newly exercises (a file that used to be a collection's own
644
- * base-root index, exempt from stripping, and is now nested one level
645
- * deeper).
646
- *
647
- * Entries from the `generatedDocs` collection (auto-generated OpenAPI
648
- * stub pages - see content.config.ts / generate-api-pages.js) live
649
- * under writedocsTempDir()'s generated-docs/ directory - an OS temp
650
- * directory location entirely outside contentDir, not a subdirectory
651
- * of it - so `relativeToContentDir` for one of these always starts with
652
- * `..` (walking back out of contentDir to reach it), and the check
653
- * right below falls back to `entry.id` instead of computing a
654
- * nonsensical id relative to a directory the file was never actually
655
- * under. Those entries always set their own `slug` frontmatter
656
- * explicitly, so there's no independent "file path" identity worth
657
- * recovering for them the way there is for a hand-written page that
658
- * might move around - `entry.id` (Astro's already-resolved slug)
659
- * already IS the exact value generate-api-pages.js's own manifest
660
- * references them by. */
661
- export function fileIdForEntry(
662
- contentDir: string,
663
- packageRoot: string,
664
- entry: DocsEntryLike
665
- ): string {
666
- if (!entry.filePath) return entry.id;
667
- const absoluteContentDir = path.resolve(contentDir);
668
- const absoluteFilePath = path.resolve(packageRoot, entry.filePath);
669
- const relativeToContentDir = path.relative(absoluteContentDir, absoluteFilePath);
670
- // Outside contentDir: `..`-prefixed, or - on Windows, when the file is on
671
- // another drive (temp on C:, project on D:) - an absolute path, since
672
- // path.relative() can't bridge drives.
673
- if (relativeToContentDir.startsWith('..') || path.isAbsolute(relativeToContentDir)) return entry.id;
674
- const posixRelative = relativeToContentDir.split(path.sep).join('/');
675
- if (EXCLUDED_TOP_LEVEL_DIRS.has(posixRelative.split('/')[0])) return entry.id;
676
- return posixRelative.replace(/\.mdx?$/i, '').replace(/\/index$/, '');
677
- }
678
-
679
- /** Normalizes a raw `entry.id` into the bare, slash-free form every
680
- * route/href in this codebase assumes. Once a page sets a frontmatter
681
- * `slug`, `entry.id` becomes that value completely verbatim - Astro's
682
- * glob loader applies no normalization of its own (see
683
- * generateIdDefault in astro/dist/content/loaders/glob.js) - so
684
- * `slug: /` or `slug: /guides/new-name` (both natural things to write,
685
- * mirroring how every href elsewhere in writedocs.json already has a
686
- * leading slash) would otherwise produce broken multi-slash hrefs
687
- * wherever hrefForSlug wraps the value in its own `/${slug}/`, and a
688
- * bare "/" would additionally fail to be recognized as claiming root,
689
- * colliding with the synthetic root-redirect route. */
690
- export function normalizeEntryId(id: string): string {
691
- const trimmed = id.replace(/^\/+/, '').replace(/\/+$/, '');
692
- return trimmed === '' ? 'index' : trimmed;
693
- }
694
-
695
- export interface FlatNavEntry {
696
- slug: string;
697
- group: string | null;
698
- }
699
-
700
- export function flattenNav(navigation: NavItem[], group: string | null = null): FlatNavEntry[] {
701
- return navigation.flatMap((item): FlatNavEntry[] => {
702
- if (typeof item === 'string') {
703
- return [{ slug: item, group }];
704
- }
705
- if ('href' in item) return []; // external link leaf, not a content page - no route/prev-next entry
706
- // loadDocsConfig() always expands `{ group, openapi }` shorthand into
707
- // a real `{ group, pages }` before anything reaches here (see
708
- // expandOpenApiInNavigation() above) - this is just a defensive
709
- // no-op for the shouldn't-happen case of an unexpanded node.
710
- if ('openapi' in item) return [];
711
- const ownPage: FlatNavEntry[] = item.page ? [{ slug: item.page, group: item.group }] : [];
712
- return [...ownPage, ...flattenNav(item.pages, item.group)];
713
- });
714
- }
715
-
716
- // --- Sections -------------------------------------------------------
717
- //
718
- // A Section is the atomic unit that owns one page tree and therefore one
719
- // sidebar - every real content page belongs to exactly one Section,
720
- // whichever `pages` leaf it's listed under, however deep in the
721
- // tabs/versions/languages/dropdowns/products tree that leaf lives.
722
- //
723
- // A Section's `path` records the full chain of containers from the
724
- // navigation root down to it, one PathSegment per level. This is
725
- // everything the topbar needs to render the right selector controls
726
- // (tabs bar, version dropdown, ...) and highlight the right option in
727
- // each - without the router or layout needing to know how deep or in
728
- // what order the site author nested things.
729
-
730
- export type PathSegment =
731
- | { kind: 'tab'; items: TabItem[]; index: number }
732
- | { kind: 'version'; items: VersionItem[]; index: number }
733
- | { kind: 'language'; items: LanguageItem[]; index: number }
734
- | { kind: 'dropdown'; items: DropdownItem[]; index: number }
735
- | { kind: 'product'; items: ProductItem[]; index: number };
736
-
737
- export interface Section {
738
- pages: NavItem[];
739
- path: PathSegment[];
740
- }
741
-
742
- type Container = NavChildren;
743
- type NamedContainer = TabItem | VersionItem | LanguageItem | DropdownItem | ProductItem;
744
-
745
- function walkSections(node: Container, path: PathSegment[], out: Section[]): void {
746
- if ('pages' in node) {
747
- out.push({ pages: node.pages, path });
748
- return;
749
- }
750
- if ('href' in node) return; // external link, not a Section
751
- if ('tabs' in node) {
752
- node.tabs.forEach((item, index) =>
753
- walkSections(item, [...path, { kind: 'tab', items: node.tabs, index }], out)
754
- );
755
- return;
756
- }
757
- if ('versions' in node) {
758
- node.versions.forEach((item, index) =>
759
- walkSections(item, [...path, { kind: 'version', items: node.versions, index }], out)
760
- );
761
- return;
762
- }
763
- if ('languages' in node) {
764
- node.languages.forEach((item, index) =>
765
- walkSections(item, [...path, { kind: 'language', items: node.languages, index }], out)
766
- );
767
- return;
768
- }
769
- if ('dropdowns' in node) {
770
- node.dropdowns.forEach((item, index) =>
771
- walkSections(item, [...path, { kind: 'dropdown', items: node.dropdowns, index }], out)
772
- );
773
- return;
774
- }
775
- if ('products' in node) {
776
- node.products.forEach((item, index) =>
777
- walkSections(item, [...path, { kind: 'product', items: node.products, index }], out)
778
- );
779
- return;
780
- }
781
- }
782
-
783
- export function resolveSections(navigation: NavigationConfig): Section[] {
784
- if (Array.isArray(navigation)) return [{ pages: navigation, path: [] }];
785
- const sections: Section[] = [];
786
- walkSections(navigation as Container, [], sections);
787
- // global.dropdowns sits outside the primary pattern, but its pages
788
- // still need routes generated for them - walk each entry too, with an
789
- // empty path (they don't participate in the tabs/version/etc.
790
- // selector chain, only in the always-visible globalDropdowns list).
791
- for (const dropdown of navigation.global?.dropdowns ?? []) {
792
- walkSections(dropdown, [], sections);
793
- }
794
- return sections;
795
- }
796
-
797
- // --- An item's own page ------------------------------------------------
798
- //
799
- // A tab, version, language, dropdown or product can have a `page`: choosing
800
- // the item opens it (firstSlugOf() above). How such a page is shown when no
801
- // sidebar lists it - inside its item - is lib/item-pages.js; the route is
802
- // landingRoutes in [...slug].astro.
803
-
804
- export interface Landing {
805
- /** The page's id. */
806
- slug: string;
807
- /** The levels down to the item, the item last. */
808
- path: PathSegment[];
809
- /** The item's own sidebar - empty when it holds tabs, products, ... */
810
- pages: NavItem[];
811
- item: NamedContainer;
812
- }
813
-
814
- export function resolveLandings(navigation: NavigationConfig): Landing[] {
815
- return resolveLandingsJs(navigation) as Landing[];
816
- }
817
-
818
- /** The selectors for an item's own page shown inside the item: the levels
819
- * down to the item, as for any page, plus the item's own options with none
820
- * chosen - the switcher shows the item's name until the reader picks one
821
- * (`placeholder`, currentOption() in lib/selector-placement.js). */
822
- export function landingSelectors(landing: Landing, hrefForSlug: (slug: string) => string): Selector[] {
823
- const selectors = buildSelectors(landing.path, hrefForSlug, -1, true);
824
- const level = childLevel(landing.item) as { kind: PathSegment['kind']; items: NamedContainer[] } | null;
825
- if (!level) return selectors;
826
- selectors.push({
827
- kind: level.kind,
828
- placeholder: {
829
- label: labelOf(landing.item),
830
- icon: iconOf(landing.item),
831
- description: 'description' in landing.item ? landing.item.description : undefined,
832
- },
833
- options: level.items.flatMap((child) => {
834
- if (isHidden(child)) return [];
835
- return {
836
- label: labelOf(child),
837
- icon: iconOf(child),
838
- tag: 'tag' in child ? child.tag : undefined,
839
- description: 'description' in child ? child.description : undefined,
840
- href: 'href' in child ? child.href : hrefForSlug(firstSlugOf(child as Container) ?? 'index'),
841
- active: false,
842
- dropdown: dropdownMenuOf(child as Container, hrefForSlug),
843
- };
844
- }),
845
- });
846
- return selectors;
847
- }
848
-
849
- /** Which Section (by index into resolveSections()'s result) a page belongs to. */
850
- export function findSectionIndexForSlug(sections: Section[], slug: string): number {
851
- const index = sections.findIndex((s) => flattenNav(s.pages).some((entry) => entry.slug === slug));
852
- return index === -1 ? 0 : index;
853
- }
854
-
855
- /** The always-visible topbar dropdown list - independent of whichever
856
- * primary pattern/section is active (Mintlify's equivalent is
857
- * `navigation.global.anchors`). */
858
- export function resolveGlobalDropdowns(navigation: NavigationConfig): DropdownItem[] {
859
- if (Array.isArray(navigation)) return [];
860
- return navigation.global?.dropdowns ?? [];
861
- }
862
-
863
- /** The first real page slug reachable by descending into a container's
864
- * content, however deep - used to compute where a selector option (a
865
- * tab, a version, ...) navigates to when chosen. Null for an external
866
- * `href` leaf, which the caller renders as a plain link using the
867
- * node's own href instead. Versions prefer whichever entry is marked
868
- * `default` (falling back to the first), matching Mintlify's version
869
- * default rule. */
870
- /** Tries `firstSlugOf()` against each item in order, returning the first
871
- * non-null result - a plain `items[0]` pick (the previous behavior)
872
- * breaks the moment that first sibling happens to be a bare `href` leaf
873
- * (returns null, with nothing that tries the next one), which is a real
874
- * case now that any container - not just a nested dropdown - can be a
875
- * bare external link (e.g. a `tabs` array whose first entry is
876
- * `{ tab: "Status", href: "..." }`). */
877
- function firstSlugAmong(items: Container[]): string | null {
878
- for (const item of items) {
879
- // A hidden item is reached only by its address - never by default.
880
- if (isHidden(item)) continue;
881
- const slug = firstSlugOf(item);
882
- if (slug !== null) return slug;
883
- }
884
- return null;
885
- }
886
-
887
- export function firstSlugOf(node: Container): string | null {
888
- // An item with a `page` of its own opens there (lib/item-pages.js).
889
- const own = itemPage(node);
890
- if (own !== null) return own;
891
- if ('pages' in node) return flattenNav(node.pages)[0]?.slug ?? null;
892
- if ('href' in node) return null;
893
- if ('tabs' in node) return firstSlugAmong(node.tabs);
894
- if ('versions' in node) {
895
- // Try the `default`-tagged version(s) first (matching the old
896
- // "preferred" pick), then fall through to the rest in order - same
897
- // href-leaf-with-no-fallback concern as `tabs` above, just with an
898
- // extra preference pass in front of it.
899
- const defaults = node.versions.filter((v) => v.default);
900
- const rest = node.versions.filter((v) => !v.default);
901
- return firstSlugAmong([...defaults, ...rest]);
902
- }
903
- if ('languages' in node) return firstSlugAmong(node.languages);
904
- if ('dropdowns' in node) return firstSlugAmong(node.dropdowns);
905
- if ('products' in node) return firstSlugAmong(node.products);
906
- return null;
907
- }
908
-
909
- /** For a version/language switcher, finds where the reader's current
910
- * page would live inside a *different* version/language's own subtree,
911
- * so switching keeps them on the same conceptual page instead of always
912
- * bouncing to that option's first page (see buildSelectors() below,
913
- * which is the only caller). "Same page" is approximated positionally
914
- * rather than by name, since nothing guarantees a version/language's
915
- * own identifier lines up with its pages' file paths - a version
916
- * tagged "2025-09" could just as easily keep its pages under a "v1"
917
- * folder with no relation to that string, so there's no naming
918
- * convention to key off safely; this heuristic only ever compares tree
919
- * position, never path text. (docs.json-examples/00-kitchen-sink/'s own
920
- * versions - "2025-09"/"2026-01" under Core Platform - happen to have
921
- * folder names that line up with their version strings, so it doesn't
922
- * demonstrate the mismatched-folder-name case directly; the guarantee
923
- * still doesn't exist regardless of what one fixture happens to do.)
924
- *
925
- * Two things have to line up for a page to count as "the same" one:
926
- * first, `remainingPath` (whatever tab/product/dropdown was chosen
927
- * *below* the version/language being switched, on the reader's actual
928
- * page) has to exist at the same index in `item`'s own subtree too -
929
- * an option isn't guaranteed to nest the same way that many levels
930
- * down (a version could add/remove a tab), so any mismatch here bails
931
- * out to null immediately rather than guessing. Second, once both
932
- * bottom out at a leaf `pages` list, `position` (the reader's own page
933
- * index within *its* pages list) has to exist in `item`'s pages list
934
- * too - two versions/languages of the same docs are usually authored
935
- * with matching page order even when the file paths differ, so this
936
- * is a reasonable proxy for "the same page" without relying on names.
937
- *
938
- * Returns null - meaning "no equivalent page, fall back to
939
- * firstSlugOf()" - on any structural mismatch or an out-of-range
940
- * position, rather than guessing at a wrong page. */
941
- export function equivalentPageIn(
942
- item: Container,
943
- remainingPath: PathSegment[],
944
- position: number
945
- ): string | null {
946
- if ('pages' in item) return flattenNav(item.pages)[position]?.slug ?? null;
947
- if ('href' in item) return null;
948
- const [next, ...rest] = remainingPath;
949
- if (!next) return null; // the reader's own page didn't go this deep - no basis to pick a branch
950
- if ('tabs' in item && next.kind === 'tab') {
951
- const target = item.tabs[next.index];
952
- return target ? equivalentPageIn(target, rest, position) : null;
953
- }
954
- if ('versions' in item && next.kind === 'version') {
955
- const target = item.versions[next.index];
956
- return target ? equivalentPageIn(target, rest, position) : null;
957
- }
958
- if ('languages' in item && next.kind === 'language') {
959
- const target = item.languages[next.index];
960
- return target ? equivalentPageIn(target, rest, position) : null;
961
- }
962
- if ('dropdowns' in item && next.kind === 'dropdown') {
963
- const target = item.dropdowns[next.index];
964
- return target ? equivalentPageIn(target, rest, position) : null;
965
- }
966
- if ('products' in item && next.kind === 'product') {
967
- const target = item.products[next.index];
968
- return target ? equivalentPageIn(target, rest, position) : null;
969
- }
970
- return null; // structural mismatch - this option nests differently at this depth
971
- }
972
-
973
- /** The first real page slug in the whole site, root navigation pattern
974
- * included - used to redirect `/` somewhere sensible when nothing in
975
- * the navigation happens to be a page literally named "index" (the
976
- * usual "docs/index.mdx is the homepage" convention). Mirrors
977
- * firstSlugOf()'s per-container descent, plus the flat-array root case
978
- * firstSlugOf() alone can't handle since a bare array isn't a Container. */
979
- export function firstSlugOfNavigation(navigation: NavigationConfig): string | null {
980
- if (Array.isArray(navigation)) return flattenNav(navigation)[0]?.slug ?? null;
981
- return firstSlugOf(navigation as Container);
982
- }
983
-
984
- /** Whether `slug` is reachable anywhere underneath a container, however
985
- * deep - used for computing active state on nodes that aren't part of
986
- * the active Section's own `path` (global dropdown entries). */
987
- export function containerContainsSlug(node: Container, slug: string): boolean {
988
- if ('pages' in node) return flattenNav(node.pages).some((entry) => entry.slug === slug);
989
- if ('href' in node) return false;
990
- if ('tabs' in node) return node.tabs.some((t) => containerContainsSlug(t, slug));
991
- if ('versions' in node) return node.versions.some((v) => containerContainsSlug(v, slug));
992
- if ('languages' in node) return node.languages.some((l) => containerContainsSlug(l, slug));
993
- if ('dropdowns' in node) return node.dropdowns.some((d) => containerContainsSlug(d, slug));
994
- if ('products' in node) return node.products.some((p) => containerContainsSlug(p, slug));
995
- return false;
996
- }
997
-
998
- function labelOf(item: NamedContainer): string {
999
- if ('tab' in item) return item.tab;
1000
- if ('version' in item) return item.label ?? item.version;
1001
- if ('language' in item) return item.label ?? item.language;
1002
- if ('dropdown' in item) return item.dropdown;
1003
- return item.product;
1004
- }
1005
-
1006
- function iconOf(item: NamedContainer): string | undefined {
1007
- return (item as { icon?: string }).icon;
1008
- }
1009
-
1010
- // --- Topbar selectors -------------------------------------------------
1011
- //
1012
- // One Selector per PathSegment on the active Section's path. Tabs render
1013
- // as the horizontal pill bar (all options always visible, exactly one
1014
- // current); versions/languages/products, and dropdowns used as a nested
1015
- // path segment, render as a single switcher control instead - the
1016
- // trigger shows the *current* option, its menu lists the alternatives.
1017
- // See BaseLayout.astro for the actual markup per kind.
1018
-
1019
- export interface SelectorOption {
1020
- label: string;
1021
- icon?: string;
1022
- tag?: string;
1023
- // A product's `description` - shown under its name where there's room
1024
- // (the sidebar's product switcher, see lib/selector-placement.js).
1025
- description?: string;
1026
- href: string;
1027
- active: boolean;
1028
- // Set when this option's own container is a `dropdowns` list (e.g. a
1029
- // tab whose content is `dropdowns` instead of `pages`) - the tab pill
1030
- // itself becomes a dropdown-trigger showing these as its menu, rather
1031
- // than a separate dropdown control rendered alongside it.
1032
- dropdown?: SelectorOption[];
1033
- // On an entry of that menu holding dropdowns of its own: those, shown in a
1034
- // flyout beside the entry (TopBar.astro). A tab's menu goes two levels deep
1035
- // at most (MAX_TAB_MENU_LEVELS in config-schema.ts), so a flyout's entries
1036
- // have none.
1037
- submenu?: SelectorOption[];
1038
- // On an entry with a `submenu`: the entry's own `page`, if it has one -
1039
- // clicking the entry opens it. Without one, clicking opens the flyout.
1040
- pageHref?: string;
1041
- }
1042
-
1043
- export interface Selector {
1044
- kind: PathSegment['kind'];
1045
- options: SelectorOption[];
1046
- // The page sits inside a hidden item on this level: the level isn't
1047
- // shown (its switcher would list the other items). Kept in the list,
1048
- // not dropped, so the levels after it are placed by their real parent
1049
- // (lib/selector-placement.js).
1050
- hidden?: boolean;
1051
- // No option is chosen on this level - the page is an item's own page,
1052
- // shown above its options (landingSelectors()). A switcher shows this
1053
- // instead of a current option (currentOption() in lib/selector-placement.js).
1054
- placeholder?: { label: string; icon?: string; description?: string };
1055
- }
1056
-
1057
- /** An option's own `dropdowns` menu, if it has one (see SelectorOption.dropdown
1058
- * above), with a `submenu` on each entry that holds dropdowns of its own.
1059
- * `activePath` is the path *below* this option's own segment, only passed
1060
- * when this option is the active one on its level, so a sibling option that
1061
- * also happens to own `dropdowns` doesn't spuriously mark one of its entries
1062
- * active just because some *other* option is currently selected. */
1063
- function dropdownMenuOf(
1064
- node: NavChildren,
1065
- hrefForSlug: (slug: string) => string,
1066
- activePath: PathSegment[] = [],
1067
- depth = 1
1068
- ): SelectorOption[] | undefined {
1069
- if (!('dropdowns' in node)) return undefined;
1070
- const [segment, ...below] = activePath;
1071
- return node.dropdowns.flatMap((d, i): SelectorOption[] => {
1072
- if (isHidden(d)) return [];
1073
- const active = segment?.kind === 'dropdown' && segment.index === i;
1074
- const option: SelectorOption = {
1075
- label: d.dropdown,
1076
- icon: iconOf(d),
1077
- href: 'href' in d ? d.href : hrefForSlug(firstSlugOf(d) ?? 'index'),
1078
- active,
1079
- };
1080
- if (depth === 1 && 'dropdowns' in d) {
1081
- const submenu = dropdownMenuOf(d, hrefForSlug, active ? below : [], depth + 1);
1082
- if (submenu && submenu.length > 0) {
1083
- option.submenu = submenu;
1084
- const own = itemPage(d);
1085
- if (own !== null) option.pageHref = hrefForSlug(own);
1086
- }
1087
- }
1088
- return [option];
1089
- });
1090
- }
1091
-
1092
- /** `activePagePosition` is the reader's current page's own index within
1093
- * its Section's flattened pages list (-1 if it can't be found there,
1094
- * which just disables the position-preserving behavior below) - see
1095
- * [...slug].astro for how it's computed. Only version/language
1096
- * switchers try to preserve position across options; tabs/dropdowns/
1097
- * products keep linking to firstSlugOf() unconditionally, since those
1098
- * represent genuinely different content (an "API Reference" tab isn't
1099
- * "the same page" as a "Guides" tab just because they're both first),
1100
- * unlike a version/language of what's meant to be the same docs. */
1101
- export function buildSelectors(
1102
- path: PathSegment[],
1103
- hrefForSlug: (slug: string) => string,
1104
- activePagePosition: number = -1,
1105
- // The page is an item's own page (landingSelectors()): a version or
1106
- // language switch goes to the same item in the other option - where
1107
- // choosing that item goes, its own page or its first page.
1108
- landing = false
1109
- ): Selector[] {
1110
- return path.map((segment, segIndex): Selector => {
1111
- const preservesPosition =
1112
- (segment.kind === 'version' || segment.kind === 'language') && (activePagePosition >= 0 || landing);
1113
- const remainingPath = path.slice(segIndex + 1);
1114
- return {
1115
- kind: segment.kind,
1116
- hidden: isHidden(segment.items[segment.index]),
1117
- options: (segment.items as NamedContainer[]).flatMap((item, i) => {
1118
- // A hidden item is never offered - not even to its own pages.
1119
- if (isHidden(item)) return [];
1120
- const isActive = i === segment.index;
1121
- const sameItem = preservesPosition && landing ? equivalentItem(item, remainingPath) : null;
1122
- const equivalentSlug = !preservesPosition
1123
- ? null
1124
- : landing
1125
- ? sameItem && firstSlugOf(sameItem as Container)
1126
- : equivalentPageIn(item as Container, remainingPath, activePagePosition);
1127
- const targetSlug = equivalentSlug ?? firstSlugOf(item as Container) ?? 'index';
1128
- return {
1129
- label: labelOf(item),
1130
- icon: iconOf(item),
1131
- tag: 'tag' in item ? item.tag : undefined,
1132
- description: 'description' in item ? item.description : undefined,
1133
- href: 'href' in item ? item.href : hrefForSlug(targetSlug),
1134
- active: isActive,
1135
- dropdown: dropdownMenuOf(item, hrefForSlug, isActive ? path.slice(segIndex + 1) : []),
1136
- };
1137
- }),
1138
- };
1139
- });
1140
- }
1141
-
1142
- // --- Global dropdowns ---------------------------------------------------
1143
- //
1144
- // Unlike path-segment selectors, global dropdowns aren't a mutually
1145
- // exclusive "pick one" choice - `global.dropdowns` is an array where
1146
- // *every* entry renders as its own always-visible trigger button
1147
- // simultaneously (Mintlify's anchors work the same way). A trigger's
1148
- // menu lists its own direct pages as quick links; a bare-href entry is
1149
- // just a plain link with no menu; a deeply-nested entry (tabs/versions/
1150
- // etc. instead of direct pages) falls back to linking straight to its
1151
- // first page, since building a rich flyout for that combination isn't
1152
- // worth the complexity for what's meant to be a quick-links affordance.
1153
-
1154
- export interface GlobalDropdownView {
1155
- label: string;
1156
- icon?: string;
1157
- href: string | null;
1158
- items: SelectorOption[];
1159
- }
1160
-
1161
- export function buildGlobalDropdowns(
1162
- dropdowns: DropdownItem[],
1163
- currentSlug: string,
1164
- titleForSlug: (slug: string) => string,
1165
- hrefForSlug: (slug: string) => string,
1166
- metaForSlug?: (slug: string) => NavPageMeta | undefined
1167
- ): GlobalDropdownView[] {
1168
- return dropdowns.map((d): GlobalDropdownView => {
1169
- if ('href' in d) {
1170
- return { label: d.dropdown, icon: d.icon, href: d.href, items: [] };
1171
- }
1172
- if ('pages' in d) {
1173
- // Same `hidden`/`url` handling as buildNavTree().
1174
- const items = flattenNav(d.pages)
1175
- .filter((entry) => !metaForSlug?.(entry.slug)?.hidden)
1176
- .map((entry) => ({
1177
- label: titleForSlug(entry.slug),
1178
- href: metaForSlug?.(entry.slug)?.url ?? hrefForSlug(entry.slug),
1179
- active: entry.slug === currentSlug,
1180
- }));
1181
- return { label: d.dropdown, icon: d.icon, href: null, items };
1182
- }
1183
- const slug = firstSlugOf(d);
1184
- return { label: d.dropdown, icon: d.icon, href: slug ? hrefForSlug(slug) : '#', items: [] };
1185
- });
1186
- }
1187
-
1188
- // --- Sidebar (recursive) -------------------------------------------------
1189
-
1190
- // A group node's `pageSlug` is the page its own label links to (null if
1191
- // it's a pure disclosure/label with no page of its own - the group only
1192
- // groups). NavTree.astro renders depth-0 groups as static, non-collapsible
1193
- // section titles (linked if `pageSlug` is set, plain text otherwise) and
1194
- // every deeper group as a collapsible row styled like a page item, with a
1195
- // chevron, defaulting open when it contains the active page - see
1196
- // navTreeContainsSlug() below.
1197
- export type NavTreeNode =
1198
- | {
1199
- kind: 'page';
1200
- slug: string;
1201
- title: string;
1202
- method: string | null;
1203
- icon?: string;
1204
- tag?: string;
1205
- deprecated?: boolean;
1206
- }
1207
- | { kind: 'group'; label: string; pageSlug: string | null; children: NavTreeNode[] }
1208
- | { kind: 'link'; label: string; href: string };
1209
-
1210
- /** Builds the sidebar's view model, preserving group nesting depth.
1211
- * `methodForSlug` is optional (most sites have no OpenAPI pages at all)
1212
- * and, when given, returns the HTTP method to badge a page with in the
1213
- * sidebar (e.g. "GET") or null for an ordinary page - see
1214
- * NavTree.astro for how that badge renders. */
1215
- /** Per-page frontmatter that changes how a page shows up in navigation -
1216
- * Mintlify's `hidden`, `url`, `icon`, `tag` and `deprecated` (see
1217
- * content.config.ts's docsSchema). */
1218
- export interface NavPageMeta {
1219
- hidden?: boolean;
1220
- url?: string;
1221
- icon?: string;
1222
- tag?: string;
1223
- deprecated?: boolean;
1224
- }
1225
-
1226
- export function buildNavTree(
1227
- navigation: NavItem[],
1228
- titleForSlug: (slug: string) => string,
1229
- methodForSlug?: (slug: string) => string | null,
1230
- metaForSlug?: (slug: string) => NavPageMeta | undefined
1231
- ): NavTreeNode[] {
1232
- return navigation.flatMap((item): NavTreeNode[] => {
1233
- if (typeof item === 'string') {
1234
- const meta = metaForSlug?.(item);
1235
- // A `hidden` page keeps its route but gets no sidebar entry.
1236
- if (meta?.hidden) return [];
1237
- // A `url` page is an external link in the sidebar, not a page.
1238
- if (meta?.url) return [{ kind: 'link', label: titleForSlug(item), href: meta.url }];
1239
- return [
1240
- {
1241
- kind: 'page',
1242
- slug: item,
1243
- title: titleForSlug(item),
1244
- method: methodForSlug?.(item) ?? null,
1245
- icon: meta?.icon,
1246
- tag: meta?.tag,
1247
- deprecated: meta?.deprecated,
1248
- },
1249
- ];
1250
- }
1251
- if ('href' in item) {
1252
- return [{ kind: 'link', label: item.label, href: item.href }];
1253
- }
1254
- // loadDocsConfig() always expands `{ group, openapi }` shorthand into
1255
- // a real `{ group, pages }` before anything reaches here (see
1256
- // expandOpenApiInNavigation() in the OpenAPI section above) - this is
1257
- // just a defensive no-op for the shouldn't-happen case of an
1258
- // unexpanded node reaching the sidebar builder.
1259
- if ('openapi' in item) {
1260
- return [{ kind: 'group', label: item.group, pageSlug: null, children: [] }];
1261
- }
1262
- return [
1263
- {
1264
- kind: 'group',
1265
- label: item.group,
1266
- pageSlug: item.page ?? null,
1267
- children: buildNavTree(item.pages, titleForSlug, methodForSlug, metaForSlug),
1268
- },
1269
- ];
1270
- });
1271
- }
1272
-
1273
- /** Whether `slug` is the group's own attached page, or belongs to any page/group nested inside it. */
1274
- export function navTreeContainsSlug(nodes: NavTreeNode[], slug: string): boolean {
1275
- return nodes.some((node) => {
1276
- if (node.kind === 'page') return node.slug === slug;
1277
- if (node.kind === 'link') return false;
1278
- return node.pageSlug === slug || navTreeContainsSlug(node.children, slug);
1279
- });
1280
- }
1281
-
1282
- export interface BreadcrumbCrumb {
1283
- label: string;
1284
- href: string | null;
1285
- }
1286
-
1287
- /** The chain of ancestor group labels (root first) that `slug` is nested
1288
- * under within `nodes` - empty when the page sits at the top level of its
1289
- * Section with no enclosing group at all, in which case the caller should
1290
- * skip rendering breadcrumbs entirely (there'd be nothing to show but the
1291
- * fixed home icon Breadcrumbs.astro always renders first).
1292
- *
1293
- * Deliberately never includes the current page itself - only the groups
1294
- * it's nested under (that's already the <h1> right below, repeating it
1295
- * in the breadcrumb trail would just be noise). A group whose own
1296
- * attached page (`pageSlug`, see NavTreeNode) *is* `slug` is excluded
1297
- * from its own trail for the same reason - you're looking at that page,
1298
- * it doesn't need to also list itself as its own ancestor. A group only
1299
- * appears here when `slug` is nested *inside* it (its own page, if any,
1300
- * links to that group's landing page - `href: null` for a label-only
1301
- * group with no page of its own to link to). */
1302
- export function ancestorGroupsForSlug(
1303
- nodes: NavTreeNode[],
1304
- slug: string,
1305
- hrefForSlug: (slug: string) => string
1306
- ): BreadcrumbCrumb[] {
1307
- for (const node of nodes) {
1308
- if (node.kind !== 'group') continue;
1309
- if (node.pageSlug === slug) return [];
1310
- if (navTreeContainsSlug(node.children, slug)) {
1311
- const crumb: BreadcrumbCrumb = { label: node.label, href: node.pageSlug ? hrefForSlug(node.pageSlug) : null };
1312
- return [crumb, ...ancestorGroupsForSlug(node.children, slug, hrefForSlug)];
1313
- }
1314
- }
1315
- return [];
1316
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { EXCLUDED_TOP_LEVEL_DIRS, navPageId, draftsIncluded, findDraftPages, fileIdForPath } from './pages.js';
4
+ import { withoutDrafts } from './drafts.js';
5
+ import { isHidden } from './hidden-sections.js';
6
+ import { itemPage, childLevel, equivalentItem, resolveLandings as resolveLandingsJs } from './item-pages.js';
7
+ import matter from 'gray-matter';
8
+ import { writedocsTempDir } from './writedocs-temp-dir.js';
9
+ import { readableTextOn } from './color.js';
10
+ import { oncePerBuild } from './build-memo.js';
11
+ import { normalizeBasePath, siteUrlFor, siteOriginFor } from './base-path.js';
12
+ import {
13
+ formatValidationIssues,
14
+ validateDocsConfig,
15
+ type DocsConfig,
16
+ type DropdownItem,
17
+ type FontVariant,
18
+ type LanguageItem,
19
+ type NavChildren,
20
+ type NavItem,
21
+ type NavigationConfig,
22
+ type ProductItem,
23
+ type TabItem,
24
+ type VersionItem,
25
+ } from './config-schema.ts';
26
+
27
+ // O schema do writedocs.json mora em ./config-schema.ts desde a extracao (E11):
28
+ // aquele modulo importa so `zod`, sem nada de node:fs, pra que a plataforma
29
+ // possa importa-lo por `@writedocs/generator/config-schema`. Este reexport
30
+ // mantem a superficie deste arquivo exatamente como era - quem importa
31
+ // `docsConfigSchema`, `DocsConfig`, `seoFieldsSchema`, `mergeSeo` etc. de
32
+ // './config.js' continua importando do mesmo lugar, sem mudar uma linha.
33
+ //
34
+ // `.ts` e nao o `./config-schema.js` gerado, de proposito - e a unica coisa no
35
+ // repositorio que ainda aponta pra fonte, e o bin/ e o `exports` apontam pro
36
+ // `.js`. O motivo e que este reexport carrega 24 `export type`/`interface`
37
+ // (DocsConfig, NavItem, Selector, GlobalDropdownView, ContextMenuConfig...) que
38
+ // uma duzia de .astro consome como `import type { X } from '../lib/config'`, e
39
+ // o esbuild apaga todos eles: o `.js` gerado exporta exatamente 5 simbolos de
40
+ // runtime. Este repositorio nao tem tsconfig.json nem o typescript instalado,
41
+ // entao (a) nada configura o mapeamento `.js` -> `.ts` que faria os tipos
42
+ // voltarem e (b) nao existe typecheck que reclamasse - a troca so apagaria os
43
+ // tipos em silencio. Aqui tudo passa pelo transform do Astro/Vite, que le `.ts`
44
+ // nativamente, entao o `.js` nao resolve problema nenhum deste lado.
45
+ //
46
+ // O custo aceito e que o tarball leva as duas copias e um build do Astro pode
47
+ // carregar as duas (o `.ts` por aqui, o `.js` por quem importa o subpath) - duas
48
+ // instancias do schema, inofensivas porque nada compara identidade de schema.
49
+ export * from './config-schema.ts';
50
+
51
+ /** Normalizes writedocs.json's `domain` into a full origin with no trailing
52
+ * slash (e.g. "docs.example.com" -> "https://docs.example.com"), or null
53
+ * if the site hasn't set one. The single source of truth for "does this
54
+ * site have a real deployed URL" - astro.config.mjs (sitemap
55
+ * registration), BaseLayout.astro (canonical/OG/Twitter URLs), and
56
+ * resolveAbsoluteUrl() below all call this rather than reading
57
+ * config.domain directly, so the http(s):// normalization only happens
58
+ * in one place.
59
+ *
60
+ * With a `basePath` it's the site's root, not just the origin -
61
+ * "https://empresa.com/docs" - so every absolute URL built as siteUrl + a
62
+ * site address ("/guides/a/") comes out under the base: canonical, og:url,
63
+ * hreflang, structured data, llms.txt, mcp-index.json, the .md links.
64
+ * resolveSiteOrigin() is the origin alone, for Astro's own `site`. */
65
+ export function resolveSiteUrl(config: Pick<DocsConfig, 'domain' | 'basePath'>): string | null {
66
+ return siteUrlFor(config.domain, resolveBasePath(config));
67
+ }
68
+
69
+ /** The `domain` as a full origin ("https://docs.example.com"), or null -
70
+ * without the basePath. */
71
+ export function resolveSiteOrigin(config: Pick<DocsConfig, 'domain'>): string | null {
72
+ return siteOriginFor(config.domain);
73
+ }
74
+
75
+ /** writedocs.json's `basePath` as the base every address takes: "" with no
76
+ * base, else "/docs" - see lib/base-path.js. */
77
+ export function resolveBasePath(config: Pick<DocsConfig, 'basePath'>): string {
78
+ return normalizeBasePath(config.basePath);
79
+ }
80
+
81
+ /** What goes in front of a site address to make the address a reader uses:
82
+ * the siteUrl with a `domain`, else the base alone ("/docs", or "" at the
83
+ * root) - for links that are absolute when they can be (llms.txt,
84
+ * mcp-index.json). */
85
+ export function resolveSiteRoot(config: Pick<DocsConfig, 'domain' | 'basePath'>): string {
86
+ return resolveSiteUrl(config) ?? resolveBasePath(config);
87
+ }
88
+
89
+ /** Resolves a possibly-relative asset path (e.g. `seo.ogImage: "/card.png"`)
90
+ * against the site's own domain into an absolute URL - social crawlers
91
+ * (Facebook/Twitter/Slack unfurls) generally require an absolute
92
+ * og:image/twitter:image URL, a same-origin relative path isn't reliably
93
+ * respected. Returns the value unchanged if it's already absolute, or if
94
+ * there's no siteUrl to resolve it against (a relative path is still
95
+ * better than nothing in that case - most social crawlers do at least
96
+ * attempt to fetch it relative to the page they scraped). */
97
+ export function resolveAbsoluteUrl(siteUrl: string | null, value: string): string {
98
+ if (/^https?:\/\//i.test(value)) return value;
99
+ if (!siteUrl) return value;
100
+ return `${siteUrl}${value.startsWith('/') ? '' : '/'}${value}`;
101
+ }
102
+
103
+ /** The resolved (never-undefined) Shiki theme names for light/dark code
104
+ * blocks - shared by astro.config.mjs (sitewide MDX code-fence
105
+ * highlighting) and ApiReferencePanel.astro (the API playground's own
106
+ * separate <Code/> usages, which don't inherit markdown.shikiConfig at
107
+ * all - see astro.config.mjs's own comment on that) so both read the
108
+ * same writedocs.json field and fall back to the same defaults instead of
109
+ * each hardcoding its own copy. */
110
+ export function resolveCodeblockTheme(config: DocsConfig): { light: string; dark: string } {
111
+ return {
112
+ light: config.styles.codeblocks?.light ?? 'github-light',
113
+ dark: config.styles.codeblocks?.dark ?? 'github-dark',
114
+ };
115
+ }
116
+
117
+ // mdx is a real, bundled Shiki grammar (@shikijs/langs' mdx.mjs - it does
118
+ // exist, this isn't a "Shiki doesn't know this language" situation), but in
119
+ // practice it tokenizes ```mdx fences into one single run per line with no
120
+ // internal token boundaries at all - every character, JSX tag or not,
121
+ // lands in the exact same TextMate scope and renders in the theme's plain
122
+ // foreground color. Confirmed directly against real built output: every
123
+ // span in a ```mdx block's compiled HTML carries the identical inline
124
+ // color, none of the tag/attribute/string distinction a JS or JSX fence
125
+ // gets. Aliasing to jsx - a close structural match for the JSX-heavy
126
+ // snippets these fences are actually used for in this codebase's own docs
127
+ // (`<Callout>`, `<Card>`, etc.) - actually highlights the tags/attributes,
128
+ // at the cost of not distinctly coloring the markdown-prose portions
129
+ // interleaved between them (jsx's grammar doesn't know about those) - a
130
+ // worthwhile trade given the alternative is no color at all. See
131
+ // astro.config.mjs's own shikiConfig.langAlias for where this actually
132
+ // gets used. */
133
+ const DEFAULT_CODEBLOCK_LANG_ALIAS: Record<string, string> = { mdx: 'jsx' };
134
+
135
+ /** The resolved fence-language alias map - the built-in mdx -> jsx default
136
+ * above, merged with (not replaced by) whatever a site adds under its own
137
+ * writedocs.json styles.codeblocks.langAlias, so a site can extend this list
138
+ * without having to redeclare the built-in entry to keep it. Same
139
+ * "shared resolver, not each consumer re-deriving its own defaults"
140
+ * pattern resolveCodeblockTheme() right above already establishes -
141
+ * though today only astro.config.mjs actually consumes this one, unlike
142
+ * that one, since ApiReferencePanel.astro's own <Code/> usages never
143
+ * render a `mdx`-tagged snippet (API operation samples are curl/js/
144
+ * python/etc., not MDX markup) to begin with. */
145
+ export function resolveCodeblockLangAlias(config: DocsConfig): Record<string, string> {
146
+ return { ...DEFAULT_CODEBLOCK_LANG_ALIAS, ...config.styles.codeblocks?.langAlias };
147
+ }
148
+
149
+ const DEFAULT_FONT_FAMILY = 'Inter';
150
+
151
+ export interface ResolvedFonts {
152
+ base: FontVariant;
153
+ heading: FontVariant | null;
154
+ body: FontVariant | null;
155
+ }
156
+
157
+ /** Resolves writedocs.json's `styles.fonts` into the three font declarations
158
+ * BaseLayout.astro actually needs to render: `base` (the site-wide
159
+ * default - every element gets this unless `heading`/`body` narrows it
160
+ * further), and `heading`/`body`, each `null` when not independently
161
+ * configured (letting BaseLayout fall back to `base` for whichever side
162
+ * wasn't overridden, rather than this function silently copying `base`
163
+ * into both and losing the distinction between "explicitly set to the
164
+ * same font" and "just inheriting the default"). The one hardcoded
165
+ * default in this whole feature lives right here: no `styles.fonts` at
166
+ * all resolves to plain Inter, loaded for real (a Google Fonts `<link>`,
167
+ * not just a name in a fallback stack that only renders correctly for a
168
+ * reader who happens to already have Inter installed - see base.css's
169
+ * old `font-family` rule, which was exactly that, before this feature
170
+ * existed). */
171
+ export function resolveFonts(config: DocsConfig): ResolvedFonts {
172
+ const fonts = config.styles.fonts;
173
+ const base: FontVariant = fonts
174
+ ? { family: fonts.family, weight: fonts.weight, source: fonts.source, format: fonts.format }
175
+ : { family: DEFAULT_FONT_FAMILY };
176
+ return { base, heading: fonts?.heading ?? null, body: fonts?.body ?? null };
177
+ }
178
+
179
+ /** The Google Fonts CSS2 API URL for every font in `fonts` that isn't a
180
+ * `source`-based (local/externally-hosted) font - `null` if there's
181
+ * nothing to load this way at all (every configured font has its own
182
+ * `source`). One request covers every family needed (`&family=` repeated
183
+ * per unique family+weight pair, deduped so the same pair - e.g. `base`
184
+ * and `body` both left at the site default - isn't requested twice)
185
+ * rather than a separate `<link>` per font. `display=swap` avoids an
186
+ * invisible-text flash while the font file loads (renders in the
187
+ * fallback stack immediately, swaps once the real font is ready) -
188
+ * Google's own recommended default for exactly this use case. */
189
+ export function googleFontsHref(fonts: ResolvedFonts): string | null {
190
+ const entries = [fonts.base, fonts.heading, fonts.body].filter(
191
+ (f): f is FontVariant => f !== null && !f.source
192
+ );
193
+ if (entries.length === 0) return null;
194
+ const seen = new Set<string>();
195
+ const params: string[] = [];
196
+ for (const f of entries) {
197
+ const key = `${f.family}|${f.weight ?? ''}`;
198
+ if (seen.has(key)) continue;
199
+ seen.add(key);
200
+ const familyParam = f.family.trim().replace(/\s+/g, '+');
201
+ params.push(f.weight ? `family=${familyParam}:wght@${f.weight}` : `family=${familyParam}`);
202
+ }
203
+ return `https://fonts.googleapis.com/css2?${params.join('&')}&display=swap`;
204
+ }
205
+
206
+ /** A `@font-face` rule for one `source`-based font (local project path or
207
+ * externally-hosted URL), or `''` for a Google Font (no `source` - see
208
+ * googleFontsHref() above, the other half of font loading). `weight`
209
+ * becomes the rule's `font-weight` *descriptor* here - it tells the
210
+ * browser which weight this specific file represents, so a `font-weight`
211
+ * CSS value requested elsewhere (BaseLayout.astro's own
212
+ * `wdFontWeightHeading`/`wdFontWeightBody`, see its comment) picks the
213
+ * real matching file instead of synthetically ("faux") bolding/
214
+ * thinning a mismatched one. This function only ever produces the
215
+ * `@font-face` rule itself - actually applying `font-weight` to any
216
+ * element (h1-h6, body) is BaseLayout's job, not this one's. */
217
+ export function fontFaceRule(font: FontVariant | null): string {
218
+ if (!font || !font.source) return '';
219
+ const weightDecl = font.weight !== undefined ? ` font-weight: ${font.weight};` : '';
220
+ return `@font-face { font-family: '${font.family}'; src: url('${font.source}') format('${font.format ?? 'woff2'}'); font-display: swap;${weightDecl} }`;
221
+ }
222
+
223
+ /** Splits one side of `styles.navbar` (the string-or-object union
224
+ * navbarColorValueSchema allows) into its two parts, filling in the
225
+ * fallback background when the field is unset at all. `accent` stays
226
+ * `undefined` - not defaulted here - for both the bare-string case and
227
+ * the object case where a site set `background` without `accent`;
228
+ * BaseLayout.astro is what turns that `undefined` into "fall back to
229
+ * --wd-primary" for the accent CSS var. There's no `foreground` here at
230
+ * all to resolve - the navbar's text/icon color is never read from
231
+ * writedocs.json, see `navbar`'s own schema comment (stylesSchema) for why. */
232
+ export function resolveNavbarColor(
233
+ value: string | { background: string; accent?: string } | undefined,
234
+ fallbackBackground: string
235
+ ): { background: string; accent: string | undefined } {
236
+ if (!value) return { background: fallbackBackground, accent: undefined };
237
+ if (typeof value === 'string') return { background: value, accent: undefined };
238
+ return { background: value.background, accent: value.accent };
239
+ }
240
+
241
+ /** Picks black or white text for `hexColor` - white unless white falls
242
+ * below 3:1 on it (readableTextOn() in lib/color.js), the same rule and
243
+ * WCAG math `writedocs a11y` checks with, so the check measures what the
244
+ * site renders. (This used a BT.601 brightness threshold.) Also
245
+ * gives `--wd-on-primary`, the text on step numbers, the info banner and
246
+ * the API playground's buttons. Used two ways in BaseLayout.astro: for `--wd-navbar-accent-text`
247
+ * (the active tab's own fill used to always be `var(--wd-primary)` with
248
+ * hardcoded `color: #fff`, which only actually read fine because every
249
+ * default/example primary color so far has been dark/saturated enough
250
+ * for white text; once a site's navbar accent can be *any* color -
251
+ * `styles.navbar.light.accent`, falling back to `styles.colors.primary`
252
+ * when unset, see resolveNavbarColor() above - that assumption can't
253
+ * hold unconditionally), and for `--wd-navbar-foreground` itself once
254
+ * `styles.navbar` is configured at all (the navbar's plain text/icon
255
+ * color - see `navbar`'s own schema comment for why that's always
256
+ * computed, never a writedocs.json value). Malformed input (not a
257
+ * `#rgb`/`#rrggbb` hex) falls back to white rather than throwing - same "don't
258
+ * fail a build over a cosmetic color value" posture every other color
259
+ * field here takes (none of them validate hex syntax either). */
260
+ export function contrastTextColor(hexColor: string): '#000000' | '#ffffff' {
261
+ return readableTextOn(hexColor) as '#000000' | '#ffffff';
262
+ }
263
+
264
+ /** Whether an href points off-site - has an explicit scheme (`https:`,
265
+ * `mailto:`, `tel:`, ...) or is protocol-relative (`//...`) - versus a
266
+ * same-site path, which this codebase always produces as a single
267
+ * leading slash (hrefForSlug() in [...slug].astro). Used everywhere a
268
+ * nav link is rendered to decide whether it should open in a new tab;
269
+ * deliberately a plain string check rather than a schema-level flag,
270
+ * so it applies uniformly to every href source (topbar.links, a
271
+ * switcher/tab pill pointing at a bare `href` container, a global
272
+ * dropdown's own link, a sidebar link leaf) without threading an
273
+ * `external` field through every one of those call sites. */
274
+ export function isExternalHref(href: string): boolean {
275
+ return /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith('//');
276
+ }
277
+
278
+ // ---------------------------------------------------------------------
279
+ // Icons - writedocs.json's `icon` fields (TabItem, DropdownItem, ProductItem,
280
+ // Card) are plain strings with no schema-level distinction between "an
281
+ // emoji, paste it verbatim" and "an icon-set name, look it up". Resolved
282
+ // here rather than validated in the schema, since both are valid uses of
283
+ // the same string field and the right rendering only becomes obvious once
284
+ // you look at the value's shape.
285
+ // ---------------------------------------------------------------------
286
+
287
+ export type IconResolution =
288
+ | { kind: 'iconify'; name: string } // ready for astro-icon/components' <Icon name=... />
289
+ | { kind: 'image'; src: string } // an image URL or site path, rendered as <img>
290
+ | { kind: 'text'; value: string }; // literal text/emoji, rendered as-is
291
+
292
+ // The implementation lives in lib/icons.js - plain JavaScript, because
293
+ // `writedocs validate` loads it with plain Node (see that file's comment).
294
+ export { resolveIcon, iconExists, iconSvg } from './icons.js';
295
+
296
+ // ---------------------------------------------------------------------
297
+ // OpenAPI navigation expansion - turns a group's `openapi: { src, path }`
298
+ // shorthand into a concrete `{ group, pages }` (one sub-group per tag),
299
+ // using the per-spec manifest generate-api-pages.js writes to
300
+ // writedocsTempDir()'s openapi/<path>/manifest.json before Astro starts (both
301
+ // `writedocs dev` and `writedocs build` run it first - see
302
+ // src/cli/dev.js, src/cli/build.js). Applied once, here in
303
+ // loadDocsConfig(), so every other function in this file
304
+ // (resolveSections, flattenNav, buildNavTree, ...) only ever sees plain
305
+ // page-slug strings and ordinary `{ group, pages }` nodes, and never
306
+ // needs to know the `openapi` group shorthand exists. A writedocs.json can
307
+ // have any number of these groups, each pointing at its own spec and
308
+ // mounted under its own `path` - generate-api-pages.js namespaces each
309
+ // spec's manifest/operations under that same `path`, so there's no
310
+ // cross-spec collision as long as every group uses a distinct `path`.
311
+ // ---------------------------------------------------------------------
312
+
313
+ export interface OpenApiManifestEntry {
314
+ slug: string;
315
+ method: string;
316
+ path: string;
317
+ tags: string[];
318
+ title: string;
319
+ generated: boolean;
320
+ }
321
+
322
+ /** `specPath` is the owning group's own `openapi.path` (e.g. "/api") -
323
+ * generate-api-pages.js writes each spec's manifest under a directory
324
+ * named after that same value, so this only ever needs to know which
325
+ * group is asking, not anything about the spec's contents itself. */
326
+ function loadOpenApiManifest(contentDir: string, specPath: string): OpenApiManifestEntry[] | null {
327
+ const normalized = specPath.replace(/^\/+|\/+$/g, '');
328
+ const manifestPath = path.join(writedocsTempDir(contentDir), 'openapi', normalized, 'manifest.json');
329
+ if (!fs.existsSync(manifestPath)) return null;
330
+ try {
331
+ return JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
332
+ } catch {
333
+ return null; // stale/partial write from an interrupted previous run - treat as absent
334
+ }
335
+ }
336
+
337
+ /** Expands one group's `openapi: { src, path }` into the `pages` array
338
+ * it stands in for - one sub-group per tag (in first-seen order),
339
+ * untagged operations collected into a trailing "Other" group. Returns
340
+ * an empty array (an empty, harmless group) rather than throwing if the
341
+ * manifest is missing - generate-api-pages.js always runs before this
342
+ * does (see src/cli/dev.js/build.js), so a missing manifest here means
343
+ * generation hasn't happened yet rather than a user error worth
344
+ * crashing the dev server over. */
345
+ function expandOpenApiGroupPages(openapiRef: { src: string; path: string }, contentDir: string): NavItem[] {
346
+ const manifest = loadOpenApiManifest(contentDir, openapiRef.path);
347
+ if (!manifest) return [];
348
+
349
+ const seenTags: string[] = [];
350
+ const byTag = new Map<string, string[]>();
351
+ const untagged: string[] = [];
352
+ for (const op of manifest) {
353
+ const tag = op.tags[0];
354
+ if (!tag) {
355
+ untagged.push(op.slug);
356
+ continue;
357
+ }
358
+ if (!byTag.has(tag)) {
359
+ byTag.set(tag, []);
360
+ seenTags.push(tag);
361
+ }
362
+ byTag.get(tag)!.push(op.slug);
363
+ }
364
+ const groups: NavItem[] = seenTags.map((tag) => ({ group: tag, pages: byTag.get(tag)! }));
365
+ return untagged.length > 0 ? [...groups, { group: 'Other', pages: untagged }] : groups;
366
+ }
367
+
368
+ function expandOpenApiInPages(pages: NavItem[], contentDir: string): NavItem[] {
369
+ return pages.map((item): NavItem => {
370
+ if (typeof item === 'string') return item;
371
+ if ('href' in item) return item;
372
+ if ('openapi' in item) {
373
+ // A group using the { group, openapi: { src, path } } shorthand -
374
+ // replace it with a real { group, pages } node built from that
375
+ // spec's own manifest, so nothing downstream needs to know the
376
+ // shorthand ever existed.
377
+ return { group: item.group, pages: expandOpenApiGroupPages(item.openapi, contentDir) };
378
+ }
379
+ // An ordinary { group, page?, pages } - recurse into its own pages,
380
+ // since an openapi-group can be nested inside a hand-authored group
381
+ // too (e.g. wrapping it to add hand-written pages alongside the
382
+ // auto-generated ones).
383
+ return { ...item, pages: expandOpenApiInPages(item.pages, contentDir) };
384
+ });
385
+ }
386
+
387
+ /** Mirrors walkSections()'s traversal (tabs/versions/languages/
388
+ * dropdowns/products, each bottoming out at `pages`), but rewrites
389
+ * rather than collects - every `pages` array anywhere in the tree gets
390
+ * run through expandOpenApiInPages(). */
391
+ function expandOpenApiInContainer(node: NavChildren, contentDir: string): NavChildren {
392
+ if ('pages' in node) return { pages: expandOpenApiInPages(node.pages, contentDir) };
393
+ if ('href' in node) return node;
394
+ if ('tabs' in node) {
395
+ return { tabs: node.tabs.map((t) => ({ ...t, ...expandOpenApiInContainer(t, contentDir) })) };
396
+ }
397
+ if ('versions' in node) {
398
+ return { versions: node.versions.map((v) => ({ ...v, ...expandOpenApiInContainer(v, contentDir) })) };
399
+ }
400
+ if ('languages' in node) {
401
+ return { languages: node.languages.map((l) => ({ ...l, ...expandOpenApiInContainer(l, contentDir) })) };
402
+ }
403
+ if ('dropdowns' in node) {
404
+ return { dropdowns: node.dropdowns.map((d) => ({ ...d, ...expandOpenApiInContainer(d, contentDir) })) };
405
+ }
406
+ if ('products' in node) {
407
+ return { products: node.products.map((p) => ({ ...p, ...expandOpenApiInContainer(p, contentDir) })) };
408
+ }
409
+ return node;
410
+ }
411
+
412
+ function expandOpenApiInNavigation(navigation: NavigationConfig, contentDir: string): NavigationConfig {
413
+ if (Array.isArray(navigation)) return expandOpenApiInPages(navigation, contentDir);
414
+ const expanded = { ...navigation, ...expandOpenApiInContainer(navigation as Container, contentDir) };
415
+ if (navigation.global?.dropdowns) {
416
+ expanded.global = {
417
+ dropdowns: navigation.global.dropdowns.map(
418
+ (d) => ({ ...d, ...expandOpenApiInContainer(d, contentDir) }) as DropdownItem
419
+ ),
420
+ };
421
+ }
422
+ return expanded as NavigationConfig;
423
+ }
424
+
425
+ export function loadDocsConfig(contentDir: string): DocsConfig {
426
+ // Read and validated once per build, not once per page (lib/build-memo.js):
427
+ // every caller there gets the same object, so none of them may change it.
428
+ // In `writedocs dev` it's read again on every call, and an edit shows up.
429
+ return oncePerBuild(`config:${contentDir}`, () => readDocsConfig(contentDir));
430
+ }
431
+
432
+ function readDocsConfig(contentDir: string): DocsConfig {
433
+ const configPath = path.join(contentDir, 'writedocs.json');
434
+ if (!fs.existsSync(configPath)) {
435
+ throw new Error(
436
+ `[writedocs] writedocs.json not found at ${configPath}. Run "writedocs init" to scaffold one.`
437
+ );
438
+ }
439
+ // A validacao em si (JSON.parse incluso) vive em validateDocsConfig
440
+ // (./config-schema.ts), o mesmo ponto de entrada que o `writedocs validate` e
441
+ // a plataforma usam - e o que garante que os tres reportem exatamente os
442
+ // mesmos problemas, com as mesmas palavras.
443
+ //
444
+ // As duas formas de falhar continuam saindo daqui EXATAMENTE como saiam antes
445
+ // desta extracao:
446
+ // - JSON quebrado: relanca o proprio SyntaxError do JSON.parse (mesmo tipo,
447
+ // mesma mensagem que o runtime produz);
448
+ // - schema invalido: o mesmo Error, com o mesmo texto, montado a partir do
449
+ // mesmo formatador que a CLI usa.
450
+ const result = validateDocsConfig(fs.readFileSync(configPath, 'utf-8'));
451
+ if (!result.ok) {
452
+ if (result.parseError) throw result.parseError;
453
+ throw new Error(
454
+ `[writedocs] writedocs.json failed validation:\n${formatValidationIssues(result.issues, { total: result.issuesTotal, truncated: result.issuesTruncated })}`
455
+ );
456
+ }
457
+ // A no-op pass over ordinary navigation trees (no openapi groups) -
458
+ // always run, rather than gated behind a global manifest check, since
459
+ // there's no longer a single global spec to check for.
460
+ result.data.navigation = withPageIds(expandOpenApiInNavigation(result.data.navigation, contentDir));
461
+ // `writedocs build` (without --drafts): no entry for a draft page, and no
462
+ // item left with no pages - everything that reads the navigation sees it
463
+ // this way (lib/drafts.js). The build prints what was left out
464
+ // (draftWarnings(), src/cli/build.js).
465
+ if (!draftsIncluded()) {
466
+ const draftIds = new Set(findDraftPages(contentDir).map((draft) => fileIdForPath(draft.file)));
467
+ result.data.navigation = withoutDrafts(result.data.navigation, draftIds).navigation;
468
+ }
469
+ return result.data;
470
+ }
471
+
472
+ /** The navigation with every page entry as its page id - "guides/index"
473
+ * becomes "guides" (navPageId() in lib/pages.js), so everything that
474
+ * matches entries against pages (routes, the sidebar, prev/next, llms.txt,
475
+ * the MCP index) finds a folder's index.mdx however writedocs.json names it. */
476
+ function withPageIds<T>(node: T): T {
477
+ if (Array.isArray(node)) return node.map((item) => (typeof item === 'string' ? navPageId(item) : withPageIds(item))) as T;
478
+ if (node && typeof node === 'object') {
479
+ return Object.fromEntries(
480
+ Object.entries(node).map(([key, value]) => [
481
+ key,
482
+ key === 'page' && typeof value === 'string' ? navPageId(value) : key === 'href' || key === 'openapi' ? value : withPageIds(value),
483
+ ])
484
+ ) as T;
485
+ }
486
+ return node;
487
+ }
488
+
489
+ // --- Locating a page by file id, independent of its effective slug -----
490
+ //
491
+ // writedocs.json's `pages` arrays, and every helper above/below that walks
492
+ // them (flattenNav, firstSlugOf, containerContainsSlug, buildNavTree, ...),
493
+ // always identify a page by its file id - its path relative to the
494
+ // content directory (project root), extension stripped, with a trailing
495
+ // `/index` segment dropped (matching Astro's own default id computation -
496
+ // see the `/index` note below) - regardless of how that page ends up
497
+ // being served. docs/ is not special: a file at `docs/guides/x.mdx` has
498
+ // file id `docs/guides/x`, the exact same rule applied to a file
499
+ // anywhere else in the project.
500
+ //
501
+ // A page's actual URL is a separate question, and Astro's own glob()
502
+ // content loader already has a first-class answer for it: if a page's
503
+ // frontmatter sets `slug`, `entry.id` (and therefore the route Astro
504
+ // builds for it) becomes that value verbatim instead of the file-path
505
+ // default - see astro/dist/content/loaders/glob.js's generateIdDefault:
506
+ // `if (data.slug) return data.slug`. content.config.ts's `slug` schema
507
+ // field is deliberately the same field Astro already recognizes, so
508
+ // nothing here needs to reimplement the override or track it separately -
509
+ // it only needs a way to find a page BY file id (to resolve writedocs.json's
510
+ // references) even once `entry.id` no longer equals it.
511
+ //
512
+ // --- Page discovery -------------------------------------------------
513
+ //
514
+ // Any .md/.mdx file anywhere under the content directory becomes a page
515
+ // candidate the moment it has *any* frontmatter block at all - docs/ has
516
+ // no special status here, it's just a folder like any other (a
517
+ // conventional, recommended place to put most pages, not a requirement).
518
+ // content.config.ts's `pages` collection is the same docsSchema applied
519
+ // to exactly this file set. A file with zero frontmatter (no `---` block
520
+ // whatsoever) is never a page candidate - a snippet (see
521
+ // docs/dev/docs/snippets.mdx) typically has none, which is what lets it
522
+ // live anywhere without tripping schema validation. A file that *does*
523
+ // open a frontmatter block but is missing a required field (`title`)
524
+ // still fails validation exactly as before - only "no frontmatter at
525
+ // all" is new; a genuine mistake (frontmatter present, title forgotten)
526
+ // stays a loud build error rather than being silently treated as
527
+ // non-page content.
528
+ //
529
+ // A handful of directories are never scanned regardless of what's in
530
+ // them - build output, dependencies, and writedocs' own working
531
+ // directories, none of which a site author would ever intend as page
532
+ // content. Only excluded at the content directory's own top level (a
533
+ // hand-authored `guides/dist-notes.mdx` isn't mistaken for the build
534
+ // output directory `dist/` just because a folder two levels down happens
535
+ // to also be named `dist`).
536
+ // EXCLUDED_TOP_LEVEL_DIRS and findAllPages() live in lib/pages.js - plain
537
+ // JavaScript, so `writedocs validate` can find a site's pages with plain Node.
538
+ export { findAllPages } from './pages.js';
539
+
540
+ // findRootAssets() lives in lib/pages.js - plain JavaScript, so it can be
541
+ // tested with plain Node, next to findAllPages() whose exclusions it shares.
542
+ export { findRootAssets } from './pages.js';
543
+
544
+ /** The root-relative URL paths (leading `/`, e.g. `/images/hero.svg`)
545
+ * referenced by the writedocs.json/styles fields that point at a static asset
546
+ * *by URL* rather than embedding it inline: `styles.favicon`,
547
+ * `styles.logo` (both the plain-string and `{light, dark}` object forms),
548
+ * `styles.background.images.{light,dark}`, and `seo.ogImage`. External
549
+ * URLs (anything not starting with `/` - `https://...`, mainly) are
550
+ * filtered out, since those need no local file resolution at all.
551
+ * Deduped, since e.g. `logo.light` and `background.images.light`
552
+ * coincidentally pointing at the same file shouldn't resolve/copy it
553
+ * twice.
554
+ *
555
+ * Used by `stylesAssetFallback()` (`styles-asset-integration.js`,
556
+ * imported from `astro.config.mjs`) to let every one of these resolve
557
+ * from *anywhere* in the project, not just `public/` - previously,
558
+ * `public/` was the one place `styles.background.images` (etc.) had to
559
+ * live, since Astro's own `publicDir` copy is the only thing that ever
560
+ * served them; everywhere else in this codebase's own "drop a file
561
+ * anywhere, it's found" convention (`findRootAssets()` in lib/pages.js,
562
+ * `findAllPages()` for content) already worked project-wide. See that
563
+ * integration's own comment for the actual resolution mechanism (a dev-time
564
+ * middleware plus a post-build copy step, not a duplicated `publicDir`)
565
+ * and why a straight copy-into-`public/`-on-disk approach was rejected.
566
+ *
567
+ * Logo light/dark resolution here deliberately mirrors BaseLayout.astro's
568
+ * own `logoLight`/`logoDark` derivation exactly (a plain-string `logo`
569
+ * counts as both light and dark) - two independent implementations of
570
+ * that same union-unwrapping would only be one accidental edit away from
571
+ * disagreeing with each other. `footer.logo` (footerSchema) gets the
572
+ * same treatment, independently of `styles.logo` - both are collected
573
+ * unconditionally here (not just whichever one BaseLayout.astro would
574
+ * actually end up using for a given page), since this function has no
575
+ * page context to know which page modes render a footer at all; an
576
+ * unreferenced path collected here that never actually renders anywhere
577
+ * is harmless (nothing copies/resolves a file that's never requested),
578
+ * but a real footer.logo file silently 404ing because this function
579
+ * didn't know to resolve it is exactly the bug this comment is warning
580
+ * future edits away from repeating.
581
+ *
582
+ * Per-page frontmatter `seo.ogImage` overrides are deliberately out of
583
+ * scope - those aren't visible from a `DocsConfig` alone (they live in
584
+ * each page's own frontmatter, merged in per-request by [...slug].astro/
585
+ * BaseLayout.astro), and resolving every page's own override would need
586
+ * a full content scan this function has no reason to also become. A
587
+ * page overriding `seo.ogImage` to something outside `public/` still
588
+ * needs to put it there for now. */
589
+ export function collectConfiguredAssetPaths(config: DocsConfig): string[] {
590
+ const logo = config.styles.logo;
591
+ const logoLight = typeof logo === 'string' ? logo : logo?.light;
592
+ const logoDark = typeof logo === 'string' ? logo : logo?.dark;
593
+ const footerLogo = config.footer.logo;
594
+ const footerLogoLight = typeof footerLogo === 'string' ? footerLogo : footerLogo?.light;
595
+ const footerLogoDark = typeof footerLogo === 'string' ? footerLogo : footerLogo?.dark;
596
+ const fonts = config.styles.fonts;
597
+ const raw: (string | undefined)[] = [
598
+ config.styles.favicon,
599
+ logoLight,
600
+ logoDark,
601
+ footerLogoLight,
602
+ footerLogoDark,
603
+ config.styles.background?.images?.light,
604
+ config.styles.background?.images?.dark,
605
+ config.seo?.ogImage,
606
+ // A `styles.fonts` `source` is only ever handled here when it's a
607
+ // project-relative path (the `p.startsWith('/')` filter below already
608
+ // excludes both Google Font names, which never start with "/", and a
609
+ // full https:// external font URL, which the browser fetches directly
610
+ // - neither needs resolving/copying through this pipeline at all).
611
+ fonts?.source,
612
+ fonts?.heading?.source,
613
+ fonts?.body?.source,
614
+ ];
615
+ const paths = raw.filter((p): p is string => Boolean(p) && p.startsWith('/'));
616
+ return Array.from(new Set(paths));
617
+ }
618
+
619
+ export interface DocsEntryLike {
620
+ id: string;
621
+ filePath?: string;
622
+ }
623
+
624
+ /** Recovers a content entry's writedocs.json-facing file id (its path
625
+ * relative to the content directory, extension stripped, trailing
626
+ * `/index` dropped), independent of any frontmatter `slug` override -
627
+ * `entry.filePath` is always root-relative and POSIX-separated (how
628
+ * Astro's content layer records it, relative to whatever `--root` Astro
629
+ * itself was invoked with - see run-astro.js), so both it and the
630
+ * content directory are resolved to absolute paths before comparing,
631
+ * rather than string-matching a prefix that could be relative,
632
+ * absolute, or platform-separated inconsistently.
633
+ *
634
+ * The trailing-`/index`-drop mirrors Astro's own default id computation
635
+ * exactly (`getContentEntryIdAndSlug()` in astro/dist/content/
636
+ * utils.js: segments are joined then `.replace(/\/index$/, '')`) -
637
+ * without it, a nested index file like `docs/guides/index.mdx` (Astro's
638
+ * own default id: "docs/guides") would recover the wrong file id here
639
+ * ("docs/guides/index"), and a writedocs.json reference written to match the
640
+ * page's real URL would fail to resolve. A single-segment `index.mdx`
641
+ * at the content root is unaffected either way - the regex requires a
642
+ * preceding `/`, which a bare "index" doesn't have (matching Astro's
643
+ * own behavior: a root-level index.mdx keeps file id "index", not "").
644
+ *
645
+ * Full per-segment slugification (github-slugger, applied by Astro to
646
+ * every path segment) is deliberately *not* replicated here - every
647
+ * filename in this codebase's own fixtures and every filename this
648
+ * function needs to have handled correctly is already slug-safe
649
+ * (lowercase, hyphenated, no spaces/unicode), so slugification is
650
+ * always a no-op in practice; only the `/index`-stripping behavior is
651
+ * reproduced, since that's the one part of Astro's algorithm this
652
+ * change newly exercises (a file that used to be a collection's own
653
+ * base-root index, exempt from stripping, and is now nested one level
654
+ * deeper).
655
+ *
656
+ * Entries from the `generatedDocs` collection (auto-generated OpenAPI
657
+ * stub pages - see content.config.ts / generate-api-pages.js) live
658
+ * under writedocsTempDir()'s generated-docs/ directory - an OS temp
659
+ * directory location entirely outside contentDir, not a subdirectory
660
+ * of it - so `relativeToContentDir` for one of these always starts with
661
+ * `..` (walking back out of contentDir to reach it), and the check
662
+ * right below falls back to `entry.id` instead of computing a
663
+ * nonsensical id relative to a directory the file was never actually
664
+ * under. Those entries always set their own `slug` frontmatter
665
+ * explicitly, so there's no independent "file path" identity worth
666
+ * recovering for them the way there is for a hand-written page that
667
+ * might move around - `entry.id` (Astro's already-resolved slug)
668
+ * already IS the exact value generate-api-pages.js's own manifest
669
+ * references them by. */
670
+ export function fileIdForEntry(
671
+ contentDir: string,
672
+ packageRoot: string,
673
+ entry: DocsEntryLike
674
+ ): string {
675
+ if (!entry.filePath) return entry.id;
676
+ const absoluteContentDir = path.resolve(contentDir);
677
+ const absoluteFilePath = path.resolve(packageRoot, entry.filePath);
678
+ const relativeToContentDir = path.relative(absoluteContentDir, absoluteFilePath);
679
+ // Outside contentDir: `..`-prefixed, or - on Windows, when the file is on
680
+ // another drive (temp on C:, project on D:) - an absolute path, since
681
+ // path.relative() can't bridge drives.
682
+ if (relativeToContentDir.startsWith('..') || path.isAbsolute(relativeToContentDir)) return entry.id;
683
+ const posixRelative = relativeToContentDir.split(path.sep).join('/');
684
+ if (EXCLUDED_TOP_LEVEL_DIRS.has(posixRelative.split('/')[0])) return entry.id;
685
+ return posixRelative.replace(/\.mdx?$/i, '').replace(/\/index$/, '');
686
+ }
687
+
688
+ /** Normalizes a raw `entry.id` into the bare, slash-free form every
689
+ * route/href in this codebase assumes. Once a page sets a frontmatter
690
+ * `slug`, `entry.id` becomes that value completely verbatim - Astro's
691
+ * glob loader applies no normalization of its own (see
692
+ * generateIdDefault in astro/dist/content/loaders/glob.js) - so
693
+ * `slug: /` or `slug: /guides/new-name` (both natural things to write,
694
+ * mirroring how every href elsewhere in writedocs.json already has a
695
+ * leading slash) would otherwise produce broken multi-slash hrefs
696
+ * wherever hrefForSlug wraps the value in its own `/${slug}/`, and a
697
+ * bare "/" would additionally fail to be recognized as claiming root,
698
+ * colliding with the synthetic root-redirect route. */
699
+ export function normalizeEntryId(id: string): string {
700
+ const trimmed = id.replace(/^\/+/, '').replace(/\/+$/, '');
701
+ return trimmed === '' ? 'index' : trimmed;
702
+ }
703
+
704
+ export interface FlatNavEntry {
705
+ slug: string;
706
+ group: string | null;
707
+ }
708
+
709
+ export function flattenNav(navigation: NavItem[], group: string | null = null): FlatNavEntry[] {
710
+ return navigation.flatMap((item): FlatNavEntry[] => {
711
+ if (typeof item === 'string') {
712
+ return [{ slug: item, group }];
713
+ }
714
+ if ('href' in item) return []; // external link leaf, not a content page - no route/prev-next entry
715
+ // loadDocsConfig() always expands `{ group, openapi }` shorthand into
716
+ // a real `{ group, pages }` before anything reaches here (see
717
+ // expandOpenApiInNavigation() above) - this is just a defensive
718
+ // no-op for the shouldn't-happen case of an unexpanded node.
719
+ if ('openapi' in item) return [];
720
+ const ownPage: FlatNavEntry[] = item.page ? [{ slug: item.page, group: item.group }] : [];
721
+ return [...ownPage, ...flattenNav(item.pages, item.group)];
722
+ });
723
+ }
724
+
725
+ // --- Sections -------------------------------------------------------
726
+ //
727
+ // A Section is the atomic unit that owns one page tree and therefore one
728
+ // sidebar - every real content page belongs to exactly one Section,
729
+ // whichever `pages` leaf it's listed under, however deep in the
730
+ // tabs/versions/languages/dropdowns/products tree that leaf lives.
731
+ //
732
+ // A Section's `path` records the full chain of containers from the
733
+ // navigation root down to it, one PathSegment per level. This is
734
+ // everything the topbar needs to render the right selector controls
735
+ // (tabs bar, version dropdown, ...) and highlight the right option in
736
+ // each - without the router or layout needing to know how deep or in
737
+ // what order the site author nested things.
738
+
739
+ export type PathSegment =
740
+ | { kind: 'tab'; items: TabItem[]; index: number }
741
+ | { kind: 'version'; items: VersionItem[]; index: number }
742
+ | { kind: 'language'; items: LanguageItem[]; index: number }
743
+ | { kind: 'dropdown'; items: DropdownItem[]; index: number }
744
+ | { kind: 'product'; items: ProductItem[]; index: number };
745
+
746
+ export interface Section {
747
+ pages: NavItem[];
748
+ path: PathSegment[];
749
+ }
750
+
751
+ type Container = NavChildren;
752
+ type NamedContainer = TabItem | VersionItem | LanguageItem | DropdownItem | ProductItem;
753
+
754
+ function walkSections(node: Container, path: PathSegment[], out: Section[]): void {
755
+ if ('pages' in node) {
756
+ out.push({ pages: node.pages, path });
757
+ return;
758
+ }
759
+ if ('href' in node) return; // external link, not a Section
760
+ if ('tabs' in node) {
761
+ node.tabs.forEach((item, index) =>
762
+ walkSections(item, [...path, { kind: 'tab', items: node.tabs, index }], out)
763
+ );
764
+ return;
765
+ }
766
+ if ('versions' in node) {
767
+ node.versions.forEach((item, index) =>
768
+ walkSections(item, [...path, { kind: 'version', items: node.versions, index }], out)
769
+ );
770
+ return;
771
+ }
772
+ if ('languages' in node) {
773
+ node.languages.forEach((item, index) =>
774
+ walkSections(item, [...path, { kind: 'language', items: node.languages, index }], out)
775
+ );
776
+ return;
777
+ }
778
+ if ('dropdowns' in node) {
779
+ node.dropdowns.forEach((item, index) =>
780
+ walkSections(item, [...path, { kind: 'dropdown', items: node.dropdowns, index }], out)
781
+ );
782
+ return;
783
+ }
784
+ if ('products' in node) {
785
+ node.products.forEach((item, index) =>
786
+ walkSections(item, [...path, { kind: 'product', items: node.products, index }], out)
787
+ );
788
+ return;
789
+ }
790
+ }
791
+
792
+ export function resolveSections(navigation: NavigationConfig): Section[] {
793
+ if (Array.isArray(navigation)) return [{ pages: navigation, path: [] }];
794
+ const sections: Section[] = [];
795
+ walkSections(navigation as Container, [], sections);
796
+ // global.dropdowns sits outside the primary pattern, but its pages
797
+ // still need routes generated for them - walk each entry too, with an
798
+ // empty path (they don't participate in the tabs/version/etc.
799
+ // selector chain, only in the always-visible globalDropdowns list).
800
+ for (const dropdown of navigation.global?.dropdowns ?? []) {
801
+ walkSections(dropdown, [], sections);
802
+ }
803
+ return sections;
804
+ }
805
+
806
+ // --- An item's own page ------------------------------------------------
807
+ //
808
+ // A tab, version, language, dropdown or product can have a `page`: choosing
809
+ // the item opens it (firstSlugOf() above). How such a page is shown when no
810
+ // sidebar lists it - inside its item - is lib/item-pages.js; the route is
811
+ // landingRoutes in [...slug].astro.
812
+
813
+ export interface Landing {
814
+ /** The page's id. */
815
+ slug: string;
816
+ /** The levels down to the item, the item last. */
817
+ path: PathSegment[];
818
+ /** The item's own sidebar - empty when it holds tabs, products, ... */
819
+ pages: NavItem[];
820
+ item: NamedContainer;
821
+ }
822
+
823
+ export function resolveLandings(navigation: NavigationConfig): Landing[] {
824
+ return resolveLandingsJs(navigation) as Landing[];
825
+ }
826
+
827
+ /** The selectors for an item's own page shown inside the item: the levels
828
+ * down to the item, as for any page, plus the item's own options with none
829
+ * chosen - the switcher shows the item's name until the reader picks one
830
+ * (`placeholder`, currentOption() in lib/selector-placement.js). */
831
+ export function landingSelectors(landing: Landing, hrefForSlug: (slug: string) => string): Selector[] {
832
+ const selectors = buildSelectors(landing.path, hrefForSlug, -1, true);
833
+ const level = childLevel(landing.item) as { kind: PathSegment['kind']; items: NamedContainer[] } | null;
834
+ if (!level) return selectors;
835
+ selectors.push({
836
+ kind: level.kind,
837
+ placeholder: {
838
+ label: labelOf(landing.item),
839
+ icon: iconOf(landing.item),
840
+ description: 'description' in landing.item ? landing.item.description : undefined,
841
+ },
842
+ options: level.items.flatMap((child) => {
843
+ if (isHidden(child)) return [];
844
+ return {
845
+ label: labelOf(child),
846
+ icon: iconOf(child),
847
+ tag: 'tag' in child ? child.tag : undefined,
848
+ description: 'description' in child ? child.description : undefined,
849
+ href: 'href' in child ? child.href : hrefForSlug(firstSlugOf(child as Container) ?? 'index'),
850
+ active: false,
851
+ dropdown: dropdownMenuOf(child as Container, hrefForSlug),
852
+ };
853
+ }),
854
+ });
855
+ return selectors;
856
+ }
857
+
858
+ /** Which Section (by index into resolveSections()'s result) a page belongs to. */
859
+ export function findSectionIndexForSlug(sections: Section[], slug: string): number {
860
+ const index = sections.findIndex((s) => flattenNav(s.pages).some((entry) => entry.slug === slug));
861
+ return index === -1 ? 0 : index;
862
+ }
863
+
864
+ /** The always-visible topbar dropdown list - independent of whichever
865
+ * primary pattern/section is active (Mintlify's equivalent is
866
+ * `navigation.global.anchors`). */
867
+ export function resolveGlobalDropdowns(navigation: NavigationConfig): DropdownItem[] {
868
+ if (Array.isArray(navigation)) return [];
869
+ return navigation.global?.dropdowns ?? [];
870
+ }
871
+
872
+ /** The first real page slug reachable by descending into a container's
873
+ * content, however deep - used to compute where a selector option (a
874
+ * tab, a version, ...) navigates to when chosen. Null for an external
875
+ * `href` leaf, which the caller renders as a plain link using the
876
+ * node's own href instead. Versions prefer whichever entry is marked
877
+ * `default` (falling back to the first), matching Mintlify's version
878
+ * default rule. */
879
+ /** Tries `firstSlugOf()` against each item in order, returning the first
880
+ * non-null result - a plain `items[0]` pick (the previous behavior)
881
+ * breaks the moment that first sibling happens to be a bare `href` leaf
882
+ * (returns null, with nothing that tries the next one), which is a real
883
+ * case now that any container - not just a nested dropdown - can be a
884
+ * bare external link (e.g. a `tabs` array whose first entry is
885
+ * `{ tab: "Status", href: "..." }`). */
886
+ function firstSlugAmong(items: Container[]): string | null {
887
+ for (const item of items) {
888
+ // A hidden item is reached only by its address - never by default.
889
+ if (isHidden(item)) continue;
890
+ const slug = firstSlugOf(item);
891
+ if (slug !== null) return slug;
892
+ }
893
+ return null;
894
+ }
895
+
896
+ export function firstSlugOf(node: Container): string | null {
897
+ // An item with a `page` of its own opens there (lib/item-pages.js).
898
+ const own = itemPage(node);
899
+ if (own !== null) return own;
900
+ if ('pages' in node) return flattenNav(node.pages)[0]?.slug ?? null;
901
+ if ('href' in node) return null;
902
+ if ('tabs' in node) return firstSlugAmong(node.tabs);
903
+ if ('versions' in node) {
904
+ // Try the `default`-tagged version(s) first (matching the old
905
+ // "preferred" pick), then fall through to the rest in order - same
906
+ // href-leaf-with-no-fallback concern as `tabs` above, just with an
907
+ // extra preference pass in front of it.
908
+ const defaults = node.versions.filter((v) => v.default);
909
+ const rest = node.versions.filter((v) => !v.default);
910
+ return firstSlugAmong([...defaults, ...rest]);
911
+ }
912
+ if ('languages' in node) return firstSlugAmong(node.languages);
913
+ if ('dropdowns' in node) return firstSlugAmong(node.dropdowns);
914
+ if ('products' in node) return firstSlugAmong(node.products);
915
+ return null;
916
+ }
917
+
918
+ /** For a version/language switcher, finds where the reader's current
919
+ * page would live inside a *different* version/language's own subtree,
920
+ * so switching keeps them on the same conceptual page instead of always
921
+ * bouncing to that option's first page (see buildSelectors() below,
922
+ * which is the only caller). "Same page" is approximated positionally
923
+ * rather than by name, since nothing guarantees a version/language's
924
+ * own identifier lines up with its pages' file paths - a version
925
+ * tagged "2025-09" could just as easily keep its pages under a "v1"
926
+ * folder with no relation to that string, so there's no naming
927
+ * convention to key off safely; this heuristic only ever compares tree
928
+ * position, never path text. (docs.json-examples/00-kitchen-sink/'s own
929
+ * versions - "2025-09"/"2026-01" under Core Platform - happen to have
930
+ * folder names that line up with their version strings, so it doesn't
931
+ * demonstrate the mismatched-folder-name case directly; the guarantee
932
+ * still doesn't exist regardless of what one fixture happens to do.)
933
+ *
934
+ * Two things have to line up for a page to count as "the same" one:
935
+ * first, `remainingPath` (whatever tab/product/dropdown was chosen
936
+ * *below* the version/language being switched, on the reader's actual
937
+ * page) has to exist at the same index in `item`'s own subtree too -
938
+ * an option isn't guaranteed to nest the same way that many levels
939
+ * down (a version could add/remove a tab), so any mismatch here bails
940
+ * out to null immediately rather than guessing. Second, once both
941
+ * bottom out at a leaf `pages` list, `position` (the reader's own page
942
+ * index within *its* pages list) has to exist in `item`'s pages list
943
+ * too - two versions/languages of the same docs are usually authored
944
+ * with matching page order even when the file paths differ, so this
945
+ * is a reasonable proxy for "the same page" without relying on names.
946
+ *
947
+ * Returns null - meaning "no equivalent page, fall back to
948
+ * firstSlugOf()" - on any structural mismatch or an out-of-range
949
+ * position, rather than guessing at a wrong page. */
950
+ export function equivalentPageIn(
951
+ item: Container,
952
+ remainingPath: PathSegment[],
953
+ position: number
954
+ ): string | null {
955
+ if ('pages' in item) return flattenNav(item.pages)[position]?.slug ?? null;
956
+ if ('href' in item) return null;
957
+ const [next, ...rest] = remainingPath;
958
+ if (!next) return null; // the reader's own page didn't go this deep - no basis to pick a branch
959
+ if ('tabs' in item && next.kind === 'tab') {
960
+ const target = item.tabs[next.index];
961
+ return target ? equivalentPageIn(target, rest, position) : null;
962
+ }
963
+ if ('versions' in item && next.kind === 'version') {
964
+ const target = item.versions[next.index];
965
+ return target ? equivalentPageIn(target, rest, position) : null;
966
+ }
967
+ if ('languages' in item && next.kind === 'language') {
968
+ const target = item.languages[next.index];
969
+ return target ? equivalentPageIn(target, rest, position) : null;
970
+ }
971
+ if ('dropdowns' in item && next.kind === 'dropdown') {
972
+ const target = item.dropdowns[next.index];
973
+ return target ? equivalentPageIn(target, rest, position) : null;
974
+ }
975
+ if ('products' in item && next.kind === 'product') {
976
+ const target = item.products[next.index];
977
+ return target ? equivalentPageIn(target, rest, position) : null;
978
+ }
979
+ return null; // structural mismatch - this option nests differently at this depth
980
+ }
981
+
982
+ /** The first real page slug in the whole site, root navigation pattern
983
+ * included - used to redirect `/` somewhere sensible when nothing in
984
+ * the navigation happens to be a page literally named "index" (the
985
+ * usual "docs/index.mdx is the homepage" convention). Mirrors
986
+ * firstSlugOf()'s per-container descent, plus the flat-array root case
987
+ * firstSlugOf() alone can't handle since a bare array isn't a Container. */
988
+ export function firstSlugOfNavigation(navigation: NavigationConfig): string | null {
989
+ if (Array.isArray(navigation)) return flattenNav(navigation)[0]?.slug ?? null;
990
+ return firstSlugOf(navigation as Container);
991
+ }
992
+
993
+ /** Whether `slug` is reachable anywhere underneath a container, however
994
+ * deep - used for computing active state on nodes that aren't part of
995
+ * the active Section's own `path` (global dropdown entries). */
996
+ export function containerContainsSlug(node: Container, slug: string): boolean {
997
+ if ('pages' in node) return flattenNav(node.pages).some((entry) => entry.slug === slug);
998
+ if ('href' in node) return false;
999
+ if ('tabs' in node) return node.tabs.some((t) => containerContainsSlug(t, slug));
1000
+ if ('versions' in node) return node.versions.some((v) => containerContainsSlug(v, slug));
1001
+ if ('languages' in node) return node.languages.some((l) => containerContainsSlug(l, slug));
1002
+ if ('dropdowns' in node) return node.dropdowns.some((d) => containerContainsSlug(d, slug));
1003
+ if ('products' in node) return node.products.some((p) => containerContainsSlug(p, slug));
1004
+ return false;
1005
+ }
1006
+
1007
+ function labelOf(item: NamedContainer): string {
1008
+ if ('tab' in item) return item.tab;
1009
+ if ('version' in item) return item.label ?? item.version;
1010
+ if ('language' in item) return item.label ?? item.language;
1011
+ if ('dropdown' in item) return item.dropdown;
1012
+ return item.product;
1013
+ }
1014
+
1015
+ function iconOf(item: NamedContainer): string | undefined {
1016
+ return (item as { icon?: string }).icon;
1017
+ }
1018
+
1019
+ // --- Topbar selectors -------------------------------------------------
1020
+ //
1021
+ // One Selector per PathSegment on the active Section's path. Tabs render
1022
+ // as the horizontal pill bar (all options always visible, exactly one
1023
+ // current); versions/languages/products, and dropdowns used as a nested
1024
+ // path segment, render as a single switcher control instead - the
1025
+ // trigger shows the *current* option, its menu lists the alternatives.
1026
+ // See BaseLayout.astro for the actual markup per kind.
1027
+
1028
+ export interface SelectorOption {
1029
+ label: string;
1030
+ icon?: string;
1031
+ tag?: string;
1032
+ // A product's `description` - shown under its name where there's room
1033
+ // (the sidebar's product switcher, see lib/selector-placement.js).
1034
+ description?: string;
1035
+ href: string;
1036
+ active: boolean;
1037
+ // Set when this option's own container is a `dropdowns` list (e.g. a
1038
+ // tab whose content is `dropdowns` instead of `pages`) - the tab pill
1039
+ // itself becomes a dropdown-trigger showing these as its menu, rather
1040
+ // than a separate dropdown control rendered alongside it.
1041
+ dropdown?: SelectorOption[];
1042
+ // On an entry of that menu holding dropdowns of its own: those, shown in a
1043
+ // flyout beside the entry (TopBar.astro). A tab's menu goes two levels deep
1044
+ // at most (MAX_TAB_MENU_LEVELS in config-schema.ts), so a flyout's entries
1045
+ // have none.
1046
+ submenu?: SelectorOption[];
1047
+ // On an entry with a `submenu`: the entry's own `page`, if it has one -
1048
+ // clicking the entry opens it. Without one, clicking opens the flyout.
1049
+ pageHref?: string;
1050
+ }
1051
+
1052
+ export interface Selector {
1053
+ kind: PathSegment['kind'];
1054
+ options: SelectorOption[];
1055
+ // The page sits inside a hidden item on this level: the level isn't
1056
+ // shown (its switcher would list the other items). Kept in the list,
1057
+ // not dropped, so the levels after it are placed by their real parent
1058
+ // (lib/selector-placement.js).
1059
+ hidden?: boolean;
1060
+ // No option is chosen on this level - the page is an item's own page,
1061
+ // shown above its options (landingSelectors()). A switcher shows this
1062
+ // instead of a current option (currentOption() in lib/selector-placement.js).
1063
+ placeholder?: { label: string; icon?: string; description?: string };
1064
+ }
1065
+
1066
+ /** An option's own `dropdowns` menu, if it has one (see SelectorOption.dropdown
1067
+ * above), with a `submenu` on each entry that holds dropdowns of its own.
1068
+ * `activePath` is the path *below* this option's own segment, only passed
1069
+ * when this option is the active one on its level, so a sibling option that
1070
+ * also happens to own `dropdowns` doesn't spuriously mark one of its entries
1071
+ * active just because some *other* option is currently selected. */
1072
+ function dropdownMenuOf(
1073
+ node: NavChildren,
1074
+ hrefForSlug: (slug: string) => string,
1075
+ activePath: PathSegment[] = [],
1076
+ depth = 1
1077
+ ): SelectorOption[] | undefined {
1078
+ if (!('dropdowns' in node)) return undefined;
1079
+ const [segment, ...below] = activePath;
1080
+ return node.dropdowns.flatMap((d, i): SelectorOption[] => {
1081
+ if (isHidden(d)) return [];
1082
+ const active = segment?.kind === 'dropdown' && segment.index === i;
1083
+ const option: SelectorOption = {
1084
+ label: d.dropdown,
1085
+ icon: iconOf(d),
1086
+ href: 'href' in d ? d.href : hrefForSlug(firstSlugOf(d) ?? 'index'),
1087
+ active,
1088
+ };
1089
+ if (depth === 1 && 'dropdowns' in d) {
1090
+ const submenu = dropdownMenuOf(d, hrefForSlug, active ? below : [], depth + 1);
1091
+ if (submenu && submenu.length > 0) {
1092
+ option.submenu = submenu;
1093
+ const own = itemPage(d);
1094
+ if (own !== null) option.pageHref = hrefForSlug(own);
1095
+ }
1096
+ }
1097
+ return [option];
1098
+ });
1099
+ }
1100
+
1101
+ /** `activePagePosition` is the reader's current page's own index within
1102
+ * its Section's flattened pages list (-1 if it can't be found there,
1103
+ * which just disables the position-preserving behavior below) - see
1104
+ * [...slug].astro for how it's computed. Only version/language
1105
+ * switchers try to preserve position across options; tabs/dropdowns/
1106
+ * products keep linking to firstSlugOf() unconditionally, since those
1107
+ * represent genuinely different content (an "API Reference" tab isn't
1108
+ * "the same page" as a "Guides" tab just because they're both first),
1109
+ * unlike a version/language of what's meant to be the same docs. */
1110
+ export function buildSelectors(
1111
+ path: PathSegment[],
1112
+ hrefForSlug: (slug: string) => string,
1113
+ activePagePosition: number = -1,
1114
+ // The page is an item's own page (landingSelectors()): a version or
1115
+ // language switch goes to the same item in the other option - where
1116
+ // choosing that item goes, its own page or its first page.
1117
+ landing = false
1118
+ ): Selector[] {
1119
+ return path.map((segment, segIndex): Selector => {
1120
+ const preservesPosition =
1121
+ (segment.kind === 'version' || segment.kind === 'language') && (activePagePosition >= 0 || landing);
1122
+ const remainingPath = path.slice(segIndex + 1);
1123
+ return {
1124
+ kind: segment.kind,
1125
+ hidden: isHidden(segment.items[segment.index]),
1126
+ options: (segment.items as NamedContainer[]).flatMap((item, i) => {
1127
+ // A hidden item is never offered - not even to its own pages.
1128
+ if (isHidden(item)) return [];
1129
+ const isActive = i === segment.index;
1130
+ const sameItem = preservesPosition && landing ? equivalentItem(item, remainingPath) : null;
1131
+ const equivalentSlug = !preservesPosition
1132
+ ? null
1133
+ : landing
1134
+ ? sameItem && firstSlugOf(sameItem as Container)
1135
+ : equivalentPageIn(item as Container, remainingPath, activePagePosition);
1136
+ const targetSlug = equivalentSlug ?? firstSlugOf(item as Container) ?? 'index';
1137
+ return {
1138
+ label: labelOf(item),
1139
+ icon: iconOf(item),
1140
+ tag: 'tag' in item ? item.tag : undefined,
1141
+ description: 'description' in item ? item.description : undefined,
1142
+ href: 'href' in item ? item.href : hrefForSlug(targetSlug),
1143
+ active: isActive,
1144
+ dropdown: dropdownMenuOf(item, hrefForSlug, isActive ? path.slice(segIndex + 1) : []),
1145
+ };
1146
+ }),
1147
+ };
1148
+ });
1149
+ }
1150
+
1151
+ // --- Global dropdowns ---------------------------------------------------
1152
+ //
1153
+ // Unlike path-segment selectors, global dropdowns aren't a mutually
1154
+ // exclusive "pick one" choice - `global.dropdowns` is an array where
1155
+ // *every* entry renders as its own always-visible trigger button
1156
+ // simultaneously (Mintlify's anchors work the same way). A trigger's
1157
+ // menu lists its own direct pages as quick links; a bare-href entry is
1158
+ // just a plain link with no menu; a deeply-nested entry (tabs/versions/
1159
+ // etc. instead of direct pages) falls back to linking straight to its
1160
+ // first page, since building a rich flyout for that combination isn't
1161
+ // worth the complexity for what's meant to be a quick-links affordance.
1162
+
1163
+ export interface GlobalDropdownView {
1164
+ label: string;
1165
+ icon?: string;
1166
+ href: string | null;
1167
+ items: SelectorOption[];
1168
+ }
1169
+
1170
+ export function buildGlobalDropdowns(
1171
+ dropdowns: DropdownItem[],
1172
+ currentSlug: string,
1173
+ titleForSlug: (slug: string) => string,
1174
+ hrefForSlug: (slug: string) => string,
1175
+ metaForSlug?: (slug: string) => NavPageMeta | undefined
1176
+ ): GlobalDropdownView[] {
1177
+ return dropdowns.map((d): GlobalDropdownView => {
1178
+ if ('href' in d) {
1179
+ return { label: d.dropdown, icon: d.icon, href: d.href, items: [] };
1180
+ }
1181
+ if ('pages' in d) {
1182
+ // Same `hidden`/`url` handling as buildNavTree().
1183
+ const items = flattenNav(d.pages)
1184
+ .filter((entry) => !metaForSlug?.(entry.slug)?.hidden)
1185
+ .map((entry) => ({
1186
+ label: titleForSlug(entry.slug),
1187
+ href: metaForSlug?.(entry.slug)?.url ?? hrefForSlug(entry.slug),
1188
+ active: entry.slug === currentSlug,
1189
+ }));
1190
+ return { label: d.dropdown, icon: d.icon, href: null, items };
1191
+ }
1192
+ const slug = firstSlugOf(d);
1193
+ return { label: d.dropdown, icon: d.icon, href: slug ? hrefForSlug(slug) : '#', items: [] };
1194
+ });
1195
+ }
1196
+
1197
+ // --- Sidebar (recursive) -------------------------------------------------
1198
+
1199
+ // A group node's `pageSlug` is the page its own label links to (null if
1200
+ // it's a pure disclosure/label with no page of its own - the group only
1201
+ // groups). NavTree.astro renders depth-0 groups as static, non-collapsible
1202
+ // section titles (linked if `pageSlug` is set, plain text otherwise) and
1203
+ // every deeper group as a collapsible row styled like a page item, with a
1204
+ // chevron, defaulting open when it contains the active page - see
1205
+ // navTreeContainsSlug() below.
1206
+ export type NavTreeNode =
1207
+ | {
1208
+ kind: 'page';
1209
+ slug: string;
1210
+ title: string;
1211
+ method: string | null;
1212
+ icon?: string;
1213
+ tag?: string;
1214
+ deprecated?: boolean;
1215
+ // A draft page (`draft: true`): only in `writedocs dev` and `build
1216
+ // --drafts` - the build takes it out of the navigation (lib/drafts.js).
1217
+ draft?: boolean;
1218
+ }
1219
+ | { kind: 'group'; label: string; pageSlug: string | null; children: NavTreeNode[] }
1220
+ | { kind: 'link'; label: string; href: string };
1221
+
1222
+ /** Builds the sidebar's view model, preserving group nesting depth.
1223
+ * `methodForSlug` is optional (most sites have no OpenAPI pages at all)
1224
+ * and, when given, returns the HTTP method to badge a page with in the
1225
+ * sidebar (e.g. "GET") or null for an ordinary page - see
1226
+ * NavTree.astro for how that badge renders. */
1227
+ /** Per-page frontmatter that changes how a page shows up in navigation -
1228
+ * Mintlify's `hidden`, `url`, `icon`, `tag` and `deprecated`, and `draft`
1229
+ * (see content.config.ts's docsSchema). */
1230
+ export interface NavPageMeta {
1231
+ hidden?: boolean;
1232
+ url?: string;
1233
+ icon?: string;
1234
+ tag?: string;
1235
+ deprecated?: boolean;
1236
+ draft?: boolean;
1237
+ }
1238
+
1239
+ export function buildNavTree(
1240
+ navigation: NavItem[],
1241
+ titleForSlug: (slug: string) => string,
1242
+ methodForSlug?: (slug: string) => string | null,
1243
+ metaForSlug?: (slug: string) => NavPageMeta | undefined
1244
+ ): NavTreeNode[] {
1245
+ return navigation.flatMap((item): NavTreeNode[] => {
1246
+ if (typeof item === 'string') {
1247
+ const meta = metaForSlug?.(item);
1248
+ // A `hidden` page keeps its route but gets no sidebar entry.
1249
+ if (meta?.hidden) return [];
1250
+ // A `url` page is an external link in the sidebar, not a page.
1251
+ if (meta?.url) return [{ kind: 'link', label: titleForSlug(item), href: meta.url }];
1252
+ return [
1253
+ {
1254
+ kind: 'page',
1255
+ slug: item,
1256
+ title: titleForSlug(item),
1257
+ method: methodForSlug?.(item) ?? null,
1258
+ icon: meta?.icon,
1259
+ tag: meta?.tag,
1260
+ deprecated: meta?.deprecated,
1261
+ // Only on a draft, so every other page's node is as it was.
1262
+ ...(meta?.draft ? { draft: true } : {}),
1263
+ },
1264
+ ];
1265
+ }
1266
+ if ('href' in item) {
1267
+ return [{ kind: 'link', label: item.label, href: item.href }];
1268
+ }
1269
+ // loadDocsConfig() always expands `{ group, openapi }` shorthand into
1270
+ // a real `{ group, pages }` before anything reaches here (see
1271
+ // expandOpenApiInNavigation() in the OpenAPI section above) - this is
1272
+ // just a defensive no-op for the shouldn't-happen case of an
1273
+ // unexpanded node reaching the sidebar builder.
1274
+ if ('openapi' in item) {
1275
+ return [{ kind: 'group', label: item.group, pageSlug: null, children: [] }];
1276
+ }
1277
+ return [
1278
+ {
1279
+ kind: 'group',
1280
+ label: item.group,
1281
+ pageSlug: item.page ?? null,
1282
+ children: buildNavTree(item.pages, titleForSlug, methodForSlug, metaForSlug),
1283
+ },
1284
+ ];
1285
+ });
1286
+ }
1287
+
1288
+ /** Whether `slug` is the group's own attached page, or belongs to any page/group nested inside it. */
1289
+ export function navTreeContainsSlug(nodes: NavTreeNode[], slug: string): boolean {
1290
+ return nodes.some((node) => {
1291
+ if (node.kind === 'page') return node.slug === slug;
1292
+ if (node.kind === 'link') return false;
1293
+ return node.pageSlug === slug || navTreeContainsSlug(node.children, slug);
1294
+ });
1295
+ }
1296
+
1297
+ export interface BreadcrumbCrumb {
1298
+ label: string;
1299
+ href: string | null;
1300
+ }
1301
+
1302
+ /** The chain of ancestor group labels (root first) that `slug` is nested
1303
+ * under within `nodes` - empty when the page sits at the top level of its
1304
+ * Section with no enclosing group at all, in which case the caller should
1305
+ * skip rendering breadcrumbs entirely (there'd be nothing to show but the
1306
+ * fixed home icon Breadcrumbs.astro always renders first).
1307
+ *
1308
+ * Deliberately never includes the current page itself - only the groups
1309
+ * it's nested under (that's already the <h1> right below, repeating it
1310
+ * in the breadcrumb trail would just be noise). A group whose own
1311
+ * attached page (`pageSlug`, see NavTreeNode) *is* `slug` is excluded
1312
+ * from its own trail for the same reason - you're looking at that page,
1313
+ * it doesn't need to also list itself as its own ancestor. A group only
1314
+ * appears here when `slug` is nested *inside* it (its own page, if any,
1315
+ * links to that group's landing page - `href: null` for a label-only
1316
+ * group with no page of its own to link to). */
1317
+ export function ancestorGroupsForSlug(
1318
+ nodes: NavTreeNode[],
1319
+ slug: string,
1320
+ hrefForSlug: (slug: string) => string
1321
+ ): BreadcrumbCrumb[] {
1322
+ for (const node of nodes) {
1323
+ if (node.kind !== 'group') continue;
1324
+ if (node.pageSlug === slug) return [];
1325
+ if (navTreeContainsSlug(node.children, slug)) {
1326
+ const crumb: BreadcrumbCrumb = { label: node.label, href: node.pageSlug ? hrefForSlug(node.pageSlug) : null };
1327
+ return [crumb, ...ancestorGroupsForSlug(node.children, slug, hrefForSlug)];
1328
+ }
1329
+ }
1330
+ return [];
1331
+ }