@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
@@ -1,1597 +1,1604 @@
1
- ---
2
- import { getCollection, render, type CollectionEntry } from "astro:content";
3
- import fs from "node:fs";
4
- import path from "node:path";
5
- import {
6
- loadDocsConfig,
7
- resolveSections,
8
- resolveGlobalDropdowns,
9
- findSectionIndexForSlug,
10
- buildNavTree,
11
- ancestorGroupsForSlug,
12
- buildSelectors,
13
- buildGlobalDropdowns,
14
- fileIdForEntry,
15
- normalizeEntryId,
16
- flattenNav,
17
- firstSlugOfNavigation,
18
- mergeSeo,
19
- contextMenuOptions,
20
- resolveSiteUrl,
21
- findAllPages,
22
- resolveLandings,
23
- landingSelectors,
24
- } from "../lib/config";
25
- import { writedocsTempDir } from "../lib/writedocs-temp-dir.js";
26
- import { parseOpenApiRef } from "../lib/openapi-ref.js";
27
- import { languageAlternates } from "../lib/item-pages.js";
28
- import { wantsGeneratedCard, ogImagePath } from "../lib/og-image.js";
29
- import BaseLayout from "../layout/BaseLayout.astro";
30
- import Sidebar from "../layout/components/Sidebar.astro";
31
- import TableOfContents from "../layout/components/TableOfContents.astro";
32
- import Breadcrumbs from "../layout/components/Breadcrumbs.astro";
33
- import CopyPageMenu from "../components/CopyPageMenu.astro";
34
- import Callout from "../components/Callout.astro";
35
- import Note from "../components/Note.astro";
36
- import Info from "../components/Info.astro";
37
- import Tip from "../components/Tip.astro";
38
- import Warning from "../components/Warning.astro";
39
- import Danger from "../components/Danger.astro";
40
- import Card from "../components/Card.astro";
41
- import CardGroup from "../components/CardGroup.astro";
42
- import Tabs from "../components/Tabs.astro";
43
- import Tab from "../components/Tab.astro";
44
- import CodeGroup from "../components/CodeGroup.astro";
45
- import Accordion from "../components/Accordion.astro";
46
- import AccordionGroup from "../components/AccordionGroup.astro";
47
- import Steps from "../components/Steps.astro";
48
- import Step from "../components/Step.astro";
49
- import Hint from "../components/Hint.astro";
50
- import Image from "../components/Image.astro";
51
- import Frame from "../components/Frame.astro";
52
- import Video from "../components/Video.astro";
53
- import Parameter from "../components/Parameter.astro";
54
- import Expandable from "../components/Expandable.astro";
55
- import Searchbar from "../components/Searchbar.astro";
56
- import Badge from "../components/Badge.astro";
57
- import Icon from "../components/Icon.astro";
58
- import RequestExample from "../components/RequestExample.astro";
59
- import ResponseExample from "../components/ResponseExample.astro";
60
- import Check from "../components/Check.astro";
61
- import ParamField from "../components/ParamField.astro";
62
- import ResponseField from "../components/ResponseField.astro";
63
- import Columns from "../components/Columns.astro";
64
- import Column from "../components/Column.astro";
65
- import CodeBlock from "../components/CodeBlock.astro";
66
- import Tooltip from "../components/Tooltip.astro";
67
- import Update from "../components/Update.astro";
68
- import Tile from "../components/Tile.astro";
69
- import Panel from "../components/Panel.astro";
70
- import Prompt from "../components/Prompt.astro";
71
- import View from "../components/View.astro";
72
- import Visibility from "../components/Visibility.astro";
73
- import { Tree, FileTree, Color, GitHub } from "../components/compound";
74
- import ApiPlayground from "../components/ApiPlayground.astro";
75
- import ApiReferencePanel from "../components/ApiReferencePanel.astro";
76
- import { searchScope, sectionTrail, ALL_SCOPES } from "../lib/search-scope.js";
77
- import { selectorPlacements } from "../lib/selector-placement.js";
78
- import { spaceOf } from "../lib/hidden-sections.js";
79
- import { navigationPageOrder } from "../lib/pages.js";
80
- import { folderRedirects } from "../lib/folder-redirects.js";
81
- import { oncePerBuild } from "../lib/build-memo.js";
82
-
83
- // A page is hand-written (the `pages` collection, sourced from anywhere
84
- // in the project - docs/ has no special status, see findAllPages() in
85
- // lib/config.ts) or an auto-generated OpenAPI stub (the `generatedDocs`
86
- // collection, sourced from writedocsTempDir()'s generated-docs/
87
- // directory - see content.config.ts / generate-api-pages.js) - kept as two separate
88
- // collections rather than one, since Astro's loader API has no supported
89
- // way to point a single collection's glob() at more than one base
90
- // directory without one's own cleanup pass deleting the other's entries
91
- // (see content.config.ts's own comment on this). Both share the exact
92
- // same schema, so every consumer below just treats them as one combined
93
- // list.
94
- //
95
- // The two `getCollection()` calls below are inlined at each of their two
96
- // call sites (getStaticPaths, and the component body further down)
97
- // rather than factored into one shared top-level helper: Astro's
98
- // getStaticPaths extraction (a separate bundling pass from the rest of
99
- // the component - see the pathDescription comment further down for
100
- // another instance of this) was observed to silently drop a top-level
101
- // function declaration referenced from inside getStaticPaths, producing
102
- // a raw "getAllDocsEntries is not defined" ReferenceError at build time
103
- // instead of ever running. Keeping both call sites self-contained avoids
104
- // relying on whatever static-analysis pass decides what counts as
105
- // "used" by the extracted chunk.
106
- //
107
- // Each site also only calls getCollection('generatedDocs') when there's
108
- // actually something in it (most sites have no OpenAPI groups - see
109
- // generate-api-pages.js), rather than unconditionally calling it and
110
- // letting content.config.ts's skipIfMissing() loader no-op internally:
111
- // astro:content's own getCollection() logs "The collection ... does not
112
- // exist or is empty" to the console whenever a collection ends up with
113
- // zero registered entries, regardless of *why* it's empty - the data
114
- // store has no supported way to mark a collection as "intentionally
115
- // empty" short of writing at least one entry to it. Not calling
116
- // getCollection() at all for an empty one sidesteps that warning at the
117
- // source instead of trying to suppress it after the fact.
118
- type DocsEntry = CollectionEntry<"pages"> | CollectionEntry<"generatedDocs">;
119
-
120
- export async function getStaticPaths() {
121
- const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
122
- const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
123
- const config = loadDocsConfig(contentDir);
124
- const sections = resolveSections(config.navigation);
125
- const hasGeneratedDocs = fs.existsSync(path.join(writedocsTempDir(contentDir), "generated-docs"));
126
- const hasPages = findAllPages(contentDir).length > 0;
127
- const [pagesEntries, generatedDocsEntries] = await Promise.all([
128
- hasPages ? getCollection("pages") : Promise.resolve([]),
129
- hasGeneratedDocs ? getCollection("generatedDocs") : Promise.resolve([]),
130
- ]);
131
- const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
132
- // writedocs.json always references a page by its file id; `entry.id` is
133
- // Astro's own resolved slug for it (the file-path default, or a
134
- // frontmatter `slug` override it recognizes natively - see
135
- // fileIdForEntry() in lib/config.ts) and is what the page is actually
136
- // routed at. Keyed by file id so every navEntry.slug below finds its
137
- // entry regardless of which one is in play.
138
- const entryByFileId = new Map(entries.map((e) => [fileIdForEntry(contentDir, packageRoot, e), e]));
139
-
140
- // "/" is only produced below when some page's *resolved* slug
141
- // (entry.id) is literally "index" - the conventional home page (an
142
- // index.mdx at the project root; a root-level index.mdx keeps file id
143
- // "index" verbatim, since Astro's own default id computation only
144
- // strips a trailing `/index` *segment*, which a single-segment root
145
- // file doesn't have - see fileIdForEntry()'s own comment on this in
146
- // lib/config.ts), or any page overriding its own slug to "index"/"/".
147
- // Most navigations don't have such a page - Astro then warns "no
148
- // matching static path was found for /" on every request. Rather than
149
- // requiring every writedocs.json to name a page "index", synthesize a
150
- // redirect-only route for "/" pointing at the site's first real page
151
- // whenever nothing already claims root.
152
- // Checked against every entry, not just nav-referenced ones - a hidden
153
- // page (see hiddenRoutes below) sitting at "index" claims root exactly
154
- // as well as a nav-listed one would, and needs to suppress the synthetic
155
- // redirect below the same way (two routes both wanting `params.slug:
156
- // undefined` is a build error, not a silent pick-one).
157
- const rootAlreadyClaimed = entries.some((e) => normalizeEntryId(e.id) === "index");
158
- const firstSlug = rootAlreadyClaimed ? null : firstSlugOfNavigation(config.navigation);
159
- const firstEntry = firstSlug ? entryByFileId.get(firstSlug) : undefined;
160
- // Not calling the top-level hrefForSlug() here: it's only otherwise
161
- // referenced from the component body, not from inside getStaticPaths,
162
- // and per the describeSectionPath lesson above, closures introduced
163
- // into getStaticPaths should be self-contained rather than assume a
164
- // module-level binding survives Astro's bundling extraction. firstEntry
165
- // can never resolve to "index" here (that's exactly what
166
- // rootAlreadyClaimed rules out), so the ternary below always resolves
167
- // to the non-root branch.
168
- const rootRedirect = firstEntry
169
- ? [{ params: { slug: undefined }, props: { redirectTo: `/${normalizeEntryId(firstEntry.id)}/`, temporary: true } }]
170
- : [];
171
-
172
- // Tracks every file id a nav-driven route below already claims, so
173
- // hiddenRoutes (further down) knows which entries are left over - any
174
- // page/generatedDocs entry that exists (findAllPages() already required
175
- // it to have frontmatter with a `title` - see content.config.ts's
176
- // docsSchema) but isn't reachable by walking writedocs.json's navigation at
177
- // all. Those still get routed here, just without a nav-derived
178
- // prev/next or section - a page doesn't have to be in the sidebar to be
179
- // a real, directly-linkable page (an in-progress draft, an unlisted
180
- // landing page, etc.).
181
- const claimedFileIds = new Set<string>();
182
-
183
- const pageRoutes = sections.flatMap((section, sectionIndex) => {
184
- const flatNav = flattenNav(section.pages);
185
- // Prev/next skip pages that aren't in the sidebar (frontmatter
186
- // `hidden`) or aren't pages at all (frontmatter `url`, an external
187
- // link) - the reader should land on the next page they could also
188
- // have clicked in the sidebar. Inlined for the same reason as the
189
- // error branch below.
190
- const isPaginationStop = (slug: string) => {
191
- const data = entryByFileId.get(slug)?.data;
192
- return Boolean(data) && !data!.hidden && !data!.url;
193
- };
194
- return flatNav.map((navEntry, i) => {
195
- const entry = entryByFileId.get(navEntry.slug);
196
- if (!entry) {
197
- // Inlined rather than a separate top-level helper: Astro's
198
- // getStaticPaths extraction (a separate bundling pass from the
199
- // rest of the component) was observed to silently drop a
200
- // top-level function declaration that's only referenced inside
201
- // this rarely-taken branch, producing a raw "X is not defined"
202
- // ReferenceError instead of this readable message. Keeping the
203
- // logic inside getStaticPaths' own closure avoids relying on
204
- // whatever static-analysis pass decides what counts as "used".
205
- const pathDescription =
206
- section.path.length === 0
207
- ? "(root)"
208
- : section.path
209
- .map((seg) => {
210
- const item = seg.items[seg.index] as Record<string, unknown>;
211
- const name = (item.tab ?? item.version ?? item.language ?? item.dropdown ?? item.product) as string;
212
- return `${seg.kind} "${name}"`;
213
- })
214
- .join(" > ");
215
- throw new Error(
216
- `[writedocs] writedocs.json references page "${navEntry.slug}"` +
217
- ` (${pathDescription})` +
218
- ` but no matching file was found`,
219
- );
220
- }
221
- claimedFileIds.add(navEntry.slug);
222
- const prev = flatNav.slice(0, i).findLast((e) => isPaginationStop(e.slug)) ?? null;
223
- const next = flatNav.slice(i + 1).find((e) => isPaginationStop(e.slug)) ?? null;
224
- const urlSlug = normalizeEntryId(entry.id);
225
- // A frontmatter `url` page (Mintlify's external link) exists only
226
- // to put that link in the sidebar - its own URL redirects there.
227
- if (entry.data.url) {
228
- return {
229
- params: { slug: urlSlug === "index" ? undefined : urlSlug },
230
- props: { redirectTo: entry.data.url },
231
- };
232
- }
233
- return {
234
- params: { slug: urlSlug === "index" ? undefined : urlSlug },
235
- props: { entry, prev, next, sectionIndex },
236
- };
237
- });
238
- });
239
-
240
- // An item's own page (a tab's, a dropdown's, ... `page` - resolveLandings()
241
- // in lib/config.ts) that no sidebar lists: shown inside its item. One the
242
- // sidebar does list was routed above, in its sidebar. Its Next is the
243
- // item's first sidebar page, if the item has a sidebar of its own.
244
- const landings = resolveLandings(config.navigation);
245
- const landingRoutes = landings.flatMap((landing, landingIndex) => {
246
- if (claimedFileIds.has(landing.slug)) return [];
247
- const entry = entryByFileId.get(landing.slug);
248
- if (!entry) {
249
- const last = landing.path[landing.path.length - 1];
250
- const item = landing.item as Record<string, unknown>;
251
- const name = (item.tab ?? item.version ?? item.language ?? item.dropdown ?? item.product) as string;
252
- throw new Error(
253
- `[writedocs] writedocs.json's ${last.kind} "${name}" names page "${landing.slug}" as its own page,` +
254
- ` but no matching file was found`,
255
- );
256
- }
257
- claimedFileIds.add(landing.slug);
258
- const next =
259
- flattenNav(landing.pages).find((e) => {
260
- const data = entryByFileId.get(e.slug)?.data;
261
- return Boolean(data) && !data!.hidden && !data!.url;
262
- }) ?? null;
263
- const urlSlug = normalizeEntryId(entry.id);
264
- if (entry.data.url) {
265
- return [{ params: { slug: urlSlug === "index" ? undefined : urlSlug }, props: { redirectTo: entry.data.url } }];
266
- }
267
- return [{ params: { slug: urlSlug === "index" ? undefined : urlSlug }, props: { entry, prev: null, next, landingIndex } }];
268
- });
269
-
270
- // "Hidden" pages: any file the `pages`/`generatedDocs` collections
271
- // picked up that writedocs.json's navigation never references (see
272
- // claimedFileIds above) still gets a real route here - just with no
273
- // prev/next (nothing in nav to derive that from) and no section of its
274
- // own to be "active" in. findSectionIndexForSlug's existing "0 if this
275
- // slug isn't in any section" fallback (already used nowhere else in
276
- // this file, but built for exactly this) picks which section's
277
- // sidebar/selectors a hidden page borrows - arbitrary, but no worse
278
- // than the alternative of hidden pages having no chrome at all.
279
- const hiddenRoutes = entries
280
- .filter((entry) => !claimedFileIds.has(fileIdForEntry(contentDir, packageRoot, entry)))
281
- .map((entry) => {
282
- const urlSlug = normalizeEntryId(entry.id);
283
- return {
284
- params: { slug: urlSlug === "index" ? undefined : urlSlug },
285
- props: {
286
- entry,
287
- prev: null,
288
- next: null,
289
- sectionIndex: findSectionIndexForSlug(sections, fileIdForEntry(contentDir, packageRoot, entry)),
290
- isHidden: true,
291
- },
292
- };
293
- });
294
-
295
- // Folder addresses with pages under them but none of their own
296
- // (`/docs/creator/`) redirect to the first page under them
297
- // (lib/folder-redirects.js). Preferred in the reader's order: navigation
298
- // order, public sections before hidden ones, pages outside the
299
- // navigation last.
300
- const slugOf = (route: { params: { slug?: string } }) => route.params.slug ?? "index";
301
- const inHiddenSection = sections.map((section) => spaceOf(section.path) !== null);
302
- const contentRoutes = pageRoutes.filter((route) => !("redirectTo" in route.props));
303
- // An item's own page counts where the navigation names it: before the
304
- // item's sidebar (navigationPageOrder()), so `/guides/` opens the Guides
305
- // tab's own page rather than its first sidebar page.
306
- type ContentRoute = { params: { slug?: string }; props: { entry?: DocsEntry; sectionIndex?: number; landingIndex?: number } };
307
- const navOrder = new Map(navigationPageOrder(config.navigation).map((id, i) => [id, i]));
308
- const orderOf = (route: ContentRoute) => navOrder.get(fileIdForEntry(contentDir, packageRoot, route.props.entry!)) ?? Infinity;
309
- const inHiddenItem = (route: ContentRoute) =>
310
- route.props.landingIndex !== undefined
311
- ? spaceOf(landings[route.props.landingIndex].path) !== null
312
- : inHiddenSection[route.props.sectionIndex!];
313
- const navContent = [...contentRoutes, ...landingRoutes.filter((route) => !("redirectTo" in route.props))] as ContentRoute[];
314
- const folderTargets = [
315
- ...navContent.filter((route) => !inHiddenItem(route)).sort((a, b) => orderOf(a) - orderOf(b)).map(slugOf),
316
- ...navContent.filter(inHiddenItem).sort((a, b) => orderOf(a) - orderOf(b)).map(slugOf),
317
- ...hiddenRoutes.map(slugOf),
318
- ];
319
- const takenAddresses = new Set([
320
- ...[...pageRoutes, ...landingRoutes, ...hiddenRoutes].map(slugOf),
321
- ...(config.redirects ?? []).map((r) => r.source.replace(/^\/+|\/+$/g, "")),
322
- ]);
323
- const folderRoutes = [...folderRedirects(folderTargets, takenAddresses)].map(([folder, target]) => ({
324
- params: { slug: folder },
325
- props: { redirectTo: `/${target}/`, temporary: true },
326
- }));
327
-
328
- return [...rootRedirect, ...pageRoutes, ...landingRoutes, ...hiddenRoutes, ...folderRoutes];
329
- }
330
-
331
- interface Props {
332
- redirectTo?: string;
333
- // The automatic "/" and folder redirects: temporary, see below.
334
- temporary?: boolean;
335
- entry?: DocsEntry;
336
- prev?: { slug: string; group: string | null } | null;
337
- next?: { slug: string; group: string | null } | null;
338
- sectionIndex?: number;
339
- // Set by hiddenRoutes in getStaticPaths above - a page with no place in
340
- // writedocs.json's navigation has no sidebar section of its own to show, so
341
- // its default mode drops the sidebar entirely (see pageMode below)
342
- // rather than borrowing findSectionIndexForSlug's arbitrary fallback
343
- // section's sidebar contents, which would misleadingly suggest the page
344
- // belongs there.
345
- isHidden?: boolean;
346
- // Set by landingRoutes in getStaticPaths above - an item's own page that
347
- // no sidebar lists, shown inside that item (index into resolveLandings()).
348
- landingIndex?: number;
349
- }
350
-
351
- const rawProps = Astro.props as Props;
352
- if (rawProps.redirectTo) {
353
- // The automatic "/" redirect is temporary (302): its target is just the
354
- // navigation's first page, and it goes away once the site has a page at
355
- // "/". A 301 is remembered by the browser for good - after that, "/" kept
356
- // redirecting even with a home page in place, in `writedocs dev` (every
357
- // project's preview shares localhost:4321) and for returning visitors.
358
- // A frontmatter `url` page stays 301. In a static build the status only
359
- // picks the refresh delay of Astro's redirect page, and the build rewrites
360
- // those pages to redirect at once either way (rewrite-redirect-pages.js).
361
- return Astro.redirect(rawProps.redirectTo, rawProps.temporary ? 302 : 301);
362
- }
363
- const {
364
- entry,
365
- prev = null,
366
- next = null,
367
- sectionIndex = 0,
368
- isHidden = false,
369
- landingIndex,
370
- } = rawProps as Required<Props>;
371
-
372
- const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
373
- const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
374
- const config = loadDocsConfig(contentDir);
375
- // Once per build, like the lookup tables further down.
376
- const sections = oncePerBuild("slug:sections", () => resolveSections(config.navigation));
377
- // Falls back to an empty stand-in section rather than crashing on
378
- // `.pages` below - only reachable for a hidden page (see hiddenRoutes in
379
- // getStaticPaths above) on a site whose writedocs.json has no navigation
380
- // sections at all, which previously could never produce a route to
381
- // render in the first place.
382
- // An item's own page shown inside its item (landingRoutes above): the item's
383
- // path, and its own sidebar if it has one.
384
- const landing = landingIndex === undefined ? undefined : oncePerBuild("slug:landings", () => resolveLandings(config.navigation))[landingIndex];
385
- const activeSection = landing ? { pages: landing.pages, path: landing.path } : sections[sectionIndex] ?? { pages: [], path: [] };
386
-
387
- const { Content, headings } = await render(entry);
388
- const tocHeadings = headings.filter((h) => h.depth === 2 || h.depth === 3);
389
-
390
- // The lookup tables below are the same for every page, so a build makes
391
- // them once (oncePerBuild(), lib/build-memo.js) - findAllPages() alone reads
392
- // every page file of the project, and ran here once per page. In
393
- // `writedocs dev` they're made again on every request, as before.
394
- const { titleByFileId, navTitleByFileId, entryByFileId, methodByFileId } = await oncePerBuild("slug:lookups", async () => {
395
- const hasGeneratedDocs = fs.existsSync(path.join(writedocsTempDir(contentDir), "generated-docs"));
396
- const hasPages = findAllPages(contentDir).length > 0;
397
- const [pagesEntries, generatedDocsEntries] = await Promise.all([
398
- hasPages ? getCollection("pages") : Promise.resolve([]),
399
- hasGeneratedDocs ? getCollection("generatedDocs") : Promise.resolve([]),
400
- ]);
401
- const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
402
- // Two maps keyed by file id (not `entry.id` - see fileIdForEntry() in
403
- // lib/config.ts for why those can differ once a page overrides its own
404
- // slug): titles for prev/next and sidebar labels, and the entries
405
- // themselves so hrefForSlug can resolve a writedocs.json file-id reference to
406
- // wherever that page actually got routed.
407
- const titleByFileId = new Map<string, string>();
408
- // Navigation labels (sidebar, topbar dropdowns): a page's `sidebarTitle`
409
- // when it has one - Mintlify's short nav label - else its `title`.
410
- const navTitleByFileId = new Map<string, string>();
411
- const entryByFileId = new Map<string, DocsEntry>();
412
- // The HTTP method badge NavTree.astro shows next to an API operation
413
- // page in the sidebar - read straight off the page's own `openapi:
414
- // "METHOD /path"` frontmatter rather than the resolved operation JSON,
415
- // since the method itself is right there in that string already and
416
- // doesn't need a spec lookup.
417
- const methodByFileId = new Map<string, string>();
418
- for (const e of entries) {
419
- const fileId = fileIdForEntry(contentDir, packageRoot, e);
420
- titleByFileId.set(fileId, e.data.title);
421
- navTitleByFileId.set(fileId, e.data.sidebarTitle ?? e.data.title);
422
- entryByFileId.set(fileId, e);
423
- // `hideApiMarker` (Mintlify's) drops the badge for this one page.
424
- const apiRef = parseOpenApiRef(e.data.openapi);
425
- if (apiRef && !e.data.hideApiMarker) {
426
- methodByFileId.set(fileId, apiRef.method);
427
- }
428
- }
429
- return { titleByFileId, navTitleByFileId, entryByFileId, methodByFileId };
430
- });
431
- const titleForSlug = (slug: string) => titleByFileId.get(slug) ?? slug;
432
- const navTitleForSlug = (slug: string) => navTitleByFileId.get(slug) ?? slug;
433
- const methodForSlug = (slug: string) => methodByFileId.get(slug) ?? null;
434
- // Frontmatter that changes how a page appears in navigation (hidden, url,
435
- // icon, tag, deprecated) - see buildNavTree() in lib/config.ts.
436
- const navMetaForSlug = (slug: string) => entryByFileId.get(slug)?.data;
437
- const hrefForSlug = (slug: string) => {
438
- const raw = entryByFileId.get(slug)?.id ?? slug;
439
- const effective = normalizeEntryId(raw);
440
- return effective === "index" ? "/" : `/${effective}/`;
441
- };
442
- // The current page's own file id (as writedocs.json references it) - distinct
443
- // from `entry.id` (its resolved URL slug) for the same reason as above,
444
- // and what every "is this the active page" comparison below needs, since
445
- // navTree/globalDropdowns are built from writedocs.json's file-id space.
446
- const currentFileId = fileIdForEntry(contentDir, packageRoot, entry);
447
- // A section's tree doesn't depend on which of its pages is open (NavTree.astro
448
- // marks the current one), so it's built once per section in a build.
449
- const navTree = oncePerBuild(`slug:nav:${landingIndex === undefined ? `s${sectionIndex}` : `l${landingIndex}`}`, () => buildNavTree(activeSection.pages, navTitleForSlug, methodForSlug, navMetaForSlug));
450
- // The ancestor sidebar-group trail above the auto <h1> (Breadcrumbs.astro)
451
- // - empty for a page sitting at the top level of its Section with no
452
- // enclosing group, in which case [...slug].astro below skips rendering
453
- // the component entirely rather than showing a breadcrumb bar with
454
- // nothing in it but the page's own title.
455
- const breadcrumbs = ancestorGroupsForSlug(navTree, currentFileId, hrefForSlug);
456
-
457
- // The reader's page's own position within the active Section's flattened
458
- // pages list - passed to buildSelectors() so a version/language switch
459
- // can try to land on the *same* page in the target option instead of
460
- // always its first page (equivalentPageIn() in lib/config.ts). -1 (not
461
- // found) just disables that - firstSlugOf() is still the fallback.
462
- const activePagePosition = flattenNav(activeSection.pages).findIndex((e) => e.slug === currentFileId);
463
-
464
- // One selector per level of the active page's navigation path (tabs,
465
- // versions, languages, products, or a dropdown nested partway down),
466
- // plus the always-visible global dropdown list - see BaseLayout.astro
467
- // for how each renders.
468
- // An item's own page also gets the level under the item, with nothing chosen.
469
- const selectors = landing ? landingSelectors(landing, hrefForSlug) : buildSelectors(activeSection.path, hrefForSlug, activePagePosition);
470
- // <html lang>: the `language` of the navigation level this page sits under,
471
- // if any. A hidden page has no level of its own (activeSection is only a
472
- // fallback for its chrome), so it keeps the default.
473
- // For search: the section line under this page's result (and words it can
474
- // be found by), and the version/language/product it belongs to - search
475
- // shows the reader's own first. A hidden page belongs to no section.
476
- const pageSearchScope = isHidden ? { key: ALL_SCOPES, label: "" } : searchScope(activeSection.path);
477
- const pageSectionTrail = isHidden ? "" : sectionTrail(activeSection.path, breadcrumbs);
478
- // A page under a hidden navigation item searches its own index, not the
479
- // site's (lib/hidden-sections.js, cli/run-pagefind.js).
480
- const pageSearchSpace = isHidden ? null : spaceOf(activeSection.path);
481
- const languageSegment = isHidden ? undefined : activeSection.path.find((segment) => segment.kind === "language");
482
- const pageLang = languageSegment ? (languageSegment.items[languageSegment.index] as { language: string }).language : undefined;
483
- const globalDropdowns = buildGlobalDropdowns(
484
- resolveGlobalDropdowns(config.navigation),
485
- currentFileId,
486
- navTitleForSlug,
487
- hrefForSlug,
488
- navMetaForSlug,
489
- );
490
-
491
- // Meta tags: this page's own frontmatter `seo` overrides writedocs.json's
492
- // site-wide `seo` field by field (mergeSeo() in lib/config.ts), and the
493
- // canonical/OG/Twitter URLs need this page's actual served path - reusing
494
- // hrefForSlug (already built above for prev/next and the sidebar) rather
495
- // than recomputing it, since it already encodes the same
496
- // frontmatter-slug-override-aware routing logic.
497
- const pageSeo = mergeSeo(config.seo, entry.data.seo);
498
- // A page with no picture of its own for link previews gets the generated
499
- // card (lib/og-image.js, served by src/pages/og/[...slug].png.ts).
500
- if (wantsGeneratedCard(pageSeo, entry.data, config.seo)) pageSeo.ogImage = ogImagePath(normalizeEntryId(entry.id));
501
- const currentPath = hrefForSlug(currentFileId);
502
- // This page in each language, for hreflang (languageAlternates() in
503
- // lib/item-pages.js) - a hidden page belongs to no language level.
504
- const alternates = isHidden
505
- ? []
506
- : languageAlternates(activeSection.path, currentFileId, activeSection.pages, landing !== undefined).map((a) => ({
507
- lang: a.lang,
508
- href: hrefForSlug(a.slug),
509
- }));
510
- // The trail for the page's structured data (lib/json-ld.js): home, the
511
- // groups above the page that have a page of their own, the page.
512
- const structuredTrail = [
513
- { name: config.name, href: "/" },
514
- ...breadcrumbs.filter((crumb) => crumb.href).map((crumb) => ({ name: crumb.label, href: crumb.href as string })),
515
- ...(currentPath === "/" ? [] : [{ name: entry.data.title, href: currentPath }]),
516
- ];
517
-
518
- // Page mode (content.config.ts's docsSchema `mode` field, defaulted to
519
- // 'default' there so this is never actually undefined) - see
520
- // BaseLayout.astro for what each value strips out of the topbar/shell,
521
- // and the comment on <BaseLayout mode=...> below for what this file
522
- // itself controls (which slots get filled at all, and how the article
523
- // itself renders).
524
- // A hidden page (isHidden - see hiddenRoutes/Props above) defaults to
525
- // "frame" instead of "default": it has no real section of its own, so
526
- // the sidebar would otherwise show findSectionIndexForSlug's arbitrary
527
- // fallback section with nothing in it actually active - "frame" drops
528
- // the sidebar (and ToC) while keeping the topbar and normal article
529
- // styling. Only a *default*: a hidden page's own frontmatter mode, if
530
- // it set one explicitly, still wins.
531
- // An item's own page with nothing for a sidebar - the item holds tabs, or
532
- // versions, ... that switch elsewhere - is laid out the same way.
533
- const landingWithoutSidebar =
534
- landing !== undefined &&
535
- flattenNav(landing.pages).length === 0 &&
536
- !selectorPlacements(selectors, { sidebar: true }).includes("sidebar");
537
- const pageMode = (isHidden || landingWithoutSidebar) && entry.data.mode === "default" ? "frame" : entry.data.mode;
538
- const showSidebar = pageMode === "default" || pageMode === "wide";
539
- // Products inside a tab or dropdown switch at the top of the sidebar, not in
540
- // the top bar (lib/selector-placement.js - TopBar.astro applies the same rule).
541
- const sidebarPlacements = selectorPlacements(selectors, { sidebar: showSidebar });
542
- const sidebarSwitchers = selectors.filter((_, i) => sidebarPlacements[i] === "sidebar");
543
- const showToc = pageMode === "default";
544
- // 'custom' and 'blank' both get the bare wd-canvas treatment below (no
545
- // auto <h1>, no prev/next, no prose width/padding) - they only differ in
546
- // whether BaseLayout keeps the topbar, which is BaseLayout's own concern
547
- // (mode is passed straight through), not something this file needs to
548
- // branch on separately.
549
- const isCanvasMode = pageMode === "custom" || pageMode === "blank";
550
-
551
- // The "Copy page" menu (CopyPageMenu.astro) - on by default, with the
552
- // options writedocs.json's `contextMenu` leaves on (contextMenuOptions() in
553
- // lib/config-schema.ts; `false` turns it off), and only
554
- // shown where there's a real auto-rendered <h1> to sit next to: canvas
555
- // mode pages (custom/blank) have no such header (a hand-built landing
556
- // page controls its own layout, there's nothing standard to anchor the
557
- // menu to), and OpenAPI operation pages render almost entirely from the
558
- // spec rather than prose - see [...slug].md.ts's own comment on why
559
- // those are excluded from the .md route this menu links to in the first
560
- // place, which this mirrors on the UI side.
561
- const contextMenuItems = contextMenuOptions(config.contextMenu, { mcp: config.mcp });
562
- const showCopyPageMenu = contextMenuItems.length > 0 && !isCanvasMode;
563
- const siteUrl = resolveSiteUrl(config);
564
-
565
- const components = {
566
- Callout,
567
- Note,
568
- Info,
569
- Tip,
570
- Warning,
571
- Danger,
572
- Card,
573
- CardGroup,
574
- Tabs,
575
- Tab,
576
- CodeGroup,
577
- Accordion,
578
- AccordionGroup,
579
- Steps,
580
- Step,
581
- Hint,
582
- Image,
583
- Frame,
584
- Video,
585
- Parameter,
586
- Expandable,
587
- Searchbar,
588
- Badge,
589
- Icon,
590
- RequestExample,
591
- ResponseExample,
592
- Check,
593
- ParamField,
594
- ResponseField,
595
- Columns,
596
- Column,
597
- CodeBlock,
598
- Tooltip,
599
- Update,
600
- Tile,
601
- Panel,
602
- Prompt,
603
- View,
604
- Visibility,
605
- Tree,
606
- FileTree,
607
- Color,
608
- GitHub,
609
- };
610
- ---
611
-
612
- <BaseLayout
613
- config={config}
614
- title={entry.data.title}
615
- description={entry.data.description}
616
- path={currentPath}
617
- seo={pageSeo}
618
- selectors={selectors}
619
- globalDropdowns={globalDropdowns}
620
- mode={pageMode}
621
- lang={pageLang}
622
- alternates={alternates}
623
- breadcrumbs={structuredTrail}
624
- isApi={Boolean(entry.data.openapi)}
625
- >
626
- {showSidebar && <Sidebar slot="sidebar" navTree={navTree} hrefForSlug={hrefForSlug} currentSlug={currentFileId} switchers={sidebarSwitchers} />}
627
- {
628
- isCanvasMode ? (
629
- // 'custom' and 'blank' both get this treatment: no auto <h1>, no
630
- // prev/next nav, none of .wd-article's own prose max-width/padding -
631
- // just the page's own MDX/component content, edge to edge. Still gets
632
- // a data-pagefind-body wrapper so a hand-built page's own text is
633
- // still searchable.
634
- <div class="wd-canvas" data-pagefind-body>
635
- <Content components={components} />
636
- {entry.data.openapi && <ApiPlayground operation={entry.data.openapi} contentDir={contentDir} />}
637
- {/* After the content: a result's excerpt shows the section only when
638
- that's what matched. */}
639
- <div hidden data-markdown-ignore data-wd-search-scope={pageSearchScope.key} data-wd-search-scope-label={pageSearchScope.label} data-wd-search-space={pageSearchSpace?.id} data-wd-search-public={pageSearchSpace?.searchPublic ? "true" : undefined} data-pagefind-filter={`scope:${pageSearchScope.key}`}>
640
- {pageSectionTrail && <span data-pagefind-meta="section">{pageSectionTrail}</span>}
641
- </div>
642
- </div>
643
- ) : (
644
- <article class={`wd-article ${pageMode === "wide" ? "wd-article-wide" : ""}`} data-pagefind-body>
645
- {breadcrumbs.length > 0 && <Breadcrumbs items={breadcrumbs} />}
646
- <div class="wd-article-header">
647
- {
648
- // Frontmatter `deprecated` puts a label beside the <h1>, not in
649
- // it - the <h1>'s text is the search index's page title.
650
- entry.data.deprecated ? (
651
- <div class="wd-article-title">
652
- <h1 data-pagefind-meta="title">{entry.data.title}</h1>
653
- <span class="wd-deprecated-badge">Deprecated</span>
654
- </div>
655
- ) : (
656
- <h1 data-pagefind-meta="title">{entry.data.title}</h1>
657
- )
658
- }
659
- {showCopyPageMenu && (
660
- <CopyPageMenu currentPath={currentPath} siteUrl={siteUrl} siteName={config.name} options={contextMenuItems} />
661
- )}
662
- </div>
663
- <Content components={components} />
664
- {entry.data.openapi && <ApiPlayground operation={entry.data.openapi} contentDir={contentDir} />}
665
- <div hidden data-markdown-ignore data-wd-search-scope={pageSearchScope.key} data-wd-search-scope-label={pageSearchScope.label} data-wd-search-space={pageSearchSpace?.id} data-wd-search-public={pageSearchSpace?.searchPublic ? "true" : undefined} data-pagefind-filter={`scope:${pageSearchScope.key}`}>
666
- {pageSectionTrail && <span data-pagefind-meta="section">{pageSectionTrail}</span>}
667
- </div>
668
- {!entry.data.hideFooterPagination && (
669
- <nav class="wd-prevnext" data-pagefind-ignore data-markdown-ignore>
670
- {prev && (
671
- <a class="wd-prevnext-card wd-prevnext-prev" href={hrefForSlug(prev.slug)}>
672
- <span class="wd-prevnext-row">
673
- <svg
674
- class="wd-prevnext-icon"
675
- width="16"
676
- height="16"
677
- viewBox="0 0 24 24"
678
- fill="none"
679
- stroke="currentColor"
680
- stroke-width="2"
681
- stroke-linecap="round"
682
- stroke-linejoin="round"
683
- aria-hidden="true"
684
- >
685
- <line x1="19" y1="12" x2="5" y2="12" />
686
- <polyline points="12 19 5 12 12 5" />
687
- </svg>
688
- <span class="wd-prevnext-label">Previous</span>
689
- </span>
690
- <span class="wd-prevnext-title">{titleForSlug(prev.slug)}</span>
691
- </a>
692
- )}
693
- {next && (
694
- <a class="wd-prevnext-card wd-prevnext-next" href={hrefForSlug(next.slug)}>
695
- <span class="wd-prevnext-row">
696
- <span class="wd-prevnext-label">Next</span>
697
- <svg
698
- class="wd-prevnext-icon"
699
- width="16"
700
- height="16"
701
- viewBox="0 0 24 24"
702
- fill="none"
703
- stroke="currentColor"
704
- stroke-width="2"
705
- stroke-linecap="round"
706
- stroke-linejoin="round"
707
- aria-hidden="true"
708
- >
709
- <line x1="5" y1="12" x2="19" y2="12" />
710
- <polyline points="12 5 19 12 12 19" />
711
- </svg>
712
- </span>
713
- <span class="wd-prevnext-title">{titleForSlug(next.slug)}</span>
714
- </a>
715
- )}
716
- </nav>
717
- )}
718
- </article>
719
- )
720
- }
721
- {
722
- showToc &&
723
- (entry.data.openapi ? (
724
- <ApiReferencePanel slot="toc" operation={entry.data.openapi} contentDir={contentDir} />
725
- ) : (
726
- <TableOfContents slot="toc" headings={tocHeadings} />
727
- ))
728
- }
729
- </BaseLayout>
730
-
731
- <script>
732
- import { mcpServerUrl, cursorInstallLink, vscodeInstallLink } from "../lib/mcp-links.js";
733
-
734
- // Astro assigns every h2-h4 an id automatically, but doesn't add a
735
- // clickable anchor next to it. rehype-autolink-headings can't be used
736
- // for this directly: Astro's own heading-id rehype plugin always runs
737
- // AFTER any user-supplied rehypePlugins in its pipeline, so a plugin
738
- // that links existing ids never sees them. Adding the anchor client-side
739
- // sidesteps that ordering constraint entirely.
740
- function addHeadingAnchors(root: ParentNode) {
741
- root
742
- .querySelectorAll<HTMLElement>(".wd-article > h2[id], .wd-article > h3[id], .wd-article > h4[id]")
743
- .forEach((heading) => {
744
- if (heading.querySelector(".wd-heading-anchor")) return;
745
- const anchor = document.createElement("a");
746
- anchor.className = "wd-heading-anchor";
747
- anchor.href = `#${heading.id}`;
748
- anchor.setAttribute("aria-label", "Link to this section");
749
- anchor.textContent = "#";
750
- heading.appendChild(anchor);
751
- });
752
- }
753
- addHeadingAnchors(document);
754
- document.addEventListener("astro:page-load", () => addHeadingAnchors(document));
755
-
756
- // Copy-to-clipboard button for every fenced (```) code block - the
757
- // button itself is emitted at build time by codeBlockTransformer
758
- // (astro.config.mjs / src/lib/shiki-code-block.js), wrapping each
759
- // <pre> in a .wd-code-block container; this just wires up the click
760
- // behavior client-side, same dataset-guarded init pattern as
761
- // addHeadingAnchors above.
762
- function initCodeCopyButtons(root: ParentNode) {
763
- root.querySelectorAll<HTMLButtonElement>(".wd-code-copy-btn").forEach((btn) => {
764
- if (btn.dataset.wdInit) return;
765
- btn.dataset.wdInit = "true";
766
- btn.addEventListener("click", async () => {
767
- const pre = btn.closest(".wd-code-block")?.querySelector("pre");
768
- if (!pre) return;
769
- try {
770
- await navigator.clipboard.writeText(pre.textContent ?? "");
771
- } catch {
772
- return; // clipboard unavailable (e.g. insecure context) - fail silently
773
- }
774
- btn.textContent = "✓";
775
- btn.classList.add("wd-code-copied");
776
- window.setTimeout(() => {
777
- btn.textContent = "⧉";
778
- btn.classList.remove("wd-code-copied");
779
- }, 1500);
780
- });
781
- });
782
- }
783
- initCodeCopyButtons(document);
784
- document.addEventListener("astro:page-load", () => initCodeCopyButtons(document));
785
-
786
- // Clipboard-copy button for CopyPageMenu.astro's primary "Copy page"
787
- // button (the split button's left half - the right half is just a
788
- // .wd-dropdown-trigger caret, handled by BaseLayout's own
789
- // initDropdowns()) - same dataset-guarded init pattern as
790
- // initCodeCopyButtons above, but fetches its content from the button's
791
- // own data-md-path (the [...slug].md.ts route for the current page -
792
- // see CopyPageMenu.astro) rather than reading it from an
793
- // already-rendered element on the page, since the raw Markdown source
794
- // isn't otherwise present in the DOM anywhere (the rendered HTML
795
- // content is not the same text).
796
- function initCopyPageMenu(root: ParentNode) {
797
- root.querySelectorAll<HTMLButtonElement>("button[data-copy-page]").forEach((btn) => {
798
- if (btn.dataset.wdInit) return;
799
- btn.dataset.wdInit = "true";
800
- const label = btn.querySelector<HTMLElement>(".wd-copy-page-primary-label");
801
- const originalLabel = label?.textContent ?? "Copy page";
802
- btn.addEventListener("click", async () => {
803
- const mdPath = btn.dataset.mdPath;
804
- if (!mdPath) return;
805
- try {
806
- const res = await fetch(mdPath);
807
- const text = await res.text();
808
- await navigator.clipboard.writeText(text);
809
- } catch {
810
- return; // fetch/clipboard unavailable - fail silently, same as initCodeCopyButtons
811
- }
812
- btn.classList.add("wd-copy-page-copied");
813
- if (label) label.textContent = "Copied!";
814
- window.setTimeout(() => {
815
- btn.classList.remove("wd-copy-page-copied");
816
- if (label) label.textContent = originalLabel;
817
- }, 1500);
818
- });
819
- });
820
- }
821
- initCopyPageMenu(document);
822
- document.addEventListener("astro:page-load", () => initCopyPageMenu(document));
823
-
824
- // "Open in ChatGPT/Claude/Perplexity" on a site with no writedocs.json
825
- // `domain`: the page's absolute .md URL isn't known at build time, so the
826
- // link is completed here from the address the page is served from (see
827
- // CopyPageMenu.astro) - same prompt the build writes when it does know.
828
- function initAskLinks(root: ParentNode) {
829
- root.querySelectorAll<HTMLAnchorElement>("a[data-ask-base][data-md-path]").forEach((link) => {
830
- const url = new URL(link.dataset.mdPath ?? "/", window.location.origin).href;
831
- link.href = link.dataset.askBase + encodeURIComponent(`Read ${url} so you can answer questions about it.`);
832
- });
833
- }
834
- initAskLinks(document);
835
- document.addEventListener("astro:page-load", () => initAskLinks(document));
836
-
837
- // The menu's MCP options (CopyPageMenu.astro). "Copy MCP server URL"
838
- // copies it and says so in its own label - inside the menu, which stays
839
- // open to show it. "Connect to Cursor / VS Code" on a site with no
840
- // `domain` get their install links here, for the address the page is
841
- // served from.
842
- function initMcpMenu(root: ParentNode) {
843
- const serverUrl = (el: HTMLElement) => el.dataset.copyMcp || mcpServerUrl(window.location.origin);
844
- root.querySelectorAll<HTMLButtonElement>("button[data-copy-mcp]").forEach((btn) => {
845
- if (btn.dataset.wdInit) return;
846
- btn.dataset.wdInit = "true";
847
- const label = btn.querySelector<HTMLElement>(".wd-copy-page-item-title, .wd-copy-page-primary-label");
848
- const originalLabel = label?.textContent ?? "";
849
- btn.addEventListener("click", async (e) => {
850
- e.stopPropagation();
851
- try {
852
- await navigator.clipboard.writeText(serverUrl(btn));
853
- } catch {
854
- return;
855
- }
856
- if (label) label.textContent = "Copied!";
857
- window.setTimeout(() => {
858
- if (label) label.textContent = originalLabel;
859
- }, 1500);
860
- });
861
- });
862
- root.querySelectorAll<HTMLAnchorElement>("a[data-mcp-install]").forEach((link) => {
863
- const url = mcpServerUrl(window.location.origin);
864
- const name = link.dataset.mcpName ?? document.title;
865
- link.href = link.dataset.mcpInstall === "cursor" ? cursorInstallLink(name, url) : vscodeInstallLink(name, url);
866
- });
867
- }
868
- initMcpMenu(document);
869
- document.addEventListener("astro:page-load", () => initMcpMenu(document));
870
-
871
- // Show more/less toggle for ```js expandable code blocks - same
872
- // build-time-emitted-button + client-wired-click pattern as the copy
873
- // button above; codeBlockTransformer only adds this button when the
874
- // fence's meta string contains the `expandable` keyword.
875
- function initCodeExpandButtons(root: ParentNode) {
876
- root.querySelectorAll<HTMLButtonElement>(".wd-code-expand-btn").forEach((btn) => {
877
- if (btn.dataset.wdInit) return;
878
- btn.dataset.wdInit = "true";
879
- btn.addEventListener("click", () => {
880
- const block = btn.closest(".wd-code-expandable");
881
- if (!block) return;
882
- const expanded = block.classList.toggle("wd-code-expanded");
883
- btn.textContent = expanded ? "Show less" : "Show more";
884
- });
885
- });
886
- }
887
- initCodeExpandButtons(document);
888
- document.addEventListener("astro:page-load", () => initCodeExpandButtons(document));
889
-
890
- // Renders ```mermaid fenced blocks - already reshaped at build time into
891
- // plain <div class="mermaid">source text</div> containers (see
892
- // rehypeMermaid in astro.config.mjs/src/lib/mermaid-rehype.js) - into
893
- // actual SVG diagrams. Lazily imports the mermaid package itself, same
894
- // reasoning as initSearch's Pagefind import above: most pages have no
895
- // diagrams at all, no reason to ship/parse that bundle on every load.
896
- let mermaidLoadPromise: Promise<typeof import("mermaid")> | null = null;
897
- function ensureMermaid() {
898
- if (!mermaidLoadPromise) mermaidLoadPromise = import("mermaid");
899
- return mermaidLoadPromise;
900
- }
901
-
902
- // mermaid.run() replaces a block's contents with the rendered SVG,
903
- // destroying the original diagram source - stashed in a data attribute
904
- // the first time a block is seen (before it's ever rendered), so a
905
- // later re-render (see the wd:theme-change listener below - diagrams
906
- // are baked to static SVG at render time, so a theme change needs an
907
- // actual re-render, unlike Shiki code blocks which swap colors live via
908
- // CSS custom properties) has something to restore from.
909
- function stashMermaidSource(root: ParentNode) {
910
- root.querySelectorAll<HTMLElement>(".mermaid").forEach((el) => {
911
- if (el.dataset.mermaidSource === undefined) el.dataset.mermaidSource = el.textContent ?? "";
912
- });
913
- }
914
-
915
- async function renderMermaid(root: ParentNode, theme: "light" | "dark") {
916
- const blocks = Array.from(root.querySelectorAll<HTMLElement>(".mermaid"));
917
- if (blocks.length === 0) return;
918
- const { default: mermaid } = await ensureMermaid();
919
- mermaid.initialize({ startOnLoad: false, theme: theme === "dark" ? "dark" : "default", securityLevel: "strict" });
920
- blocks.forEach((el) => {
921
- el.removeAttribute("data-processed"); // mermaid's own re-render guard - see run()'s docs
922
- el.innerHTML = el.dataset.mermaidSource ?? "";
923
- });
924
- // suppressErrors: a malformed diagram on one block shouldn't take
925
- // down every other diagram on the page - mermaid still renders a
926
- // per-block error SVG in place and logs details to the console.
927
- await mermaid.run({ nodes: blocks, suppressErrors: true });
928
- }
929
-
930
- function initMermaid(root: ParentNode) {
931
- stashMermaidSource(root);
932
- if (!root.querySelector(".mermaid")) return;
933
- const theme = document.documentElement.dataset.theme === "dark" ? "dark" : "light";
934
- renderMermaid(root, theme);
935
- }
936
- initMermaid(document);
937
- document.addEventListener("astro:page-load", () => initMermaid(document));
938
- document.addEventListener("wd:theme-change", ((e: CustomEvent<{ theme: "light" | "dark" }>) => {
939
- renderMermaid(document, e.detail.theme);
940
- }) as EventListener);
941
-
942
- // RequestExample/ResponseExample.astro's own docking behavior - on
943
- // desktop, moves their rendered .wd-example-panel(s) out of the normal
944
- // article flow and into .wd-toc-col (replacing whatever it would
945
- // otherwise show - the heading-based TableOfContents or
946
- // ApiReferencePanel, per those two components' own comment), matching
947
- // Mintlify's stated behavior for the components this was modeled on:
948
- // pinned in the sidebar on desktop, plain in-place code blocks below
949
- // 1150px (the exact breakpoint .wd-toc-col itself disappears at - see
950
- // base.css). This can't be done at build time: MDX compiles a page's
951
- // whole body into one content flow, with no way for a static render to
952
- // place part of that flow into a *different* column's own slot output
953
- // - a client-side move after the fact is the only way to get this
954
- // content into a sibling column's subtree at all.
955
- function initExamplePanels(root: ParentNode) {
956
- const tocCol = document.querySelector<HTMLElement>(".wd-toc-col");
957
- if (!tocCol) return; // no toc column on this page (mode !== 'default') - nothing to dock into
958
-
959
- // Top-level panels only: Mintlify's <Panel> (Panel.astro) is itself a
960
- // .wd-example-panel, and a RequestExample/ResponseExample inside it
961
- // moves with it rather than on its own.
962
- const panels = Array.from(root.querySelectorAll<HTMLElement>(".wd-example-panel")).filter(
963
- (panel) => !panel.parentElement?.closest(".wd-example-panel"),
964
- );
965
- if (panels.length === 0) return;
966
- if (tocCol.dataset.wdExampleInit) return;
967
- tocCol.dataset.wdExampleInit = "true";
968
-
969
- // Response always docks below Request regardless of source order,
970
- // matching Mintlify's own stated behavior for these two components.
971
- panels.sort((a, b) => {
972
- const rank = (el: HTMLElement) => (el.classList.contains("wd-request-example") ? 0 : 1);
973
- return rank(a) - rank(b);
974
- });
975
-
976
- // A comment node marks each panel's original in-flow position, so
977
- // undock() (a desktop -> mobile resize, or simply no matching media
978
- // query at all) can put it back exactly where the article's own
979
- // content expects it, rather than leaving a permanent gap.
980
- const anchors = panels.map((panel) => {
981
- const anchor = document.createComment("wd-example-anchor");
982
- panel.before(anchor);
983
- return anchor;
984
- });
985
-
986
- let host = tocCol.querySelector<HTMLElement>(".wd-example-host");
987
- if (!host) {
988
- host = document.createElement("div");
989
- host.className = "wd-example-host";
990
- tocCol.prepend(host);
991
- }
992
- const dockedHost = host;
993
-
994
- // Whatever .wd-toc-col would otherwise render (TableOfContents' own
995
- // <nav class="wd-toc">, or ApiReferencePanel's own markup) - hidden
996
- // while panels are docked rather than removed, so undock() has
997
- // something to restore instead of needing to re-render it.
998
- const existingTocContent = Array.from(tocCol.children).filter((el) => el !== dockedHost) as HTMLElement[];
999
-
1000
- function dock() {
1001
- existingTocContent.forEach((el) => (el.style.display = "none"));
1002
- dockedHost.hidden = false;
1003
- panels.forEach((panel) => dockedHost.appendChild(panel));
1004
- }
1005
- function undock() {
1006
- dockedHost.hidden = true;
1007
- existingTocContent.forEach((el) => (el.style.display = ""));
1008
- panels.forEach((panel, i) => anchors[i].after(panel));
1009
- }
1010
- const desktopQuery = window.matchMedia("(min-width: 1151px)");
1011
- const sync = () => (desktopQuery.matches ? dock() : undock());
1012
- sync();
1013
- desktopQuery.addEventListener("change", sync);
1014
- }
1015
- initExamplePanels(document);
1016
- document.addEventListener("astro:page-load", () => initExamplePanels(document));
1017
- </script>
1018
-
1019
- <style>
1020
- .wd-article {
1021
- max-width: 900px;
1022
- margin: 0 auto;
1023
- /* Top padding matches Sidebar.astro's .wd-sidebar and
1024
- TableOfContents.astro's .wd-toc exactly (both 1.5rem) - all three
1025
- are siblings in the same .wd-shell row with no padding of their
1026
- own on .wd-main-col in between, so this is what actually lines up
1027
- the article's top edge with the sidebar/TOC's first item instead
1028
- of starting visibly lower than both. */
1029
- padding: 1.5rem 1.5rem 4rem;
1030
- }
1031
- /* frontmatter `mode: wide` - the table of contents column is gone (see
1032
- BaseLayout.astro), so the article itself gets more room too, rather
1033
- than just recentering the same 760px column into now-empty space. */
1034
- .wd-article-wide {
1035
- max-width: 1040px;
1036
- }
1037
- /* frontmatter `mode: custom` - no prose width/padding at all, no
1038
- max-width, no centering: a hand-built landing page controls its own
1039
- layout completely, full-bleed if it wants to. */
1040
- .wd-canvas {
1041
- width: 100%;
1042
- }
1043
- /* Wraps the auto-rendered <h1> together with CopyPageMenu (only
1044
- rendered when writedocs.json's `contextMenu` isn't off - see
1045
- showCopyPageMenu above) so the two sit on one row, menu pinned to
1046
- the right. Always present (even with no menu) rather than only
1047
- wrapping the <h1> conditionally, so the <h1>'s own top/bottom
1048
- spacing comes from exactly one place regardless of whether the menu
1049
- renders - flex items don't margin-collapse with their container the
1050
- way a bare <h1> would with .wd-article, so that margin is
1051
- reset/reapplied here instead of relying on the browser's default
1052
- heading margin still doing the right thing once it's no longer a
1053
- direct .wd-article child. */
1054
- .wd-article-header {
1055
- display: flex;
1056
- flex-wrap: wrap;
1057
- align-items: center;
1058
- justify-content: space-between;
1059
- gap: 0.75rem 1rem;
1060
- margin: 0 0 1rem;
1061
- }
1062
- .wd-article-header h1 {
1063
- margin: 0;
1064
- /* A word longer than the whole line (a long product name on a phone)
1065
- breaks rather than pushing the page wider than the screen. */
1066
- overflow-wrap: break-word;
1067
- }
1068
- /* The title takes the room the menu leaves. Its basis is 0, so the row
1069
- only wraps when its longest word and the menu can't share a line - on
1070
- a desktop, a long title still wraps beside the menu; on a phone, a long
1071
- word sends the menu below the title instead of off the screen. */
1072
- .wd-article-header > h1,
1073
- .wd-article-header > .wd-article-title {
1074
- flex: 1 1 0;
1075
- }
1076
- /* Frontmatter `deprecated: true` (Mintlify's) - same amber as the
1077
- sidebar's own deprecated tag (NavTree.astro) and Parameter's
1078
- deprecated badge. */
1079
- .wd-article-title {
1080
- display: flex;
1081
- align-items: center;
1082
- flex-wrap: wrap;
1083
- gap: 0.6rem;
1084
- }
1085
- .wd-deprecated-badge {
1086
- display: inline-block;
1087
- padding: 0.15rem 0.55rem;
1088
- border-radius: 999px;
1089
- font-size: 0.8rem;
1090
- font-weight: 700;
1091
- color: #d97706;
1092
- background: color-mix(in srgb, #d97706 15%, transparent);
1093
- }
1094
- .wd-prevnext {
1095
- display: flex;
1096
- justify-content: space-between;
1097
- margin-top: 3rem;
1098
- padding-top: 1.5rem;
1099
- border-top: 1px solid var(--wd-border);
1100
- gap: 1rem;
1101
- }
1102
- /* Two side-by-side cards, each taking up to half the row - flex: 1 1
1103
- 0 rather than a fixed 50% so a single remaining card (first page:
1104
- only next, last page: only prev) grows to fill the width instead
1105
- of leaving an empty gap next to it. */
1106
- .wd-prevnext-card {
1107
- display: flex;
1108
- flex: 1 1 0;
1109
- min-width: 0;
1110
- flex-direction: column;
1111
- gap: 0.1rem;
1112
- padding: 0.75rem 1.1rem;
1113
- border: 1px solid var(--wd-border);
1114
- border-radius: 0.75rem;
1115
- text-decoration: none;
1116
- color: inherit;
1117
- transition:
1118
- border-color 0.15s ease,
1119
- box-shadow 0.15s ease;
1120
- }
1121
- /* Both cards are identical at rest - the accent border/glow in the
1122
- reference screenshot is that card's :hover state, not a permanent
1123
- treatment on Next, so both wd-prevnext-prev and wd-prevnext-next
1124
- share this one hover rule instead of Next getting its own always-on
1125
- copy. Built from --wd-primary via color-mix() rather than a flat
1126
- hardcoded color, so it stays correct under any theme's own accent. */
1127
- .wd-prevnext-card:hover {
1128
- border-color: var(--wd-primary);
1129
- box-shadow: 0 0 0 3px color-mix(in srgb, var(--wd-primary) 10%, transparent);
1130
- }
1131
- .wd-prevnext-row {
1132
- display: flex;
1133
- align-items: center;
1134
- justify-content: space-between;
1135
- gap: 0.5rem;
1136
- color: var(--wd-text-muted);
1137
- font-size: 0.75rem;
1138
- }
1139
- .wd-prevnext-icon {
1140
- flex-shrink: 0;
1141
- color: var(--wd-text-muted);
1142
- transition: color 0.15s ease;
1143
- }
1144
- .wd-prevnext-title {
1145
- font-weight: 600;
1146
- font-size: 0.85rem;
1147
- color: var(--wd-heading);
1148
- white-space: nowrap;
1149
- overflow: hidden;
1150
- text-overflow: ellipsis;
1151
- transition: color 0.15s ease;
1152
- }
1153
- /* Previous's title sits at the same end of the card its own
1154
- "Previous" label already does (right-aligned, next to the arrow's
1155
- fixed spot on the left) - Next's title stays left-aligned, at the
1156
- same end its own "Next" label sits. Keeps each card's two rows
1157
- reading as one consistent left/right-anchored column instead of
1158
- the title always defaulting to the left regardless of which side
1159
- its card's own label/arrow occupy. */
1160
- .wd-prevnext-prev .wd-prevnext-title {
1161
- text-align: right;
1162
- }
1163
- /* Icon and title pick up the accent color on hover - the
1164
- "Next"/"Previous" label itself stays muted even then, since it's a
1165
- plain UI affordance rather than the actual content being pointed
1166
- to. */
1167
- .wd-prevnext-card:hover .wd-prevnext-icon,
1168
- .wd-prevnext-card:hover .wd-prevnext-title {
1169
- color: var(--wd-primary);
1170
- }
1171
- @media (width <= 640px) {
1172
- .wd-prevnext {
1173
- flex-direction: column;
1174
- }
1175
- }
1176
- </style>
1177
-
1178
- <style is:global>
1179
- /*
1180
- * These target direct children of .wd-article (or, for inline marks,
1181
- * specific prose containers) rather than bare tag selectors. MDX
1182
- * component internals (Card titles/links, prev/next nav links) also
1183
- * live inside .wd-article but nested deeper - a bare ".wd-article h3"
1184
- * or ".wd-article a" would win the specificity tie against those
1185
- * components' own scoped styles and visibly break them (oversized
1186
- * card titles, underlined cards, underlined prev/next links). Real
1187
- * MDX content (headings, paragraphs, lists, etc.) renders as flat
1188
- * direct children of .wd-article, so the ">" combinator is enough to
1189
- * separate "actual content" from "component chrome" without needing
1190
- * per-component :not() exceptions.
1191
- */
1192
- /* --wd-topbar-offset is set by initTopbarOffset() (src/scripts/
1193
- topbar-offset.ts) to the sticky topbar's real measured height - see
1194
- its own file comment for why a fixed 5rem (this var()'s own
1195
- fallback, for the instant before that script's first measurement)
1196
- isn't enough once a site's topbar grows a second row. Without this,
1197
- jumping straight to a #heading link (a hard load, or clicking one of
1198
- the .wd-heading-anchor links below) lands the heading partly hidden
1199
- under the sticky topbar. */
1200
- .wd-article > h2 {
1201
- font-size: 1.5rem;
1202
- margin: 2.75rem 0 1rem;
1203
- padding-top: 0.25rem;
1204
- scroll-margin-top: var(--wd-topbar-offset, 5rem);
1205
- }
1206
- .wd-article > h3 {
1207
- font-size: 1.2rem;
1208
- margin: 2rem 0 0.75rem;
1209
- scroll-margin-top: var(--wd-topbar-offset, 5rem);
1210
- }
1211
- .wd-article > h4 {
1212
- font-size: 1rem;
1213
- margin: 1.5rem 0 0.5rem;
1214
- scroll-margin-top: var(--wd-topbar-offset, 5rem);
1215
- }
1216
- .wd-article > h2:first-child,
1217
- .wd-article > h3:first-child {
1218
- margin-top: 0;
1219
- }
1220
- .wd-article > p {
1221
- margin: 0.9rem 0;
1222
- }
1223
- .wd-article > ul,
1224
- .wd-article > ol {
1225
- margin: 0.9rem 0;
1226
- padding-left: 1.4rem;
1227
- }
1228
- .wd-article li {
1229
- margin: 0.35rem 0;
1230
- }
1231
- .wd-article li > ul,
1232
- .wd-article li > ol {
1233
- margin: 0.35rem 0;
1234
- }
1235
- .wd-article > blockquote {
1236
- margin: 1.25rem 0;
1237
- padding: 0.1rem 1rem;
1238
- border-left: 3px solid var(--wd-primary);
1239
- background: var(--wd-surface);
1240
- border-radius: 0 0.4rem 0.4rem 0;
1241
- color: var(--wd-text-muted);
1242
- }
1243
- .wd-article blockquote p {
1244
- margin: 0.7rem 0;
1245
- }
1246
- .wd-article > table {
1247
- width: 100%;
1248
- border-collapse: collapse;
1249
- margin: 1.25rem 0;
1250
- font-size: 0.9rem;
1251
- }
1252
- .wd-article th,
1253
- .wd-article td {
1254
- text-align: left;
1255
- padding: 0.55rem 0.75rem;
1256
- border-bottom: 1px solid var(--wd-border);
1257
- vertical-align: top;
1258
- }
1259
- .wd-article th {
1260
- color: var(--wd-text-muted);
1261
- font-weight: 600;
1262
- font-size: 0.8rem;
1263
- text-transform: uppercase;
1264
- letter-spacing: 0.03em;
1265
- }
1266
- .wd-article > hr {
1267
- border: none;
1268
- border-top: 1px solid var(--wd-border);
1269
- margin: 2.5rem 0;
1270
- }
1271
- /* Fenced (```) code blocks - codeBlockTransformer
1272
- (src/lib/shiki-code-block.js) wraps every one's <pre> in this
1273
- .wd-code-block div at build time (plus an optional .wd-code-title
1274
- bar, and the copy/expand buttons - see below). The card-like chrome
1275
- (border/radius/background) lives on the wrapper rather than the
1276
- <pre> itself so a title bar, when present, can sit flush above it
1277
- inside the same box; Astro's Shiki pipeline (dual light/dark themes
1278
- configured in astro.config.mjs) already supplies the <pre>'s own
1279
- background/text colors via inline styles. Matches both a standalone
1280
- block (direct child of .wd-article) and one nested inside
1281
- <CodeGroup> (which re-targets the margin/radius itself via its own
1282
- more specific `.wd-codegroup > .wd-code-block` rule in
1283
- CodeGroup.astro). */
1284
- .wd-code-block {
1285
- position: relative;
1286
- margin: 1.25rem 0;
1287
- border: 1px solid var(--wd-border);
1288
- border-radius: 0.55rem;
1289
- overflow: hidden;
1290
- }
1291
- .wd-article pre.astro-code {
1292
- margin: 0;
1293
- padding: 1rem 1.1rem;
1294
- border: none;
1295
- border-radius: 0;
1296
- font-size: 0.85rem;
1297
- line-height: 1.55;
1298
- }
1299
- .wd-code-title {
1300
- padding: 0.5rem 1rem;
1301
- font-family: monospace;
1302
- font-size: 0.78rem;
1303
- font-weight: 500;
1304
- color: var(--wd-text-muted);
1305
- background: var(--wd-surface);
1306
- border-bottom: 1px solid var(--wd-border);
1307
- }
1308
- /* A fence's `icon="..."` (shiki-code-block.js) - the icon's own SVG
1309
- arrives as a data URL in --wd-code-icon and is used as a mask, so it
1310
- paints in the title's text color instead of the SVG's own fill. */
1311
- .wd-code-title-icon {
1312
- display: inline-block;
1313
- width: 1em;
1314
- height: 1em;
1315
- margin-right: 0.45rem;
1316
- vertical-align: -0.125em;
1317
- background: currentColor;
1318
- -webkit-mask: var(--wd-code-icon) center / contain no-repeat;
1319
- mask: var(--wd-code-icon) center / contain no-repeat;
1320
- }
1321
- .wd-code-copy-btn {
1322
- position: absolute;
1323
- top: 0.6rem;
1324
- right: 0.6rem;
1325
- display: inline-flex;
1326
- align-items: center;
1327
- justify-content: center;
1328
- width: 1.85rem;
1329
- height: 1.85rem;
1330
- padding: 0;
1331
- border-radius: 0.4rem;
1332
- border: 1px solid var(--wd-border);
1333
- background: var(--wd-background);
1334
- color: var(--wd-text-muted);
1335
- font-size: 0.9rem;
1336
- line-height: 1;
1337
- cursor: pointer;
1338
- opacity: 0;
1339
- transition:
1340
- opacity 0.15s ease,
1341
- color 0.15s ease,
1342
- background 0.15s ease,
1343
- border-color 0.15s ease;
1344
- }
1345
- .wd-code-block:hover .wd-code-copy-btn,
1346
- .wd-code-copy-btn:focus-visible {
1347
- opacity: 1;
1348
- }
1349
- .wd-code-copy-btn:hover {
1350
- color: var(--wd-text);
1351
- background: var(--wd-surface);
1352
- }
1353
- .wd-code-copy-btn.wd-code-copied {
1354
- opacity: 1;
1355
- color: #16a34a;
1356
- border-color: #16a34a;
1357
- }
1358
- /* ```js wrap - opts a single block into wrapping long lines instead
1359
- of horizontal-scrolling (the default). */
1360
- .wd-code-wrap pre.astro-code,
1361
- .wd-code-wrap pre.astro-code code {
1362
- white-space: pre-wrap;
1363
- word-break: break-word;
1364
- overflow-x: hidden;
1365
- }
1366
- /* ```js lines (or showLineNumbers) - a CSS-counter gutter, no markup
1367
- needed beyond a class since every line is already its own .line
1368
- span. */
1369
- .wd-code-lines pre.astro-code code {
1370
- counter-reset: wd-code-line;
1371
- }
1372
- .wd-code-lines pre.astro-code .line {
1373
- counter-increment: wd-code-line;
1374
- }
1375
- .wd-code-lines pre.astro-code .line::before {
1376
- content: counter(wd-code-line);
1377
- display: inline-block;
1378
- width: 1.8em;
1379
- margin-right: 1em;
1380
- text-align: right;
1381
- color: var(--wd-text-muted);
1382
- user-select: none;
1383
- }
1384
- /* ```js expandable - collapses to a fixed height with a "Show more"
1385
- button below; toggled via .wd-code-expanded, added by the click
1386
- handler in the <script> block below. */
1387
- .wd-code-expandable pre.astro-code {
1388
- max-height: 340px;
1389
- overflow-y: hidden;
1390
- }
1391
- .wd-code-expandable.wd-code-expanded pre.astro-code {
1392
- max-height: none;
1393
- }
1394
- .wd-code-expand-btn {
1395
- display: block;
1396
- width: 100%;
1397
- padding: 0.5rem;
1398
- border: none;
1399
- border-top: 1px solid var(--wd-border);
1400
- background: var(--wd-surface);
1401
- color: var(--wd-primary);
1402
- font-size: 0.8rem;
1403
- font-weight: 500;
1404
- cursor: pointer;
1405
- }
1406
- .wd-code-expand-btn:hover {
1407
- background: color-mix(in srgb, var(--wd-primary) 8%, var(--wd-surface));
1408
- }
1409
- /* Line/word annotation classes added by the official
1410
- @shikijs/transformers transformers configured alongside
1411
- codeBlockTransformer in astro.config.mjs:
1412
- .line.highlighted - transformerMetaHighlight
1413
- (```js {1,3-5}) and
1414
- transformerNotationHighlight
1415
- (// [!code highlight]/[!code hl])
1416
- .line.diff.add / .diff.remove - transformerNotationDiff
1417
- (// [!code ++] / // [!code --])
1418
- .line.error / .warning / .info - transformerNotationErrorLevel
1419
- (// [!code error]/[!code warning])
1420
- (also carries .highlighted)
1421
- pre.has-focused, .line.focused - transformerNotationFocus
1422
- (// [!code focus])
1423
- .highlighted-word - transformerMetaWordHighlight
1424
- (```js /someWord/) and
1425
- transformerNotationWordHighlight
1426
- (// [!code word:someWord])
1427
- Every .line needs display:inline-block + full width for its
1428
- highlight background to stretch edge-to-edge (by default a <span>
1429
- only extends as wide as its own text) - harmless for plain lines,
1430
- since inline-block with no other styling renders identically to
1431
- the browser's normal inline flow here. */
1432
- .astro-code .line {
1433
- display: inline-block;
1434
- width: 100%;
1435
- }
1436
- .astro-code .line.highlighted {
1437
- background: color-mix(in srgb, var(--wd-primary) 12%, transparent);
1438
- margin: 0 -1.1rem;
1439
- padding: 0 1.1rem;
1440
- width: calc(100% + 2.2rem);
1441
- }
1442
- .astro-code .line.diff {
1443
- margin: 0 -1.1rem;
1444
- padding: 0 1.1rem 0 1.6rem;
1445
- width: calc(100% + 2.2rem);
1446
- position: relative;
1447
- }
1448
- .astro-code .line.diff.add {
1449
- background: color-mix(in srgb, #16a34a 15%, transparent);
1450
- }
1451
- .astro-code .line.diff.remove {
1452
- background: color-mix(in srgb, #dc2626 15%, transparent);
1453
- opacity: 0.85;
1454
- }
1455
- .astro-code .line.diff.add::before,
1456
- .astro-code .line.diff.remove::before {
1457
- position: absolute;
1458
- left: 0.5rem;
1459
- font-weight: 700;
1460
- }
1461
- .astro-code .line.diff.add::before {
1462
- content: "+";
1463
- color: #16a34a;
1464
- }
1465
- .astro-code .line.diff.remove::before {
1466
- content: "-";
1467
- color: #dc2626;
1468
- }
1469
- .astro-code .line.error {
1470
- background: color-mix(in srgb, #dc2626 15%, transparent);
1471
- }
1472
- .astro-code .line.warning {
1473
- background: color-mix(in srgb, #d97706 15%, transparent);
1474
- }
1475
- .astro-code .line.info {
1476
- background: color-mix(in srgb, #2563eb 12%, transparent);
1477
- }
1478
- pre.astro-code.has-focused .line {
1479
- opacity: 0.45;
1480
- filter: blur(0.3px);
1481
- transition:
1482
- opacity 0.2s ease,
1483
- filter 0.2s ease;
1484
- }
1485
- pre.astro-code.has-focused .line.focused {
1486
- opacity: 1;
1487
- filter: none;
1488
- }
1489
- pre.astro-code.has-focused:hover .line {
1490
- opacity: 1;
1491
- filter: none;
1492
- }
1493
- .astro-code .highlighted-word {
1494
- background: color-mix(in srgb, var(--wd-primary) 20%, transparent);
1495
- border-radius: 0.25rem;
1496
- padding: 0.05rem 0.2rem;
1497
- margin: -0.05rem -0.15rem;
1498
- }
1499
- .wd-article img {
1500
- max-width: 100%;
1501
- border-radius: 0.5rem;
1502
- border: 1px solid var(--wd-border);
1503
- }
1504
- /* ```mermaid fenced blocks (rehypeMermaid in astro.config.mjs reshapes
1505
- them into this plain <div class="mermaid"> container at build time -
1506
- see mermaid-rehype.js) - mermaid.js (initMermaid() below) replaces
1507
- the raw source text with a rendered <svg> in place, client-side.
1508
- overflow-x: auto rather than shrinking the diagram, since a wide
1509
- flowchart squeezed into the article's ~760px column becomes
1510
- unreadable; centering only kicks in once the svg fits, via the
1511
- inline-block + text-align combo below. */
1512
- .wd-article > div.mermaid {
1513
- margin: 1.25rem 0;
1514
- padding: 1rem;
1515
- overflow-x: auto;
1516
- text-align: center;
1517
- background: var(--wd-surface);
1518
- border: 1px solid var(--wd-border);
1519
- border-radius: 0.55rem;
1520
- }
1521
- .wd-article > div.mermaid svg {
1522
- display: inline-block;
1523
- max-width: 100%;
1524
- }
1525
- /* Only style links inside actual prose containers - excludes Card
1526
- (which is itself an <a>) and the prev/next nav links. */
1527
- .wd-article p a,
1528
- .wd-article li a,
1529
- .wd-article td a,
1530
- .wd-article blockquote a {
1531
- text-decoration: underline;
1532
- text-decoration-color: color-mix(in srgb, var(--wd-primary) 40%, transparent);
1533
- text-underline-offset: 2px;
1534
- }
1535
- .wd-article strong {
1536
- font-weight: 600;
1537
- }
1538
- .wd-article > h2 a[href^="#"],
1539
- .wd-article > h3 a[href^="#"],
1540
- .wd-article > h4 a[href^="#"] {
1541
- text-decoration: none;
1542
- }
1543
- .wd-heading-anchor {
1544
- display: inline-block;
1545
- margin-left: 0.5rem;
1546
- color: var(--wd-text-muted);
1547
- opacity: 0;
1548
- text-decoration: none;
1549
- font-weight: 400;
1550
- transition: opacity 0.1s ease;
1551
- }
1552
- .wd-article > h2:hover .wd-heading-anchor,
1553
- .wd-article > h3:hover .wd-heading-anchor,
1554
- .wd-article > h4:hover .wd-heading-anchor,
1555
- .wd-heading-anchor:focus {
1556
- opacity: 1;
1557
- }
1558
- /* RequestExample/ResponseExample.astro's own panels, and the
1559
- .wd-toc-col host initExamplePanels() (see the <script> above) docks
1560
- them into on desktop - is:global (this whole style block already
1561
- is) since .wd-toc-col itself is BaseLayout.astro's own markup, a
1562
- completely different component than this one. Widens .wd-toc-col
1563
- itself only while it actually contains a non-empty host - the same
1564
- :has() technique ApiReferencePanel.astro's own identical comment
1565
- already uses to widen it for its own markup, so a page with neither
1566
- feature keeps the narrower 230px default from base.css. */
1567
- .wd-toc-col:has(.wd-example-host:not(:empty)) {
1568
- width: 340px;
1569
- }
1570
- .wd-example-host {
1571
- position: sticky;
1572
- top: var(--wd-topbar-offset, 5rem);
1573
- max-height: calc(100vh - var(--wd-topbar-offset, 5rem));
1574
- overflow-y: auto;
1575
- padding: 1.5rem 0 1.5rem 0.5rem;
1576
- }
1577
- /* Spacing between multiple docked panels (e.g. Request above
1578
- Response) is this wrapper's own job only once docked - inline
1579
- (mobile, no-toc-column, or not-yet-docked), the wrapped
1580
- .wd-codegroup's own default margin already spaces stacked panels
1581
- out correctly, so adding a second margin here unscoped would just
1582
- double it up. */
1583
- .wd-example-host .wd-example-panel {
1584
- margin-bottom: 1.25rem;
1585
- }
1586
- .wd-example-host .wd-example-panel:last-child {
1587
- margin-bottom: 0;
1588
- }
1589
- .wd-example-host .wd-codegroup {
1590
- margin: 0;
1591
- }
1592
-
1593
- .wd-example-host .astro-code {
1594
- margin: 0;
1595
- border-radius: 0 0 0.55rem 0.55rem;
1596
- }
1597
- </style>
1
+ ---
2
+ import { getCollection, render, type CollectionEntry } from "astro:content";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import {
6
+ loadDocsConfig,
7
+ resolveSections,
8
+ resolveGlobalDropdowns,
9
+ findSectionIndexForSlug,
10
+ buildNavTree,
11
+ ancestorGroupsForSlug,
12
+ buildSelectors,
13
+ buildGlobalDropdowns,
14
+ fileIdForEntry,
15
+ normalizeEntryId,
16
+ flattenNav,
17
+ firstSlugOfNavigation,
18
+ mergeSeo,
19
+ contextMenuOptions,
20
+ resolveSiteUrl,
21
+ findAllPages,
22
+ resolveLandings,
23
+ landingSelectors,
24
+ } from "../lib/config";
25
+ import { writedocsTempDir } from "../lib/writedocs-temp-dir.js";
26
+ import { parseOpenApiRef } from "../lib/openapi-ref.js";
27
+ import { languageAlternates } from "../lib/item-pages.js";
28
+ import { wantsGeneratedCard, ogImagePath } from "../lib/og-image.js";
29
+ import BaseLayout from "../layout/BaseLayout.astro";
30
+ import Sidebar from "../layout/components/Sidebar.astro";
31
+ import TableOfContents from "../layout/components/TableOfContents.astro";
32
+ import Breadcrumbs from "../layout/components/Breadcrumbs.astro";
33
+ import CopyPageMenu from "../components/CopyPageMenu.astro";
34
+ import Callout from "../components/Callout.astro";
35
+ import Note from "../components/Note.astro";
36
+ import Info from "../components/Info.astro";
37
+ import Tip from "../components/Tip.astro";
38
+ import Warning from "../components/Warning.astro";
39
+ import Danger from "../components/Danger.astro";
40
+ import Card from "../components/Card.astro";
41
+ import CardGroup from "../components/CardGroup.astro";
42
+ import Tabs from "../components/Tabs.astro";
43
+ import Tab from "../components/Tab.astro";
44
+ import CodeGroup from "../components/CodeGroup.astro";
45
+ import Accordion from "../components/Accordion.astro";
46
+ import AccordionGroup from "../components/AccordionGroup.astro";
47
+ import Steps from "../components/Steps.astro";
48
+ import Step from "../components/Step.astro";
49
+ import Hint from "../components/Hint.astro";
50
+ import Image from "../components/Image.astro";
51
+ import Frame from "../components/Frame.astro";
52
+ import Video from "../components/Video.astro";
53
+ import Parameter from "../components/Parameter.astro";
54
+ import Expandable from "../components/Expandable.astro";
55
+ import Searchbar from "../components/Searchbar.astro";
56
+ import Badge from "../components/Badge.astro";
57
+ import Icon from "../components/Icon.astro";
58
+ import RequestExample from "../components/RequestExample.astro";
59
+ import ResponseExample from "../components/ResponseExample.astro";
60
+ import Check from "../components/Check.astro";
61
+ import ParamField from "../components/ParamField.astro";
62
+ import ResponseField from "../components/ResponseField.astro";
63
+ import Columns from "../components/Columns.astro";
64
+ import Column from "../components/Column.astro";
65
+ import CodeBlock from "../components/CodeBlock.astro";
66
+ import Tooltip from "../components/Tooltip.astro";
67
+ import Update from "../components/Update.astro";
68
+ import Tile from "../components/Tile.astro";
69
+ import Panel from "../components/Panel.astro";
70
+ import Prompt from "../components/Prompt.astro";
71
+ import View from "../components/View.astro";
72
+ import Visibility from "../components/Visibility.astro";
73
+ import { Tree, FileTree, Color, GitHub } from "../components/compound";
74
+ import ApiPlayground from "../components/ApiPlayground.astro";
75
+ import ApiReferencePanel from "../components/ApiReferencePanel.astro";
76
+ import { searchScope, sectionTrail, ALL_SCOPES } from "../lib/search-scope.js";
77
+ import { selectorPlacements } from "../lib/selector-placement.js";
78
+ import { spaceOf } from "../lib/hidden-sections.js";
79
+ import { navigationPageOrder } from "../lib/pages.js";
80
+ import { folderRedirects } from "../lib/folder-redirects.js";
81
+ import { oncePerBuild } from "../lib/build-memo.js";
82
+ // writedocs.json's `basePath` - the addresses below stay site addresses
83
+ // ("/guides/a/"); the base goes in where one is written (lib/site-base.ts).
84
+ import { siteHref } from "../lib/site-base";
85
+
86
+ // A page is hand-written (the `pages` collection, sourced from anywhere
87
+ // in the project - docs/ has no special status, see findAllPages() in
88
+ // lib/config.ts) or an auto-generated OpenAPI stub (the `generatedDocs`
89
+ // collection, sourced from writedocsTempDir()'s generated-docs/
90
+ // directory - see content.config.ts / generate-api-pages.js) - kept as two separate
91
+ // collections rather than one, since Astro's loader API has no supported
92
+ // way to point a single collection's glob() at more than one base
93
+ // directory without one's own cleanup pass deleting the other's entries
94
+ // (see content.config.ts's own comment on this). Both share the exact
95
+ // same schema, so every consumer below just treats them as one combined
96
+ // list.
97
+ //
98
+ // The two `getCollection()` calls below are inlined at each of their two
99
+ // call sites (getStaticPaths, and the component body further down)
100
+ // rather than factored into one shared top-level helper: Astro's
101
+ // getStaticPaths extraction (a separate bundling pass from the rest of
102
+ // the component - see the pathDescription comment further down for
103
+ // another instance of this) was observed to silently drop a top-level
104
+ // function declaration referenced from inside getStaticPaths, producing
105
+ // a raw "getAllDocsEntries is not defined" ReferenceError at build time
106
+ // instead of ever running. Keeping both call sites self-contained avoids
107
+ // relying on whatever static-analysis pass decides what counts as
108
+ // "used" by the extracted chunk.
109
+ //
110
+ // Each site also only calls getCollection('generatedDocs') when there's
111
+ // actually something in it (most sites have no OpenAPI groups - see
112
+ // generate-api-pages.js), rather than unconditionally calling it and
113
+ // letting content.config.ts's skipIfMissing() loader no-op internally:
114
+ // astro:content's own getCollection() logs "The collection ... does not
115
+ // exist or is empty" to the console whenever a collection ends up with
116
+ // zero registered entries, regardless of *why* it's empty - the data
117
+ // store has no supported way to mark a collection as "intentionally
118
+ // empty" short of writing at least one entry to it. Not calling
119
+ // getCollection() at all for an empty one sidesteps that warning at the
120
+ // source instead of trying to suppress it after the fact.
121
+ type DocsEntry = CollectionEntry<"pages"> | CollectionEntry<"generatedDocs">;
122
+
123
+ export async function getStaticPaths() {
124
+ const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
125
+ const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
126
+ const config = loadDocsConfig(contentDir);
127
+ const sections = resolveSections(config.navigation);
128
+ const hasGeneratedDocs = fs.existsSync(path.join(writedocsTempDir(contentDir), "generated-docs"));
129
+ const hasPages = findAllPages(contentDir).length > 0;
130
+ const [pagesEntries, generatedDocsEntries] = await Promise.all([
131
+ hasPages ? getCollection("pages") : Promise.resolve([]),
132
+ hasGeneratedDocs ? getCollection("generatedDocs") : Promise.resolve([]),
133
+ ]);
134
+ const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
135
+ // writedocs.json always references a page by its file id; `entry.id` is
136
+ // Astro's own resolved slug for it (the file-path default, or a
137
+ // frontmatter `slug` override it recognizes natively - see
138
+ // fileIdForEntry() in lib/config.ts) and is what the page is actually
139
+ // routed at. Keyed by file id so every navEntry.slug below finds its
140
+ // entry regardless of which one is in play.
141
+ const entryByFileId = new Map(entries.map((e) => [fileIdForEntry(contentDir, packageRoot, e), e]));
142
+
143
+ // "/" is only produced below when some page's *resolved* slug
144
+ // (entry.id) is literally "index" - the conventional home page (an
145
+ // index.mdx at the project root; a root-level index.mdx keeps file id
146
+ // "index" verbatim, since Astro's own default id computation only
147
+ // strips a trailing `/index` *segment*, which a single-segment root
148
+ // file doesn't have - see fileIdForEntry()'s own comment on this in
149
+ // lib/config.ts), or any page overriding its own slug to "index"/"/".
150
+ // Most navigations don't have such a page - Astro then warns "no
151
+ // matching static path was found for /" on every request. Rather than
152
+ // requiring every writedocs.json to name a page "index", synthesize a
153
+ // redirect-only route for "/" pointing at the site's first real page
154
+ // whenever nothing already claims root.
155
+ // Checked against every entry, not just nav-referenced ones - a hidden
156
+ // page (see hiddenRoutes below) sitting at "index" claims root exactly
157
+ // as well as a nav-listed one would, and needs to suppress the synthetic
158
+ // redirect below the same way (two routes both wanting `params.slug:
159
+ // undefined` is a build error, not a silent pick-one).
160
+ const rootAlreadyClaimed = entries.some((e) => normalizeEntryId(e.id) === "index");
161
+ const firstSlug = rootAlreadyClaimed ? null : firstSlugOfNavigation(config.navigation);
162
+ const firstEntry = firstSlug ? entryByFileId.get(firstSlug) : undefined;
163
+ // Not calling the top-level hrefForSlug() here: it's only otherwise
164
+ // referenced from the component body, not from inside getStaticPaths,
165
+ // and per the describeSectionPath lesson above, closures introduced
166
+ // into getStaticPaths should be self-contained rather than assume a
167
+ // module-level binding survives Astro's bundling extraction. firstEntry
168
+ // can never resolve to "index" here (that's exactly what
169
+ // rootAlreadyClaimed rules out), so the ternary below always resolves
170
+ // to the non-root branch.
171
+ const rootRedirect = firstEntry
172
+ ? [{ params: { slug: undefined }, props: { redirectTo: `/${normalizeEntryId(firstEntry.id)}/`, temporary: true } }]
173
+ : [];
174
+
175
+ // Tracks every file id a nav-driven route below already claims, so
176
+ // hiddenRoutes (further down) knows which entries are left over - any
177
+ // page/generatedDocs entry that exists (findAllPages() already required
178
+ // it to have frontmatter with a `title` - see content.config.ts's
179
+ // docsSchema) but isn't reachable by walking writedocs.json's navigation at
180
+ // all. Those still get routed here, just without a nav-derived
181
+ // prev/next or section - a page doesn't have to be in the sidebar to be
182
+ // a real, directly-linkable page (an in-progress draft, an unlisted
183
+ // landing page, etc.).
184
+ const claimedFileIds = new Set<string>();
185
+
186
+ const pageRoutes = sections.flatMap((section, sectionIndex) => {
187
+ const flatNav = flattenNav(section.pages);
188
+ // Prev/next skip pages that aren't in the sidebar (frontmatter
189
+ // `hidden`) or aren't pages at all (frontmatter `url`, an external
190
+ // link) - the reader should land on the next page they could also
191
+ // have clicked in the sidebar. Inlined for the same reason as the
192
+ // error branch below.
193
+ const isPaginationStop = (slug: string) => {
194
+ const data = entryByFileId.get(slug)?.data;
195
+ return Boolean(data) && !data!.hidden && !data!.url;
196
+ };
197
+ return flatNav.map((navEntry, i) => {
198
+ const entry = entryByFileId.get(navEntry.slug);
199
+ if (!entry) {
200
+ // Inlined rather than a separate top-level helper: Astro's
201
+ // getStaticPaths extraction (a separate bundling pass from the
202
+ // rest of the component) was observed to silently drop a
203
+ // top-level function declaration that's only referenced inside
204
+ // this rarely-taken branch, producing a raw "X is not defined"
205
+ // ReferenceError instead of this readable message. Keeping the
206
+ // logic inside getStaticPaths' own closure avoids relying on
207
+ // whatever static-analysis pass decides what counts as "used".
208
+ const pathDescription =
209
+ section.path.length === 0
210
+ ? "(root)"
211
+ : section.path
212
+ .map((seg) => {
213
+ const item = seg.items[seg.index] as Record<string, unknown>;
214
+ const name = (item.tab ?? item.version ?? item.language ?? item.dropdown ?? item.product) as string;
215
+ return `${seg.kind} "${name}"`;
216
+ })
217
+ .join(" > ");
218
+ throw new Error(
219
+ `[writedocs] writedocs.json references page "${navEntry.slug}"` +
220
+ ` (${pathDescription})` +
221
+ ` but no matching file was found`,
222
+ );
223
+ }
224
+ claimedFileIds.add(navEntry.slug);
225
+ const prev = flatNav.slice(0, i).findLast((e) => isPaginationStop(e.slug)) ?? null;
226
+ const next = flatNav.slice(i + 1).find((e) => isPaginationStop(e.slug)) ?? null;
227
+ const urlSlug = normalizeEntryId(entry.id);
228
+ // A frontmatter `url` page (Mintlify's external link) exists only
229
+ // to put that link in the sidebar - its own URL redirects there.
230
+ if (entry.data.url) {
231
+ return {
232
+ params: { slug: urlSlug === "index" ? undefined : urlSlug },
233
+ props: { redirectTo: entry.data.url },
234
+ };
235
+ }
236
+ return {
237
+ params: { slug: urlSlug === "index" ? undefined : urlSlug },
238
+ props: { entry, prev, next, sectionIndex },
239
+ };
240
+ });
241
+ });
242
+
243
+ // An item's own page (a tab's, a dropdown's, ... `page` - resolveLandings()
244
+ // in lib/config.ts) that no sidebar lists: shown inside its item. One the
245
+ // sidebar does list was routed above, in its sidebar. Its Next is the
246
+ // item's first sidebar page, if the item has a sidebar of its own.
247
+ const landings = resolveLandings(config.navigation);
248
+ const landingRoutes = landings.flatMap((landing, landingIndex) => {
249
+ if (claimedFileIds.has(landing.slug)) return [];
250
+ const entry = entryByFileId.get(landing.slug);
251
+ if (!entry) {
252
+ const last = landing.path[landing.path.length - 1];
253
+ const item = landing.item as Record<string, unknown>;
254
+ const name = (item.tab ?? item.version ?? item.language ?? item.dropdown ?? item.product) as string;
255
+ throw new Error(
256
+ `[writedocs] writedocs.json's ${last.kind} "${name}" names page "${landing.slug}" as its own page,` +
257
+ ` but no matching file was found`,
258
+ );
259
+ }
260
+ claimedFileIds.add(landing.slug);
261
+ const next =
262
+ flattenNav(landing.pages).find((e) => {
263
+ const data = entryByFileId.get(e.slug)?.data;
264
+ return Boolean(data) && !data!.hidden && !data!.url;
265
+ }) ?? null;
266
+ const urlSlug = normalizeEntryId(entry.id);
267
+ if (entry.data.url) {
268
+ return [{ params: { slug: urlSlug === "index" ? undefined : urlSlug }, props: { redirectTo: entry.data.url } }];
269
+ }
270
+ return [{ params: { slug: urlSlug === "index" ? undefined : urlSlug }, props: { entry, prev: null, next, landingIndex } }];
271
+ });
272
+
273
+ // "Hidden" pages: any file the `pages`/`generatedDocs` collections
274
+ // picked up that writedocs.json's navigation never references (see
275
+ // claimedFileIds above) still gets a real route here - just with no
276
+ // prev/next (nothing in nav to derive that from) and no section of its
277
+ // own to be "active" in. findSectionIndexForSlug's existing "0 if this
278
+ // slug isn't in any section" fallback (already used nowhere else in
279
+ // this file, but built for exactly this) picks which section's
280
+ // sidebar/selectors a hidden page borrows - arbitrary, but no worse
281
+ // than the alternative of hidden pages having no chrome at all.
282
+ const hiddenRoutes = entries
283
+ .filter((entry) => !claimedFileIds.has(fileIdForEntry(contentDir, packageRoot, entry)))
284
+ .map((entry) => {
285
+ const urlSlug = normalizeEntryId(entry.id);
286
+ return {
287
+ params: { slug: urlSlug === "index" ? undefined : urlSlug },
288
+ props: {
289
+ entry,
290
+ prev: null,
291
+ next: null,
292
+ sectionIndex: findSectionIndexForSlug(sections, fileIdForEntry(contentDir, packageRoot, entry)),
293
+ isHidden: true,
294
+ },
295
+ };
296
+ });
297
+
298
+ // Folder addresses with pages under them but none of their own
299
+ // (`/docs/creator/`) redirect to the first page under them
300
+ // (lib/folder-redirects.js). Preferred in the reader's order: navigation
301
+ // order, public sections before hidden ones, pages outside the
302
+ // navigation last.
303
+ const slugOf = (route: { params: { slug?: string } }) => route.params.slug ?? "index";
304
+ const inHiddenSection = sections.map((section) => spaceOf(section.path) !== null);
305
+ const contentRoutes = pageRoutes.filter((route) => !("redirectTo" in route.props));
306
+ // An item's own page counts where the navigation names it: before the
307
+ // item's sidebar (navigationPageOrder()), so `/guides/` opens the Guides
308
+ // tab's own page rather than its first sidebar page.
309
+ type ContentRoute = { params: { slug?: string }; props: { entry?: DocsEntry; sectionIndex?: number; landingIndex?: number } };
310
+ const navOrder = new Map(navigationPageOrder(config.navigation).map((id, i) => [id, i]));
311
+ const orderOf = (route: ContentRoute) => navOrder.get(fileIdForEntry(contentDir, packageRoot, route.props.entry!)) ?? Infinity;
312
+ const inHiddenItem = (route: ContentRoute) =>
313
+ route.props.landingIndex !== undefined
314
+ ? spaceOf(landings[route.props.landingIndex].path) !== null
315
+ : inHiddenSection[route.props.sectionIndex!];
316
+ const navContent = [...contentRoutes, ...landingRoutes.filter((route) => !("redirectTo" in route.props))] as ContentRoute[];
317
+ const folderTargets = [
318
+ ...navContent.filter((route) => !inHiddenItem(route)).sort((a, b) => orderOf(a) - orderOf(b)).map(slugOf),
319
+ ...navContent.filter(inHiddenItem).sort((a, b) => orderOf(a) - orderOf(b)).map(slugOf),
320
+ ...hiddenRoutes.map(slugOf),
321
+ ];
322
+ const takenAddresses = new Set([
323
+ ...[...pageRoutes, ...landingRoutes, ...hiddenRoutes].map(slugOf),
324
+ ...(config.redirects ?? []).map((r) => r.source.replace(/^\/+|\/+$/g, "")),
325
+ ]);
326
+ const folderRoutes = [...folderRedirects(folderTargets, takenAddresses)].map(([folder, target]) => ({
327
+ params: { slug: folder },
328
+ props: { redirectTo: `/${target}/`, temporary: true },
329
+ }));
330
+
331
+ return [...rootRedirect, ...pageRoutes, ...landingRoutes, ...hiddenRoutes, ...folderRoutes];
332
+ }
333
+
334
+ interface Props {
335
+ redirectTo?: string;
336
+ // The automatic "/" and folder redirects: temporary, see below.
337
+ temporary?: boolean;
338
+ entry?: DocsEntry;
339
+ prev?: { slug: string; group: string | null } | null;
340
+ next?: { slug: string; group: string | null } | null;
341
+ sectionIndex?: number;
342
+ // Set by hiddenRoutes in getStaticPaths above - a page with no place in
343
+ // writedocs.json's navigation has no sidebar section of its own to show, so
344
+ // its default mode drops the sidebar entirely (see pageMode below)
345
+ // rather than borrowing findSectionIndexForSlug's arbitrary fallback
346
+ // section's sidebar contents, which would misleadingly suggest the page
347
+ // belongs there.
348
+ isHidden?: boolean;
349
+ // Set by landingRoutes in getStaticPaths above - an item's own page that
350
+ // no sidebar lists, shown inside that item (index into resolveLandings()).
351
+ landingIndex?: number;
352
+ }
353
+
354
+ const rawProps = Astro.props as Props;
355
+ if (rawProps.redirectTo) {
356
+ // The automatic "/" redirect is temporary (302): its target is just the
357
+ // navigation's first page, and it goes away once the site has a page at
358
+ // "/". A 301 is remembered by the browser for good - after that, "/" kept
359
+ // redirecting even with a home page in place, in `writedocs dev` (every
360
+ // project's preview shares localhost:4321) and for returning visitors.
361
+ // A frontmatter `url` page stays 301. In a static build the status only
362
+ // picks the refresh delay of Astro's redirect page, and the build rewrites
363
+ // those pages to redirect at once either way (rewrite-redirect-pages.js).
364
+ return Astro.redirect(siteHref(rawProps.redirectTo), rawProps.temporary ? 302 : 301);
365
+ }
366
+ const {
367
+ entry,
368
+ prev = null,
369
+ next = null,
370
+ sectionIndex = 0,
371
+ isHidden = false,
372
+ landingIndex,
373
+ } = rawProps as Required<Props>;
374
+
375
+ const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
376
+ const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
377
+ const config = loadDocsConfig(contentDir);
378
+ // Once per build, like the lookup tables further down.
379
+ const sections = oncePerBuild("slug:sections", () => resolveSections(config.navigation));
380
+ // Falls back to an empty stand-in section rather than crashing on
381
+ // `.pages` below - only reachable for a hidden page (see hiddenRoutes in
382
+ // getStaticPaths above) on a site whose writedocs.json has no navigation
383
+ // sections at all, which previously could never produce a route to
384
+ // render in the first place.
385
+ // An item's own page shown inside its item (landingRoutes above): the item's
386
+ // path, and its own sidebar if it has one.
387
+ const landing = landingIndex === undefined ? undefined : oncePerBuild("slug:landings", () => resolveLandings(config.navigation))[landingIndex];
388
+ const activeSection = landing ? { pages: landing.pages, path: landing.path } : sections[sectionIndex] ?? { pages: [], path: [] };
389
+
390
+ const { Content, headings } = await render(entry);
391
+ const tocHeadings = headings.filter((h) => h.depth === 2 || h.depth === 3);
392
+
393
+ // The lookup tables below are the same for every page, so a build makes
394
+ // them once (oncePerBuild(), lib/build-memo.js) - findAllPages() alone reads
395
+ // every page file of the project, and ran here once per page. In
396
+ // `writedocs dev` they're made again on every request, as before.
397
+ const { titleByFileId, navTitleByFileId, entryByFileId, methodByFileId } = await oncePerBuild("slug:lookups", async () => {
398
+ const hasGeneratedDocs = fs.existsSync(path.join(writedocsTempDir(contentDir), "generated-docs"));
399
+ const hasPages = findAllPages(contentDir).length > 0;
400
+ const [pagesEntries, generatedDocsEntries] = await Promise.all([
401
+ hasPages ? getCollection("pages") : Promise.resolve([]),
402
+ hasGeneratedDocs ? getCollection("generatedDocs") : Promise.resolve([]),
403
+ ]);
404
+ const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
405
+ // Two maps keyed by file id (not `entry.id` - see fileIdForEntry() in
406
+ // lib/config.ts for why those can differ once a page overrides its own
407
+ // slug): titles for prev/next and sidebar labels, and the entries
408
+ // themselves so hrefForSlug can resolve a writedocs.json file-id reference to
409
+ // wherever that page actually got routed.
410
+ const titleByFileId = new Map<string, string>();
411
+ // Navigation labels (sidebar, topbar dropdowns): a page's `sidebarTitle`
412
+ // when it has one - Mintlify's short nav label - else its `title`.
413
+ const navTitleByFileId = new Map<string, string>();
414
+ const entryByFileId = new Map<string, DocsEntry>();
415
+ // The HTTP method badge NavTree.astro shows next to an API operation
416
+ // page in the sidebar - read straight off the page's own `openapi:
417
+ // "METHOD /path"` frontmatter rather than the resolved operation JSON,
418
+ // since the method itself is right there in that string already and
419
+ // doesn't need a spec lookup.
420
+ const methodByFileId = new Map<string, string>();
421
+ for (const e of entries) {
422
+ const fileId = fileIdForEntry(contentDir, packageRoot, e);
423
+ titleByFileId.set(fileId, e.data.title);
424
+ navTitleByFileId.set(fileId, e.data.sidebarTitle ?? e.data.title);
425
+ entryByFileId.set(fileId, e);
426
+ // `hideApiMarker` (Mintlify's) drops the badge for this one page.
427
+ const apiRef = parseOpenApiRef(e.data.openapi);
428
+ if (apiRef && !e.data.hideApiMarker) {
429
+ methodByFileId.set(fileId, apiRef.method);
430
+ }
431
+ }
432
+ return { titleByFileId, navTitleByFileId, entryByFileId, methodByFileId };
433
+ });
434
+ const titleForSlug = (slug: string) => titleByFileId.get(slug) ?? slug;
435
+ const navTitleForSlug = (slug: string) => navTitleByFileId.get(slug) ?? slug;
436
+ const methodForSlug = (slug: string) => methodByFileId.get(slug) ?? null;
437
+ // Frontmatter that changes how a page appears in navigation (hidden, url,
438
+ // icon, tag, deprecated) - see buildNavTree() in lib/config.ts.
439
+ const navMetaForSlug = (slug: string) => entryByFileId.get(slug)?.data;
440
+ const hrefForSlug = (slug: string) => {
441
+ const raw = entryByFileId.get(slug)?.id ?? slug;
442
+ const effective = normalizeEntryId(raw);
443
+ return effective === "index" ? "/" : `/${effective}/`;
444
+ };
445
+ // The current page's own file id (as writedocs.json references it) - distinct
446
+ // from `entry.id` (its resolved URL slug) for the same reason as above,
447
+ // and what every "is this the active page" comparison below needs, since
448
+ // navTree/globalDropdowns are built from writedocs.json's file-id space.
449
+ const currentFileId = fileIdForEntry(contentDir, packageRoot, entry);
450
+ // A section's tree doesn't depend on which of its pages is open (NavTree.astro
451
+ // marks the current one), so it's built once per section in a build.
452
+ const navTree = oncePerBuild(`slug:nav:${landingIndex === undefined ? `s${sectionIndex}` : `l${landingIndex}`}`, () => buildNavTree(activeSection.pages, navTitleForSlug, methodForSlug, navMetaForSlug));
453
+ // The ancestor sidebar-group trail above the auto <h1> (Breadcrumbs.astro)
454
+ // - empty for a page sitting at the top level of its Section with no
455
+ // enclosing group, in which case [...slug].astro below skips rendering
456
+ // the component entirely rather than showing a breadcrumb bar with
457
+ // nothing in it but the page's own title.
458
+ const breadcrumbs = ancestorGroupsForSlug(navTree, currentFileId, hrefForSlug);
459
+
460
+ // The reader's page's own position within the active Section's flattened
461
+ // pages list - passed to buildSelectors() so a version/language switch
462
+ // can try to land on the *same* page in the target option instead of
463
+ // always its first page (equivalentPageIn() in lib/config.ts). -1 (not
464
+ // found) just disables that - firstSlugOf() is still the fallback.
465
+ const activePagePosition = flattenNav(activeSection.pages).findIndex((e) => e.slug === currentFileId);
466
+
467
+ // One selector per level of the active page's navigation path (tabs,
468
+ // versions, languages, products, or a dropdown nested partway down),
469
+ // plus the always-visible global dropdown list - see BaseLayout.astro
470
+ // for how each renders.
471
+ // An item's own page also gets the level under the item, with nothing chosen.
472
+ const selectors = landing ? landingSelectors(landing, hrefForSlug) : buildSelectors(activeSection.path, hrefForSlug, activePagePosition);
473
+ // <html lang>: the `language` of the navigation level this page sits under,
474
+ // if any. A hidden page has no level of its own (activeSection is only a
475
+ // fallback for its chrome), so it keeps the default.
476
+ // For search: the section line under this page's result (and words it can
477
+ // be found by), and the version/language/product it belongs to - search
478
+ // shows the reader's own first. A hidden page belongs to no section.
479
+ const pageSearchScope = isHidden ? { key: ALL_SCOPES, label: "" } : searchScope(activeSection.path);
480
+ const pageSectionTrail = isHidden ? "" : sectionTrail(activeSection.path, breadcrumbs);
481
+ // A page under a hidden navigation item searches its own index, not the
482
+ // site's (lib/hidden-sections.js, cli/run-pagefind.js).
483
+ const pageSearchSpace = isHidden ? null : spaceOf(activeSection.path);
484
+ const languageSegment = isHidden ? undefined : activeSection.path.find((segment) => segment.kind === "language");
485
+ const pageLang = languageSegment ? (languageSegment.items[languageSegment.index] as { language: string }).language : undefined;
486
+ const globalDropdowns = buildGlobalDropdowns(
487
+ resolveGlobalDropdowns(config.navigation),
488
+ currentFileId,
489
+ navTitleForSlug,
490
+ hrefForSlug,
491
+ navMetaForSlug,
492
+ );
493
+
494
+ // Meta tags: this page's own frontmatter `seo` overrides writedocs.json's
495
+ // site-wide `seo` field by field (mergeSeo() in lib/config.ts), and the
496
+ // canonical/OG/Twitter URLs need this page's actual served path - reusing
497
+ // hrefForSlug (already built above for prev/next and the sidebar) rather
498
+ // than recomputing it, since it already encodes the same
499
+ // frontmatter-slug-override-aware routing logic.
500
+ const pageSeo = mergeSeo(config.seo, entry.data.seo);
501
+ // A page with no picture of its own for link previews gets the generated
502
+ // card (lib/og-image.js, served by src/pages/og/[...slug].png.ts).
503
+ if (wantsGeneratedCard(pageSeo, entry.data, config.seo)) pageSeo.ogImage = ogImagePath(normalizeEntryId(entry.id));
504
+ const currentPath = hrefForSlug(currentFileId);
505
+ // This page in each language, for hreflang (languageAlternates() in
506
+ // lib/item-pages.js) - a hidden page belongs to no language level.
507
+ const alternates = isHidden
508
+ ? []
509
+ : languageAlternates(activeSection.path, currentFileId, activeSection.pages, landing !== undefined).map((a) => ({
510
+ lang: a.lang,
511
+ href: hrefForSlug(a.slug),
512
+ }));
513
+ // The trail for the page's structured data (lib/json-ld.js): home, the
514
+ // groups above the page that have a page of their own, the page.
515
+ const structuredTrail = [
516
+ { name: config.name, href: "/" },
517
+ ...breadcrumbs.filter((crumb) => crumb.href).map((crumb) => ({ name: crumb.label, href: crumb.href as string })),
518
+ ...(currentPath === "/" ? [] : [{ name: entry.data.title, href: currentPath }]),
519
+ ];
520
+
521
+ // Page mode (content.config.ts's docsSchema `mode` field, defaulted to
522
+ // 'default' there so this is never actually undefined) - see
523
+ // BaseLayout.astro for what each value strips out of the topbar/shell,
524
+ // and the comment on <BaseLayout mode=...> below for what this file
525
+ // itself controls (which slots get filled at all, and how the article
526
+ // itself renders).
527
+ // A hidden page (isHidden - see hiddenRoutes/Props above) defaults to
528
+ // "frame" instead of "default": it has no real section of its own, so
529
+ // the sidebar would otherwise show findSectionIndexForSlug's arbitrary
530
+ // fallback section with nothing in it actually active - "frame" drops
531
+ // the sidebar (and ToC) while keeping the topbar and normal article
532
+ // styling. Only a *default*: a hidden page's own frontmatter mode, if
533
+ // it set one explicitly, still wins.
534
+ // An item's own page with nothing for a sidebar - the item holds tabs, or
535
+ // versions, ... that switch elsewhere - is laid out the same way.
536
+ const landingWithoutSidebar =
537
+ landing !== undefined &&
538
+ flattenNav(landing.pages).length === 0 &&
539
+ !selectorPlacements(selectors, { sidebar: true }).includes("sidebar");
540
+ const pageMode = (isHidden || landingWithoutSidebar) && entry.data.mode === "default" ? "frame" : entry.data.mode;
541
+ const showSidebar = pageMode === "default" || pageMode === "wide";
542
+ // Products inside a tab or dropdown switch at the top of the sidebar, not in
543
+ // the top bar (lib/selector-placement.js - TopBar.astro applies the same rule).
544
+ const sidebarPlacements = selectorPlacements(selectors, { sidebar: showSidebar });
545
+ const sidebarSwitchers = selectors.filter((_, i) => sidebarPlacements[i] === "sidebar");
546
+ const showToc = pageMode === "default";
547
+ // 'custom' and 'blank' both get the bare wd-canvas treatment below (no
548
+ // auto <h1>, no prev/next, no prose width/padding) - they only differ in
549
+ // whether BaseLayout keeps the topbar, which is BaseLayout's own concern
550
+ // (mode is passed straight through), not something this file needs to
551
+ // branch on separately.
552
+ const isCanvasMode = pageMode === "custom" || pageMode === "blank";
553
+
554
+ // The "Copy page" menu (CopyPageMenu.astro) - on by default, with the
555
+ // options writedocs.json's `contextMenu` leaves on (contextMenuOptions() in
556
+ // lib/config-schema.ts; `false` turns it off), and only
557
+ // shown where there's a real auto-rendered <h1> to sit next to: canvas
558
+ // mode pages (custom/blank) have no such header (a hand-built landing
559
+ // page controls its own layout, there's nothing standard to anchor the
560
+ // menu to), and OpenAPI operation pages render almost entirely from the
561
+ // spec rather than prose - see [...slug].md.ts's own comment on why
562
+ // those are excluded from the .md route this menu links to in the first
563
+ // place, which this mirrors on the UI side.
564
+ const contextMenuItems = contextMenuOptions(config.contextMenu, { mcp: config.mcp });
565
+ const showCopyPageMenu = contextMenuItems.length > 0 && !isCanvasMode;
566
+ const siteUrl = resolveSiteUrl(config);
567
+
568
+ const components = {
569
+ Callout,
570
+ Note,
571
+ Info,
572
+ Tip,
573
+ Warning,
574
+ Danger,
575
+ Card,
576
+ CardGroup,
577
+ Tabs,
578
+ Tab,
579
+ CodeGroup,
580
+ Accordion,
581
+ AccordionGroup,
582
+ Steps,
583
+ Step,
584
+ Hint,
585
+ Image,
586
+ Frame,
587
+ Video,
588
+ Parameter,
589
+ Expandable,
590
+ Searchbar,
591
+ Badge,
592
+ Icon,
593
+ RequestExample,
594
+ ResponseExample,
595
+ Check,
596
+ ParamField,
597
+ ResponseField,
598
+ Columns,
599
+ Column,
600
+ CodeBlock,
601
+ Tooltip,
602
+ Update,
603
+ Tile,
604
+ Panel,
605
+ Prompt,
606
+ View,
607
+ Visibility,
608
+ Tree,
609
+ FileTree,
610
+ Color,
611
+ GitHub,
612
+ };
613
+ ---
614
+
615
+ <BaseLayout
616
+ config={config}
617
+ title={entry.data.title}
618
+ description={entry.data.description}
619
+ path={currentPath}
620
+ seo={pageSeo}
621
+ selectors={selectors}
622
+ globalDropdowns={globalDropdowns}
623
+ mode={pageMode}
624
+ lang={pageLang}
625
+ alternates={alternates}
626
+ breadcrumbs={structuredTrail}
627
+ isApi={Boolean(entry.data.openapi)}
628
+ >
629
+ {showSidebar && <Sidebar slot="sidebar" navTree={navTree} hrefForSlug={hrefForSlug} currentSlug={currentFileId} switchers={sidebarSwitchers} />}
630
+ {
631
+ isCanvasMode ? (
632
+ // 'custom' and 'blank' both get this treatment: no auto <h1>, no
633
+ // prev/next nav, none of .wd-article's own prose max-width/padding -
634
+ // just the page's own MDX/component content, edge to edge. Still gets
635
+ // a data-pagefind-body wrapper so a hand-built page's own text is
636
+ // still searchable.
637
+ <div class="wd-canvas" data-pagefind-body>
638
+ <Content components={components} />
639
+ {entry.data.openapi && <ApiPlayground operation={entry.data.openapi} contentDir={contentDir} />}
640
+ {/* After the content: a result's excerpt shows the section only when
641
+ that's what matched. */}
642
+ <div hidden data-markdown-ignore data-wd-search-scope={pageSearchScope.key} data-wd-search-scope-label={pageSearchScope.label} data-wd-search-space={pageSearchSpace?.id} data-wd-search-public={pageSearchSpace?.searchPublic ? "true" : undefined} data-pagefind-filter={`scope:${pageSearchScope.key}`}>
643
+ {pageSectionTrail && <span data-pagefind-meta="section">{pageSectionTrail}</span>}
644
+ </div>
645
+ </div>
646
+ ) : (
647
+ <article class={`wd-article ${pageMode === "wide" ? "wd-article-wide" : ""}`} data-pagefind-body>
648
+ {breadcrumbs.length > 0 && <Breadcrumbs items={breadcrumbs} />}
649
+ <div class="wd-article-header">
650
+ {
651
+ // Frontmatter `deprecated` puts a label beside the <h1>, not in
652
+ // it - the <h1>'s text is the search index's page title.
653
+ entry.data.deprecated ? (
654
+ <div class="wd-article-title">
655
+ <h1 data-pagefind-meta="title">{entry.data.title}</h1>
656
+ <span class="wd-deprecated-badge">Deprecated</span>
657
+ </div>
658
+ ) : (
659
+ <h1 data-pagefind-meta="title">{entry.data.title}</h1>
660
+ )
661
+ }
662
+ {showCopyPageMenu && (
663
+ <CopyPageMenu currentPath={currentPath} siteUrl={siteUrl} siteName={config.name} options={contextMenuItems} />
664
+ )}
665
+ </div>
666
+ <Content components={components} />
667
+ {entry.data.openapi && <ApiPlayground operation={entry.data.openapi} contentDir={contentDir} />}
668
+ <div hidden data-markdown-ignore data-wd-search-scope={pageSearchScope.key} data-wd-search-scope-label={pageSearchScope.label} data-wd-search-space={pageSearchSpace?.id} data-wd-search-public={pageSearchSpace?.searchPublic ? "true" : undefined} data-pagefind-filter={`scope:${pageSearchScope.key}`}>
669
+ {pageSectionTrail && <span data-pagefind-meta="section">{pageSectionTrail}</span>}
670
+ </div>
671
+ {!entry.data.hideFooterPagination && (
672
+ <nav class="wd-prevnext" data-pagefind-ignore data-markdown-ignore>
673
+ {prev && (
674
+ <a class="wd-prevnext-card wd-prevnext-prev" href={siteHref(hrefForSlug(prev.slug))}>
675
+ <span class="wd-prevnext-row">
676
+ <svg
677
+ class="wd-prevnext-icon"
678
+ width="16"
679
+ height="16"
680
+ viewBox="0 0 24 24"
681
+ fill="none"
682
+ stroke="currentColor"
683
+ stroke-width="2"
684
+ stroke-linecap="round"
685
+ stroke-linejoin="round"
686
+ aria-hidden="true"
687
+ >
688
+ <line x1="19" y1="12" x2="5" y2="12" />
689
+ <polyline points="12 19 5 12 12 5" />
690
+ </svg>
691
+ <span class="wd-prevnext-label">Previous</span>
692
+ </span>
693
+ <span class="wd-prevnext-title">{titleForSlug(prev.slug)}</span>
694
+ </a>
695
+ )}
696
+ {next && (
697
+ <a class="wd-prevnext-card wd-prevnext-next" href={siteHref(hrefForSlug(next.slug))}>
698
+ <span class="wd-prevnext-row">
699
+ <span class="wd-prevnext-label">Next</span>
700
+ <svg
701
+ class="wd-prevnext-icon"
702
+ width="16"
703
+ height="16"
704
+ viewBox="0 0 24 24"
705
+ fill="none"
706
+ stroke="currentColor"
707
+ stroke-width="2"
708
+ stroke-linecap="round"
709
+ stroke-linejoin="round"
710
+ aria-hidden="true"
711
+ >
712
+ <line x1="5" y1="12" x2="19" y2="12" />
713
+ <polyline points="12 5 19 12 12 19" />
714
+ </svg>
715
+ </span>
716
+ <span class="wd-prevnext-title">{titleForSlug(next.slug)}</span>
717
+ </a>
718
+ )}
719
+ </nav>
720
+ )}
721
+ </article>
722
+ )
723
+ }
724
+ {
725
+ showToc &&
726
+ (entry.data.openapi ? (
727
+ <ApiReferencePanel slot="toc" operation={entry.data.openapi} contentDir={contentDir} />
728
+ ) : (
729
+ <TableOfContents slot="toc" headings={tocHeadings} />
730
+ ))
731
+ }
732
+ </BaseLayout>
733
+
734
+ <script>
735
+ import { mcpServerUrl, cursorInstallLink, vscodeInstallLink } from "../lib/mcp-links.js";
736
+ // writedocs.json's `basePath` ("" or "/docs", astro.config.mjs) - the MCP
737
+ // server is at the site's root, under it. Written as `__WD_BASE__ ? ... : ...`
738
+ // so a site without one gets the same code as before basePath existed.
739
+ declare const __WD_BASE__: string;
740
+
741
+ // Astro assigns every h2-h4 an id automatically, but doesn't add a
742
+ // clickable anchor next to it. rehype-autolink-headings can't be used
743
+ // for this directly: Astro's own heading-id rehype plugin always runs
744
+ // AFTER any user-supplied rehypePlugins in its pipeline, so a plugin
745
+ // that links existing ids never sees them. Adding the anchor client-side
746
+ // sidesteps that ordering constraint entirely.
747
+ function addHeadingAnchors(root: ParentNode) {
748
+ root
749
+ .querySelectorAll<HTMLElement>(".wd-article > h2[id], .wd-article > h3[id], .wd-article > h4[id]")
750
+ .forEach((heading) => {
751
+ if (heading.querySelector(".wd-heading-anchor")) return;
752
+ const anchor = document.createElement("a");
753
+ anchor.className = "wd-heading-anchor";
754
+ anchor.href = `#${heading.id}`;
755
+ anchor.setAttribute("aria-label", "Link to this section");
756
+ anchor.textContent = "#";
757
+ heading.appendChild(anchor);
758
+ });
759
+ }
760
+ addHeadingAnchors(document);
761
+ document.addEventListener("astro:page-load", () => addHeadingAnchors(document));
762
+
763
+ // Copy-to-clipboard button for every fenced (```) code block - the
764
+ // button itself is emitted at build time by codeBlockTransformer
765
+ // (astro.config.mjs / src/lib/shiki-code-block.js), wrapping each
766
+ // <pre> in a .wd-code-block container; this just wires up the click
767
+ // behavior client-side, same dataset-guarded init pattern as
768
+ // addHeadingAnchors above.
769
+ function initCodeCopyButtons(root: ParentNode) {
770
+ root.querySelectorAll<HTMLButtonElement>(".wd-code-copy-btn").forEach((btn) => {
771
+ if (btn.dataset.wdInit) return;
772
+ btn.dataset.wdInit = "true";
773
+ btn.addEventListener("click", async () => {
774
+ const pre = btn.closest(".wd-code-block")?.querySelector("pre");
775
+ if (!pre) return;
776
+ try {
777
+ await navigator.clipboard.writeText(pre.textContent ?? "");
778
+ } catch {
779
+ return; // clipboard unavailable (e.g. insecure context) - fail silently
780
+ }
781
+ btn.textContent = "✓";
782
+ btn.classList.add("wd-code-copied");
783
+ window.setTimeout(() => {
784
+ btn.textContent = "⧉";
785
+ btn.classList.remove("wd-code-copied");
786
+ }, 1500);
787
+ });
788
+ });
789
+ }
790
+ initCodeCopyButtons(document);
791
+ document.addEventListener("astro:page-load", () => initCodeCopyButtons(document));
792
+
793
+ // Clipboard-copy button for CopyPageMenu.astro's primary "Copy page"
794
+ // button (the split button's left half - the right half is just a
795
+ // .wd-dropdown-trigger caret, handled by BaseLayout's own
796
+ // initDropdowns()) - same dataset-guarded init pattern as
797
+ // initCodeCopyButtons above, but fetches its content from the button's
798
+ // own data-md-path (the [...slug].md.ts route for the current page -
799
+ // see CopyPageMenu.astro) rather than reading it from an
800
+ // already-rendered element on the page, since the raw Markdown source
801
+ // isn't otherwise present in the DOM anywhere (the rendered HTML
802
+ // content is not the same text).
803
+ function initCopyPageMenu(root: ParentNode) {
804
+ root.querySelectorAll<HTMLButtonElement>("button[data-copy-page]").forEach((btn) => {
805
+ if (btn.dataset.wdInit) return;
806
+ btn.dataset.wdInit = "true";
807
+ const label = btn.querySelector<HTMLElement>(".wd-copy-page-primary-label");
808
+ const originalLabel = label?.textContent ?? "Copy page";
809
+ btn.addEventListener("click", async () => {
810
+ const mdPath = btn.dataset.mdPath;
811
+ if (!mdPath) return;
812
+ try {
813
+ const res = await fetch(mdPath);
814
+ const text = await res.text();
815
+ await navigator.clipboard.writeText(text);
816
+ } catch {
817
+ return; // fetch/clipboard unavailable - fail silently, same as initCodeCopyButtons
818
+ }
819
+ btn.classList.add("wd-copy-page-copied");
820
+ if (label) label.textContent = "Copied!";
821
+ window.setTimeout(() => {
822
+ btn.classList.remove("wd-copy-page-copied");
823
+ if (label) label.textContent = originalLabel;
824
+ }, 1500);
825
+ });
826
+ });
827
+ }
828
+ initCopyPageMenu(document);
829
+ document.addEventListener("astro:page-load", () => initCopyPageMenu(document));
830
+
831
+ // "Open in ChatGPT/Claude/Perplexity" on a site with no writedocs.json
832
+ // `domain`: the page's absolute .md URL isn't known at build time, so the
833
+ // link is completed here from the address the page is served from (see
834
+ // CopyPageMenu.astro) - same prompt the build writes when it does know.
835
+ function initAskLinks(root: ParentNode) {
836
+ root.querySelectorAll<HTMLAnchorElement>("a[data-ask-base][data-md-path]").forEach((link) => {
837
+ const url = new URL(link.dataset.mdPath ?? "/", window.location.origin).href;
838
+ link.href = link.dataset.askBase + encodeURIComponent(`Read ${url} so you can answer questions about it.`);
839
+ });
840
+ }
841
+ initAskLinks(document);
842
+ document.addEventListener("astro:page-load", () => initAskLinks(document));
843
+
844
+ // The menu's MCP options (CopyPageMenu.astro). "Copy MCP server URL"
845
+ // copies it and says so in its own label - inside the menu, which stays
846
+ // open to show it. "Connect to Cursor / VS Code" on a site with no
847
+ // `domain` get their install links here, for the address the page is
848
+ // served from.
849
+ function initMcpMenu(root: ParentNode) {
850
+ const serverUrl = (el: HTMLElement) => el.dataset.copyMcp || mcpServerUrl(__WD_BASE__ ? window.location.origin + __WD_BASE__ : window.location.origin);
851
+ root.querySelectorAll<HTMLButtonElement>("button[data-copy-mcp]").forEach((btn) => {
852
+ if (btn.dataset.wdInit) return;
853
+ btn.dataset.wdInit = "true";
854
+ const label = btn.querySelector<HTMLElement>(".wd-copy-page-item-title, .wd-copy-page-primary-label");
855
+ const originalLabel = label?.textContent ?? "";
856
+ btn.addEventListener("click", async (e) => {
857
+ e.stopPropagation();
858
+ try {
859
+ await navigator.clipboard.writeText(serverUrl(btn));
860
+ } catch {
861
+ return;
862
+ }
863
+ if (label) label.textContent = "Copied!";
864
+ window.setTimeout(() => {
865
+ if (label) label.textContent = originalLabel;
866
+ }, 1500);
867
+ });
868
+ });
869
+ root.querySelectorAll<HTMLAnchorElement>("a[data-mcp-install]").forEach((link) => {
870
+ const url = mcpServerUrl(__WD_BASE__ ? window.location.origin + __WD_BASE__ : window.location.origin);
871
+ const name = link.dataset.mcpName ?? document.title;
872
+ link.href = link.dataset.mcpInstall === "cursor" ? cursorInstallLink(name, url) : vscodeInstallLink(name, url);
873
+ });
874
+ }
875
+ initMcpMenu(document);
876
+ document.addEventListener("astro:page-load", () => initMcpMenu(document));
877
+
878
+ // Show more/less toggle for ```js expandable code blocks - same
879
+ // build-time-emitted-button + client-wired-click pattern as the copy
880
+ // button above; codeBlockTransformer only adds this button when the
881
+ // fence's meta string contains the `expandable` keyword.
882
+ function initCodeExpandButtons(root: ParentNode) {
883
+ root.querySelectorAll<HTMLButtonElement>(".wd-code-expand-btn").forEach((btn) => {
884
+ if (btn.dataset.wdInit) return;
885
+ btn.dataset.wdInit = "true";
886
+ btn.addEventListener("click", () => {
887
+ const block = btn.closest(".wd-code-expandable");
888
+ if (!block) return;
889
+ const expanded = block.classList.toggle("wd-code-expanded");
890
+ btn.textContent = expanded ? "Show less" : "Show more";
891
+ });
892
+ });
893
+ }
894
+ initCodeExpandButtons(document);
895
+ document.addEventListener("astro:page-load", () => initCodeExpandButtons(document));
896
+
897
+ // Renders ```mermaid fenced blocks - already reshaped at build time into
898
+ // plain <div class="mermaid">source text</div> containers (see
899
+ // rehypeMermaid in astro.config.mjs/src/lib/mermaid-rehype.js) - into
900
+ // actual SVG diagrams. Lazily imports the mermaid package itself, same
901
+ // reasoning as initSearch's Pagefind import above: most pages have no
902
+ // diagrams at all, no reason to ship/parse that bundle on every load.
903
+ let mermaidLoadPromise: Promise<typeof import("mermaid")> | null = null;
904
+ function ensureMermaid() {
905
+ if (!mermaidLoadPromise) mermaidLoadPromise = import("mermaid");
906
+ return mermaidLoadPromise;
907
+ }
908
+
909
+ // mermaid.run() replaces a block's contents with the rendered SVG,
910
+ // destroying the original diagram source - stashed in a data attribute
911
+ // the first time a block is seen (before it's ever rendered), so a
912
+ // later re-render (see the wd:theme-change listener below - diagrams
913
+ // are baked to static SVG at render time, so a theme change needs an
914
+ // actual re-render, unlike Shiki code blocks which swap colors live via
915
+ // CSS custom properties) has something to restore from.
916
+ function stashMermaidSource(root: ParentNode) {
917
+ root.querySelectorAll<HTMLElement>(".mermaid").forEach((el) => {
918
+ if (el.dataset.mermaidSource === undefined) el.dataset.mermaidSource = el.textContent ?? "";
919
+ });
920
+ }
921
+
922
+ async function renderMermaid(root: ParentNode, theme: "light" | "dark") {
923
+ const blocks = Array.from(root.querySelectorAll<HTMLElement>(".mermaid"));
924
+ if (blocks.length === 0) return;
925
+ const { default: mermaid } = await ensureMermaid();
926
+ mermaid.initialize({ startOnLoad: false, theme: theme === "dark" ? "dark" : "default", securityLevel: "strict" });
927
+ blocks.forEach((el) => {
928
+ el.removeAttribute("data-processed"); // mermaid's own re-render guard - see run()'s docs
929
+ el.innerHTML = el.dataset.mermaidSource ?? "";
930
+ });
931
+ // suppressErrors: a malformed diagram on one block shouldn't take
932
+ // down every other diagram on the page - mermaid still renders a
933
+ // per-block error SVG in place and logs details to the console.
934
+ await mermaid.run({ nodes: blocks, suppressErrors: true });
935
+ }
936
+
937
+ function initMermaid(root: ParentNode) {
938
+ stashMermaidSource(root);
939
+ if (!root.querySelector(".mermaid")) return;
940
+ const theme = document.documentElement.dataset.theme === "dark" ? "dark" : "light";
941
+ renderMermaid(root, theme);
942
+ }
943
+ initMermaid(document);
944
+ document.addEventListener("astro:page-load", () => initMermaid(document));
945
+ document.addEventListener("wd:theme-change", ((e: CustomEvent<{ theme: "light" | "dark" }>) => {
946
+ renderMermaid(document, e.detail.theme);
947
+ }) as EventListener);
948
+
949
+ // RequestExample/ResponseExample.astro's own docking behavior - on
950
+ // desktop, moves their rendered .wd-example-panel(s) out of the normal
951
+ // article flow and into .wd-toc-col (replacing whatever it would
952
+ // otherwise show - the heading-based TableOfContents or
953
+ // ApiReferencePanel, per those two components' own comment), matching
954
+ // Mintlify's stated behavior for the components this was modeled on:
955
+ // pinned in the sidebar on desktop, plain in-place code blocks below
956
+ // 1150px (the exact breakpoint .wd-toc-col itself disappears at - see
957
+ // base.css). This can't be done at build time: MDX compiles a page's
958
+ // whole body into one content flow, with no way for a static render to
959
+ // place part of that flow into a *different* column's own slot output
960
+ // - a client-side move after the fact is the only way to get this
961
+ // content into a sibling column's subtree at all.
962
+ function initExamplePanels(root: ParentNode) {
963
+ const tocCol = document.querySelector<HTMLElement>(".wd-toc-col");
964
+ if (!tocCol) return; // no toc column on this page (mode !== 'default') - nothing to dock into
965
+
966
+ // Top-level panels only: Mintlify's <Panel> (Panel.astro) is itself a
967
+ // .wd-example-panel, and a RequestExample/ResponseExample inside it
968
+ // moves with it rather than on its own.
969
+ const panels = Array.from(root.querySelectorAll<HTMLElement>(".wd-example-panel")).filter(
970
+ (panel) => !panel.parentElement?.closest(".wd-example-panel"),
971
+ );
972
+ if (panels.length === 0) return;
973
+ if (tocCol.dataset.wdExampleInit) return;
974
+ tocCol.dataset.wdExampleInit = "true";
975
+
976
+ // Response always docks below Request regardless of source order,
977
+ // matching Mintlify's own stated behavior for these two components.
978
+ panels.sort((a, b) => {
979
+ const rank = (el: HTMLElement) => (el.classList.contains("wd-request-example") ? 0 : 1);
980
+ return rank(a) - rank(b);
981
+ });
982
+
983
+ // A comment node marks each panel's original in-flow position, so
984
+ // undock() (a desktop -> mobile resize, or simply no matching media
985
+ // query at all) can put it back exactly where the article's own
986
+ // content expects it, rather than leaving a permanent gap.
987
+ const anchors = panels.map((panel) => {
988
+ const anchor = document.createComment("wd-example-anchor");
989
+ panel.before(anchor);
990
+ return anchor;
991
+ });
992
+
993
+ let host = tocCol.querySelector<HTMLElement>(".wd-example-host");
994
+ if (!host) {
995
+ host = document.createElement("div");
996
+ host.className = "wd-example-host";
997
+ tocCol.prepend(host);
998
+ }
999
+ const dockedHost = host;
1000
+
1001
+ // Whatever .wd-toc-col would otherwise render (TableOfContents' own
1002
+ // <nav class="wd-toc">, or ApiReferencePanel's own markup) - hidden
1003
+ // while panels are docked rather than removed, so undock() has
1004
+ // something to restore instead of needing to re-render it.
1005
+ const existingTocContent = Array.from(tocCol.children).filter((el) => el !== dockedHost) as HTMLElement[];
1006
+
1007
+ function dock() {
1008
+ existingTocContent.forEach((el) => (el.style.display = "none"));
1009
+ dockedHost.hidden = false;
1010
+ panels.forEach((panel) => dockedHost.appendChild(panel));
1011
+ }
1012
+ function undock() {
1013
+ dockedHost.hidden = true;
1014
+ existingTocContent.forEach((el) => (el.style.display = ""));
1015
+ panels.forEach((panel, i) => anchors[i].after(panel));
1016
+ }
1017
+ const desktopQuery = window.matchMedia("(min-width: 1151px)");
1018
+ const sync = () => (desktopQuery.matches ? dock() : undock());
1019
+ sync();
1020
+ desktopQuery.addEventListener("change", sync);
1021
+ }
1022
+ initExamplePanels(document);
1023
+ document.addEventListener("astro:page-load", () => initExamplePanels(document));
1024
+ </script>
1025
+
1026
+ <style>
1027
+ .wd-article {
1028
+ max-width: 900px;
1029
+ margin: 0 auto;
1030
+ /* Top padding matches Sidebar.astro's .wd-sidebar and
1031
+ TableOfContents.astro's .wd-toc exactly (both 1.5rem) - all three
1032
+ are siblings in the same .wd-shell row with no padding of their
1033
+ own on .wd-main-col in between, so this is what actually lines up
1034
+ the article's top edge with the sidebar/TOC's first item instead
1035
+ of starting visibly lower than both. */
1036
+ padding: 1.5rem 1.5rem 4rem;
1037
+ }
1038
+ /* frontmatter `mode: wide` - the table of contents column is gone (see
1039
+ BaseLayout.astro), so the article itself gets more room too, rather
1040
+ than just recentering the same 760px column into now-empty space. */
1041
+ .wd-article-wide {
1042
+ max-width: 1040px;
1043
+ }
1044
+ /* frontmatter `mode: custom` - no prose width/padding at all, no
1045
+ max-width, no centering: a hand-built landing page controls its own
1046
+ layout completely, full-bleed if it wants to. */
1047
+ .wd-canvas {
1048
+ width: 100%;
1049
+ }
1050
+ /* Wraps the auto-rendered <h1> together with CopyPageMenu (only
1051
+ rendered when writedocs.json's `contextMenu` isn't off - see
1052
+ showCopyPageMenu above) so the two sit on one row, menu pinned to
1053
+ the right. Always present (even with no menu) rather than only
1054
+ wrapping the <h1> conditionally, so the <h1>'s own top/bottom
1055
+ spacing comes from exactly one place regardless of whether the menu
1056
+ renders - flex items don't margin-collapse with their container the
1057
+ way a bare <h1> would with .wd-article, so that margin is
1058
+ reset/reapplied here instead of relying on the browser's default
1059
+ heading margin still doing the right thing once it's no longer a
1060
+ direct .wd-article child. */
1061
+ .wd-article-header {
1062
+ display: flex;
1063
+ flex-wrap: wrap;
1064
+ align-items: center;
1065
+ justify-content: space-between;
1066
+ gap: 0.75rem 1rem;
1067
+ margin: 0 0 1rem;
1068
+ }
1069
+ .wd-article-header h1 {
1070
+ margin: 0;
1071
+ /* A word longer than the whole line (a long product name on a phone)
1072
+ breaks rather than pushing the page wider than the screen. */
1073
+ overflow-wrap: break-word;
1074
+ }
1075
+ /* The title takes the room the menu leaves. Its basis is 0, so the row
1076
+ only wraps when its longest word and the menu can't share a line - on
1077
+ a desktop, a long title still wraps beside the menu; on a phone, a long
1078
+ word sends the menu below the title instead of off the screen. */
1079
+ .wd-article-header > h1,
1080
+ .wd-article-header > .wd-article-title {
1081
+ flex: 1 1 0;
1082
+ }
1083
+ /* Frontmatter `deprecated: true` (Mintlify's) - same amber as the
1084
+ sidebar's own deprecated tag (NavTree.astro) and Parameter's
1085
+ deprecated badge. */
1086
+ .wd-article-title {
1087
+ display: flex;
1088
+ align-items: center;
1089
+ flex-wrap: wrap;
1090
+ gap: 0.6rem;
1091
+ }
1092
+ .wd-deprecated-badge {
1093
+ display: inline-block;
1094
+ padding: 0.15rem 0.55rem;
1095
+ border-radius: 999px;
1096
+ font-size: 0.8rem;
1097
+ font-weight: 700;
1098
+ color: #d97706;
1099
+ background: color-mix(in srgb, #d97706 15%, transparent);
1100
+ }
1101
+ .wd-prevnext {
1102
+ display: flex;
1103
+ justify-content: space-between;
1104
+ margin-top: 3rem;
1105
+ padding-top: 1.5rem;
1106
+ border-top: 1px solid var(--wd-border);
1107
+ gap: 1rem;
1108
+ }
1109
+ /* Two side-by-side cards, each taking up to half the row - flex: 1 1
1110
+ 0 rather than a fixed 50% so a single remaining card (first page:
1111
+ only next, last page: only prev) grows to fill the width instead
1112
+ of leaving an empty gap next to it. */
1113
+ .wd-prevnext-card {
1114
+ display: flex;
1115
+ flex: 1 1 0;
1116
+ min-width: 0;
1117
+ flex-direction: column;
1118
+ gap: 0.1rem;
1119
+ padding: 0.75rem 1.1rem;
1120
+ border: 1px solid var(--wd-border);
1121
+ border-radius: 0.75rem;
1122
+ text-decoration: none;
1123
+ color: inherit;
1124
+ transition:
1125
+ border-color 0.15s ease,
1126
+ box-shadow 0.15s ease;
1127
+ }
1128
+ /* Both cards are identical at rest - the accent border/glow in the
1129
+ reference screenshot is that card's :hover state, not a permanent
1130
+ treatment on Next, so both wd-prevnext-prev and wd-prevnext-next
1131
+ share this one hover rule instead of Next getting its own always-on
1132
+ copy. Built from --wd-primary via color-mix() rather than a flat
1133
+ hardcoded color, so it stays correct under any theme's own accent. */
1134
+ .wd-prevnext-card:hover {
1135
+ border-color: var(--wd-primary);
1136
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--wd-primary) 10%, transparent);
1137
+ }
1138
+ .wd-prevnext-row {
1139
+ display: flex;
1140
+ align-items: center;
1141
+ justify-content: space-between;
1142
+ gap: 0.5rem;
1143
+ color: var(--wd-text-muted);
1144
+ font-size: 0.75rem;
1145
+ }
1146
+ .wd-prevnext-icon {
1147
+ flex-shrink: 0;
1148
+ color: var(--wd-text-muted);
1149
+ transition: color 0.15s ease;
1150
+ }
1151
+ .wd-prevnext-title {
1152
+ font-weight: 600;
1153
+ font-size: 0.85rem;
1154
+ color: var(--wd-heading);
1155
+ white-space: nowrap;
1156
+ overflow: hidden;
1157
+ text-overflow: ellipsis;
1158
+ transition: color 0.15s ease;
1159
+ }
1160
+ /* Previous's title sits at the same end of the card its own
1161
+ "Previous" label already does (right-aligned, next to the arrow's
1162
+ fixed spot on the left) - Next's title stays left-aligned, at the
1163
+ same end its own "Next" label sits. Keeps each card's two rows
1164
+ reading as one consistent left/right-anchored column instead of
1165
+ the title always defaulting to the left regardless of which side
1166
+ its card's own label/arrow occupy. */
1167
+ .wd-prevnext-prev .wd-prevnext-title {
1168
+ text-align: right;
1169
+ }
1170
+ /* Icon and title pick up the accent color on hover - the
1171
+ "Next"/"Previous" label itself stays muted even then, since it's a
1172
+ plain UI affordance rather than the actual content being pointed
1173
+ to. */
1174
+ .wd-prevnext-card:hover .wd-prevnext-icon,
1175
+ .wd-prevnext-card:hover .wd-prevnext-title {
1176
+ color: var(--wd-primary);
1177
+ }
1178
+ @media (width <= 640px) {
1179
+ .wd-prevnext {
1180
+ flex-direction: column;
1181
+ }
1182
+ }
1183
+ </style>
1184
+
1185
+ <style is:global>
1186
+ /*
1187
+ * These target direct children of .wd-article (or, for inline marks,
1188
+ * specific prose containers) rather than bare tag selectors. MDX
1189
+ * component internals (Card titles/links, prev/next nav links) also
1190
+ * live inside .wd-article but nested deeper - a bare ".wd-article h3"
1191
+ * or ".wd-article a" would win the specificity tie against those
1192
+ * components' own scoped styles and visibly break them (oversized
1193
+ * card titles, underlined cards, underlined prev/next links). Real
1194
+ * MDX content (headings, paragraphs, lists, etc.) renders as flat
1195
+ * direct children of .wd-article, so the ">" combinator is enough to
1196
+ * separate "actual content" from "component chrome" without needing
1197
+ * per-component :not() exceptions.
1198
+ */
1199
+ /* --wd-topbar-offset is set by initTopbarOffset() (src/scripts/
1200
+ topbar-offset.ts) to the sticky topbar's real measured height - see
1201
+ its own file comment for why a fixed 5rem (this var()'s own
1202
+ fallback, for the instant before that script's first measurement)
1203
+ isn't enough once a site's topbar grows a second row. Without this,
1204
+ jumping straight to a #heading link (a hard load, or clicking one of
1205
+ the .wd-heading-anchor links below) lands the heading partly hidden
1206
+ under the sticky topbar. */
1207
+ .wd-article > h2 {
1208
+ font-size: 1.5rem;
1209
+ margin: 2.75rem 0 1rem;
1210
+ padding-top: 0.25rem;
1211
+ scroll-margin-top: var(--wd-topbar-offset, 5rem);
1212
+ }
1213
+ .wd-article > h3 {
1214
+ font-size: 1.2rem;
1215
+ margin: 2rem 0 0.75rem;
1216
+ scroll-margin-top: var(--wd-topbar-offset, 5rem);
1217
+ }
1218
+ .wd-article > h4 {
1219
+ font-size: 1rem;
1220
+ margin: 1.5rem 0 0.5rem;
1221
+ scroll-margin-top: var(--wd-topbar-offset, 5rem);
1222
+ }
1223
+ .wd-article > h2:first-child,
1224
+ .wd-article > h3:first-child {
1225
+ margin-top: 0;
1226
+ }
1227
+ .wd-article > p {
1228
+ margin: 0.9rem 0;
1229
+ }
1230
+ .wd-article > ul,
1231
+ .wd-article > ol {
1232
+ margin: 0.9rem 0;
1233
+ padding-left: 1.4rem;
1234
+ }
1235
+ .wd-article li {
1236
+ margin: 0.35rem 0;
1237
+ }
1238
+ .wd-article li > ul,
1239
+ .wd-article li > ol {
1240
+ margin: 0.35rem 0;
1241
+ }
1242
+ .wd-article > blockquote {
1243
+ margin: 1.25rem 0;
1244
+ padding: 0.1rem 1rem;
1245
+ border-left: 3px solid var(--wd-primary);
1246
+ background: var(--wd-surface);
1247
+ border-radius: 0 0.4rem 0.4rem 0;
1248
+ color: var(--wd-text-muted);
1249
+ }
1250
+ .wd-article blockquote p {
1251
+ margin: 0.7rem 0;
1252
+ }
1253
+ .wd-article > table {
1254
+ width: 100%;
1255
+ border-collapse: collapse;
1256
+ margin: 1.25rem 0;
1257
+ font-size: 0.9rem;
1258
+ }
1259
+ .wd-article th,
1260
+ .wd-article td {
1261
+ text-align: left;
1262
+ padding: 0.55rem 0.75rem;
1263
+ border-bottom: 1px solid var(--wd-border);
1264
+ vertical-align: top;
1265
+ }
1266
+ .wd-article th {
1267
+ color: var(--wd-text-muted);
1268
+ font-weight: 600;
1269
+ font-size: 0.8rem;
1270
+ text-transform: uppercase;
1271
+ letter-spacing: 0.03em;
1272
+ }
1273
+ .wd-article > hr {
1274
+ border: none;
1275
+ border-top: 1px solid var(--wd-border);
1276
+ margin: 2.5rem 0;
1277
+ }
1278
+ /* Fenced (```) code blocks - codeBlockTransformer
1279
+ (src/lib/shiki-code-block.js) wraps every one's <pre> in this
1280
+ .wd-code-block div at build time (plus an optional .wd-code-title
1281
+ bar, and the copy/expand buttons - see below). The card-like chrome
1282
+ (border/radius/background) lives on the wrapper rather than the
1283
+ <pre> itself so a title bar, when present, can sit flush above it
1284
+ inside the same box; Astro's Shiki pipeline (dual light/dark themes
1285
+ configured in astro.config.mjs) already supplies the <pre>'s own
1286
+ background/text colors via inline styles. Matches both a standalone
1287
+ block (direct child of .wd-article) and one nested inside
1288
+ <CodeGroup> (which re-targets the margin/radius itself via its own
1289
+ more specific `.wd-codegroup > .wd-code-block` rule in
1290
+ CodeGroup.astro). */
1291
+ .wd-code-block {
1292
+ position: relative;
1293
+ margin: 1.25rem 0;
1294
+ border: 1px solid var(--wd-border);
1295
+ border-radius: 0.55rem;
1296
+ overflow: hidden;
1297
+ }
1298
+ .wd-article pre.astro-code {
1299
+ margin: 0;
1300
+ padding: 1rem 1.1rem;
1301
+ border: none;
1302
+ border-radius: 0;
1303
+ font-size: 0.85rem;
1304
+ line-height: 1.55;
1305
+ }
1306
+ .wd-code-title {
1307
+ padding: 0.5rem 1rem;
1308
+ font-family: monospace;
1309
+ font-size: 0.78rem;
1310
+ font-weight: 500;
1311
+ color: var(--wd-text-muted);
1312
+ background: var(--wd-surface);
1313
+ border-bottom: 1px solid var(--wd-border);
1314
+ }
1315
+ /* A fence's `icon="..."` (shiki-code-block.js) - the icon's own SVG
1316
+ arrives as a data URL in --wd-code-icon and is used as a mask, so it
1317
+ paints in the title's text color instead of the SVG's own fill. */
1318
+ .wd-code-title-icon {
1319
+ display: inline-block;
1320
+ width: 1em;
1321
+ height: 1em;
1322
+ margin-right: 0.45rem;
1323
+ vertical-align: -0.125em;
1324
+ background: currentColor;
1325
+ -webkit-mask: var(--wd-code-icon) center / contain no-repeat;
1326
+ mask: var(--wd-code-icon) center / contain no-repeat;
1327
+ }
1328
+ .wd-code-copy-btn {
1329
+ position: absolute;
1330
+ top: 0.6rem;
1331
+ right: 0.6rem;
1332
+ display: inline-flex;
1333
+ align-items: center;
1334
+ justify-content: center;
1335
+ width: 1.85rem;
1336
+ height: 1.85rem;
1337
+ padding: 0;
1338
+ border-radius: 0.4rem;
1339
+ border: 1px solid var(--wd-border);
1340
+ background: var(--wd-background);
1341
+ color: var(--wd-text-muted);
1342
+ font-size: 0.9rem;
1343
+ line-height: 1;
1344
+ cursor: pointer;
1345
+ opacity: 0;
1346
+ transition:
1347
+ opacity 0.15s ease,
1348
+ color 0.15s ease,
1349
+ background 0.15s ease,
1350
+ border-color 0.15s ease;
1351
+ }
1352
+ .wd-code-block:hover .wd-code-copy-btn,
1353
+ .wd-code-copy-btn:focus-visible {
1354
+ opacity: 1;
1355
+ }
1356
+ .wd-code-copy-btn:hover {
1357
+ color: var(--wd-text);
1358
+ background: var(--wd-surface);
1359
+ }
1360
+ .wd-code-copy-btn.wd-code-copied {
1361
+ opacity: 1;
1362
+ color: #16a34a;
1363
+ border-color: #16a34a;
1364
+ }
1365
+ /* ```js wrap - opts a single block into wrapping long lines instead
1366
+ of horizontal-scrolling (the default). */
1367
+ .wd-code-wrap pre.astro-code,
1368
+ .wd-code-wrap pre.astro-code code {
1369
+ white-space: pre-wrap;
1370
+ word-break: break-word;
1371
+ overflow-x: hidden;
1372
+ }
1373
+ /* ```js lines (or showLineNumbers) - a CSS-counter gutter, no markup
1374
+ needed beyond a class since every line is already its own .line
1375
+ span. */
1376
+ .wd-code-lines pre.astro-code code {
1377
+ counter-reset: wd-code-line;
1378
+ }
1379
+ .wd-code-lines pre.astro-code .line {
1380
+ counter-increment: wd-code-line;
1381
+ }
1382
+ .wd-code-lines pre.astro-code .line::before {
1383
+ content: counter(wd-code-line);
1384
+ display: inline-block;
1385
+ width: 1.8em;
1386
+ margin-right: 1em;
1387
+ text-align: right;
1388
+ color: var(--wd-text-muted);
1389
+ user-select: none;
1390
+ }
1391
+ /* ```js expandable - collapses to a fixed height with a "Show more"
1392
+ button below; toggled via .wd-code-expanded, added by the click
1393
+ handler in the <script> block below. */
1394
+ .wd-code-expandable pre.astro-code {
1395
+ max-height: 340px;
1396
+ overflow-y: hidden;
1397
+ }
1398
+ .wd-code-expandable.wd-code-expanded pre.astro-code {
1399
+ max-height: none;
1400
+ }
1401
+ .wd-code-expand-btn {
1402
+ display: block;
1403
+ width: 100%;
1404
+ padding: 0.5rem;
1405
+ border: none;
1406
+ border-top: 1px solid var(--wd-border);
1407
+ background: var(--wd-surface);
1408
+ color: var(--wd-primary);
1409
+ font-size: 0.8rem;
1410
+ font-weight: 500;
1411
+ cursor: pointer;
1412
+ }
1413
+ .wd-code-expand-btn:hover {
1414
+ background: color-mix(in srgb, var(--wd-primary) 8%, var(--wd-surface));
1415
+ }
1416
+ /* Line/word annotation classes added by the official
1417
+ @shikijs/transformers transformers configured alongside
1418
+ codeBlockTransformer in astro.config.mjs:
1419
+ .line.highlighted - transformerMetaHighlight
1420
+ (```js {1,3-5}) and
1421
+ transformerNotationHighlight
1422
+ (// [!code highlight]/[!code hl])
1423
+ .line.diff.add / .diff.remove - transformerNotationDiff
1424
+ (// [!code ++] / // [!code --])
1425
+ .line.error / .warning / .info - transformerNotationErrorLevel
1426
+ (// [!code error]/[!code warning])
1427
+ (also carries .highlighted)
1428
+ pre.has-focused, .line.focused - transformerNotationFocus
1429
+ (// [!code focus])
1430
+ .highlighted-word - transformerMetaWordHighlight
1431
+ (```js /someWord/) and
1432
+ transformerNotationWordHighlight
1433
+ (// [!code word:someWord])
1434
+ Every .line needs display:inline-block + full width for its
1435
+ highlight background to stretch edge-to-edge (by default a <span>
1436
+ only extends as wide as its own text) - harmless for plain lines,
1437
+ since inline-block with no other styling renders identically to
1438
+ the browser's normal inline flow here. */
1439
+ .astro-code .line {
1440
+ display: inline-block;
1441
+ width: 100%;
1442
+ }
1443
+ .astro-code .line.highlighted {
1444
+ background: color-mix(in srgb, var(--wd-primary) 12%, transparent);
1445
+ margin: 0 -1.1rem;
1446
+ padding: 0 1.1rem;
1447
+ width: calc(100% + 2.2rem);
1448
+ }
1449
+ .astro-code .line.diff {
1450
+ margin: 0 -1.1rem;
1451
+ padding: 0 1.1rem 0 1.6rem;
1452
+ width: calc(100% + 2.2rem);
1453
+ position: relative;
1454
+ }
1455
+ .astro-code .line.diff.add {
1456
+ background: color-mix(in srgb, #16a34a 15%, transparent);
1457
+ }
1458
+ .astro-code .line.diff.remove {
1459
+ background: color-mix(in srgb, #dc2626 15%, transparent);
1460
+ opacity: 0.85;
1461
+ }
1462
+ .astro-code .line.diff.add::before,
1463
+ .astro-code .line.diff.remove::before {
1464
+ position: absolute;
1465
+ left: 0.5rem;
1466
+ font-weight: 700;
1467
+ }
1468
+ .astro-code .line.diff.add::before {
1469
+ content: "+";
1470
+ color: #16a34a;
1471
+ }
1472
+ .astro-code .line.diff.remove::before {
1473
+ content: "-";
1474
+ color: #dc2626;
1475
+ }
1476
+ .astro-code .line.error {
1477
+ background: color-mix(in srgb, #dc2626 15%, transparent);
1478
+ }
1479
+ .astro-code .line.warning {
1480
+ background: color-mix(in srgb, #d97706 15%, transparent);
1481
+ }
1482
+ .astro-code .line.info {
1483
+ background: color-mix(in srgb, #2563eb 12%, transparent);
1484
+ }
1485
+ pre.astro-code.has-focused .line {
1486
+ opacity: 0.45;
1487
+ filter: blur(0.3px);
1488
+ transition:
1489
+ opacity 0.2s ease,
1490
+ filter 0.2s ease;
1491
+ }
1492
+ pre.astro-code.has-focused .line.focused {
1493
+ opacity: 1;
1494
+ filter: none;
1495
+ }
1496
+ pre.astro-code.has-focused:hover .line {
1497
+ opacity: 1;
1498
+ filter: none;
1499
+ }
1500
+ .astro-code .highlighted-word {
1501
+ background: color-mix(in srgb, var(--wd-primary) 20%, transparent);
1502
+ border-radius: 0.25rem;
1503
+ padding: 0.05rem 0.2rem;
1504
+ margin: -0.05rem -0.15rem;
1505
+ }
1506
+ .wd-article img {
1507
+ max-width: 100%;
1508
+ border-radius: 0.5rem;
1509
+ border: 1px solid var(--wd-border);
1510
+ }
1511
+ /* ```mermaid fenced blocks (rehypeMermaid in astro.config.mjs reshapes
1512
+ them into this plain <div class="mermaid"> container at build time -
1513
+ see mermaid-rehype.js) - mermaid.js (initMermaid() below) replaces
1514
+ the raw source text with a rendered <svg> in place, client-side.
1515
+ overflow-x: auto rather than shrinking the diagram, since a wide
1516
+ flowchart squeezed into the article's ~760px column becomes
1517
+ unreadable; centering only kicks in once the svg fits, via the
1518
+ inline-block + text-align combo below. */
1519
+ .wd-article > div.mermaid {
1520
+ margin: 1.25rem 0;
1521
+ padding: 1rem;
1522
+ overflow-x: auto;
1523
+ text-align: center;
1524
+ background: var(--wd-surface);
1525
+ border: 1px solid var(--wd-border);
1526
+ border-radius: 0.55rem;
1527
+ }
1528
+ .wd-article > div.mermaid svg {
1529
+ display: inline-block;
1530
+ max-width: 100%;
1531
+ }
1532
+ /* Only style links inside actual prose containers - excludes Card
1533
+ (which is itself an <a>) and the prev/next nav links. */
1534
+ .wd-article p a,
1535
+ .wd-article li a,
1536
+ .wd-article td a,
1537
+ .wd-article blockquote a {
1538
+ text-decoration: underline;
1539
+ text-decoration-color: color-mix(in srgb, var(--wd-primary) 40%, transparent);
1540
+ text-underline-offset: 2px;
1541
+ }
1542
+ .wd-article strong {
1543
+ font-weight: 600;
1544
+ }
1545
+ .wd-article > h2 a[href^="#"],
1546
+ .wd-article > h3 a[href^="#"],
1547
+ .wd-article > h4 a[href^="#"] {
1548
+ text-decoration: none;
1549
+ }
1550
+ .wd-heading-anchor {
1551
+ display: inline-block;
1552
+ margin-left: 0.5rem;
1553
+ color: var(--wd-text-muted);
1554
+ opacity: 0;
1555
+ text-decoration: none;
1556
+ font-weight: 400;
1557
+ transition: opacity 0.1s ease;
1558
+ }
1559
+ .wd-article > h2:hover .wd-heading-anchor,
1560
+ .wd-article > h3:hover .wd-heading-anchor,
1561
+ .wd-article > h4:hover .wd-heading-anchor,
1562
+ .wd-heading-anchor:focus {
1563
+ opacity: 1;
1564
+ }
1565
+ /* RequestExample/ResponseExample.astro's own panels, and the
1566
+ .wd-toc-col host initExamplePanels() (see the <script> above) docks
1567
+ them into on desktop - is:global (this whole style block already
1568
+ is) since .wd-toc-col itself is BaseLayout.astro's own markup, a
1569
+ completely different component than this one. Widens .wd-toc-col
1570
+ itself only while it actually contains a non-empty host - the same
1571
+ :has() technique ApiReferencePanel.astro's own identical comment
1572
+ already uses to widen it for its own markup, so a page with neither
1573
+ feature keeps the narrower 230px default from base.css. */
1574
+ .wd-toc-col:has(.wd-example-host:not(:empty)) {
1575
+ width: 340px;
1576
+ }
1577
+ .wd-example-host {
1578
+ position: sticky;
1579
+ top: var(--wd-topbar-offset, 5rem);
1580
+ max-height: calc(100vh - var(--wd-topbar-offset, 5rem));
1581
+ overflow-y: auto;
1582
+ padding: 1.5rem 0 1.5rem 0.5rem;
1583
+ }
1584
+ /* Spacing between multiple docked panels (e.g. Request above
1585
+ Response) is this wrapper's own job only once docked - inline
1586
+ (mobile, no-toc-column, or not-yet-docked), the wrapped
1587
+ .wd-codegroup's own default margin already spaces stacked panels
1588
+ out correctly, so adding a second margin here unscoped would just
1589
+ double it up. */
1590
+ .wd-example-host .wd-example-panel {
1591
+ margin-bottom: 1.25rem;
1592
+ }
1593
+ .wd-example-host .wd-example-panel:last-child {
1594
+ margin-bottom: 0;
1595
+ }
1596
+ .wd-example-host .wd-codegroup {
1597
+ margin: 0;
1598
+ }
1599
+
1600
+ .wd-example-host .astro-code {
1601
+ margin: 0;
1602
+ border-radius: 0 0 0.55rem 0.55rem;
1603
+ }
1604
+ </style>