@writedocs/generator 0.10.20 → 0.11.1

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