@writedocs/generator 0.13.4 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +359 -356
  4. package/package.json +99 -99
  5. package/src/cli/base-path-layout.js +44 -44
  6. package/src/cli/build-auth.js +135 -135
  7. package/src/cli/build.js +223 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +124 -124
  10. package/src/cli/dev.js +269 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +509 -507
  13. package/src/cli/og-image-worker.js +20 -20
  14. package/src/cli/og-images.js +70 -70
  15. package/src/cli/page-list-watch.js +71 -69
  16. package/src/cli/run-astro.js +97 -97
  17. package/src/cli/run-pagefind.js +154 -154
  18. package/src/cli/write-mcp-files.js +103 -103
  19. package/src/cli/write-redirects-file.js +158 -158
  20. package/src/components/ApiReferencePanel.astro +1792 -1792
  21. package/src/components/AppIcon.astro +51 -51
  22. package/src/components/Card.astro +193 -193
  23. package/src/components/CodeGroup.astro +63 -39
  24. package/src/components/CopyPageMenu.astro +374 -374
  25. package/src/components/Hint.astro +188 -188
  26. package/src/components/Icon.astro +72 -72
  27. package/src/components/Image.astro +165 -165
  28. package/src/components/Tile.astro +67 -67
  29. package/src/components/Video.astro +137 -137
  30. package/src/content.config.ts +219 -203
  31. package/src/layout/BaseLayout.astro +908 -908
  32. package/src/layout/components/AnalyticsScripts.astro +49 -49
  33. package/src/layout/components/Breadcrumbs.astro +98 -98
  34. package/src/layout/components/ConsentBanner.astro +119 -119
  35. package/src/layout/components/MobileMenu.astro +225 -225
  36. package/src/layout/components/NavTree.astro +422 -408
  37. package/src/layout/components/Sidebar.astro +232 -232
  38. package/src/layout/components/SiteFooter.astro +87 -87
  39. package/src/layout/components/TopBar.astro +386 -386
  40. package/src/layout/styles/base.css +332 -326
  41. package/src/layout/styles/mobile-menu.css +285 -285
  42. package/src/lib/agent-markdown.js +164 -164
  43. package/src/lib/asset-dimensions.js +89 -89
  44. package/src/lib/base-path.js +90 -90
  45. package/src/lib/cli-report.js +22 -22
  46. package/src/lib/code-line-numbers.js +13 -0
  47. package/src/lib/config-schema.js +12 -1
  48. package/src/lib/config-schema.ts +2523 -2509
  49. package/src/lib/config.ts +1331 -1316
  50. package/src/lib/consent.js +108 -108
  51. package/src/lib/content-check.js +4 -1
  52. package/src/lib/content-store-reload-integration.js +101 -101
  53. package/src/lib/drafts.js +186 -0
  54. package/src/lib/icon-data-dev.js +53 -53
  55. package/src/lib/image-size.js +152 -152
  56. package/src/lib/json-schema-descriptions.js +228 -228
  57. package/src/lib/link-check.js +553 -544
  58. package/src/lib/llms-index.ts +90 -90
  59. package/src/lib/mcp-dev-integration.js +65 -65
  60. package/src/lib/mcp-index.ts +102 -102
  61. package/src/lib/mintlify-convert.js +605 -605
  62. package/src/lib/moved-api-pages.js +49 -49
  63. package/src/lib/og-cards.js +33 -33
  64. package/src/lib/og-image.js +235 -235
  65. package/src/lib/openapi-dev-status.js +80 -80
  66. package/src/lib/openapi-reload-integration.js +193 -193
  67. package/src/lib/pages.js +346 -312
  68. package/src/lib/project-files-integration.js +116 -116
  69. package/src/lib/project-files.js +137 -137
  70. package/src/lib/rehype-base-path.js +62 -62
  71. package/src/lib/rehype-image-loading.js +71 -71
  72. package/src/lib/robots-txt.js +21 -21
  73. package/src/lib/search-scope.js +44 -44
  74. package/src/lib/selector-placement.js +50 -50
  75. package/src/lib/seo-tags.js +157 -155
  76. package/src/lib/shiki-code-block.js +7 -1
  77. package/src/lib/site-base.ts +27 -27
  78. package/src/lib/styles-asset-integration.js +291 -291
  79. package/src/lib/wdignore-cases.json +195 -195
  80. package/src/lib/wdignore.js +177 -177
  81. package/src/pages/404.astro +63 -63
  82. package/src/pages/[...slug].astro +1773 -1608
  83. package/src/pages/[...slug].md.ts +93 -93
  84. package/src/pages/llms-full.txt.ts +88 -88
  85. package/src/pages/og/[...slug].png.ts +63 -63
  86. package/src/scripts/mobile-menu.ts +80 -80
  87. package/src/scripts/search.ts +245 -245
  88. package/src/scripts/sidebar-scroll.ts +61 -61
  89. package/src/styles/global.css +40 -40
package/astro.config.mjs CHANGED
@@ -1,645 +1,645 @@
1
- import { defineConfig } from 'astro/config';
2
- import mdx from '@astrojs/mdx';
3
- import react from '@astrojs/react';
4
- import icon from 'astro-icon';
5
- import sitemap from '@astrojs/sitemap';
6
- import tailwindcss from '@tailwindcss/vite';
7
- import path from 'node:path';
8
- import fs from 'node:fs';
9
- import { fileURLToPath } from 'node:url';
10
- import matter from 'gray-matter';
11
- import { unified } from '@astrojs/markdown-remark';
12
- import {
13
- transformerMetaHighlight,
14
- transformerMetaWordHighlight,
15
- transformerNotationHighlight,
16
- transformerNotationWordHighlight,
17
- transformerNotationFocus,
18
- transformerNotationDiff,
19
- transformerNotationErrorLevel,
20
- } from '@shikijs/transformers';
21
- import { codeBlockTransformer } from './src/lib/shiki-code-block.js';
22
- import { rehypeMermaid } from './src/lib/mermaid-rehype.js';
23
- import remarkMath from 'remark-math';
24
- import rehypeKatex from 'rehype-katex';
25
- import { remarkAutoHydrateSnippets } from './src/lib/mdx-auto-hydrate.js';
26
- import { remarkInjectBuiltinComponents } from './src/lib/mdx-inject-builtins.js';
27
- import { remarkTitleAnchorIds } from './src/lib/mdx-title-anchor-ids.js';
28
- import { remarkSubstituteVariables } from './src/lib/mdx-substitute-variables.js';
29
- import {
30
- remarkMintlifyTreeLists,
31
- remarkMintlifyPromptText,
32
- remarkMintlifyReactHooks,
33
- mintlifyReactHooksPlugin,
34
- } from './src/lib/mdx-mintlify.js';
35
- import { remarkUnknownComponentFallback } from './src/lib/mdx-unknown-components.js';
36
- import { remarkExtractInlineReactComponents } from './src/lib/mdx-inline-react.js';
37
- import { writedocsTempDir, writedocsBuildStagingDir } from './src/lib/writedocs-temp-dir.js';
38
- import { stylesAssetFallback } from './src/lib/styles-asset-integration.js';
39
- import { mcpDevServer } from './src/lib/mcp-dev-integration.js';
40
- import { configReload } from './src/lib/config-reload-integration.js';
41
- import { openapiReload } from './src/lib/openapi-reload-integration.js';
42
- import { contentStoreReload } from './src/lib/content-store-reload-integration.js';
43
- import { iconDataFromFile } from './src/lib/icon-data-dev.js';
44
- import { canonicalPath } from './src/lib/canonical-path.js';
45
- import { withBase, withoutBase } from './src/lib/base-path.js';
46
- import { folderAddresses } from './src/lib/folder-redirects.js';
47
- import { report } from './src/lib/cli-report.js';
48
- import { publishProjectFiles, generatedRobotsTxt } from './src/lib/project-files-integration.js';
49
- import { frontmatterNoindex, canonicalIsElsewhere } from './src/lib/seo-tags.js';
50
- import { readMovedApiPages } from './src/lib/moved-api-pages.js';
51
- import { rehypeImageLoading } from './src/lib/rehype-image-loading.js';
52
- import { rehypeBasePath } from './src/lib/rehype-base-path.js';
53
- import { gitLastModified, newestDate } from './src/lib/last-modified.js';
54
- import { readSpecPaths } from './src/lib/project-files.js';
55
- import {
56
- loadDocsConfig,
57
- resolveCodeblockTheme,
58
- resolveCodeblockLangAlias,
59
- resolveSiteUrl,
60
- resolveSiteOrigin,
61
- resolveBasePath,
62
- normalizeEntryId,
63
- findAllPages,
64
- } from './src/lib/config.ts';
65
-
66
- const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
67
- // See writedocsBuildStagingDir()'s own comment (writedocs-temp-dir.js) for
68
- // why `outDir` below points here instead of directly at contentDir/dist -
69
- // short version: keeps Astro's own build executing inside the package (so
70
- // its dependencies' own module resolution keeps working), while build.js
71
- // does the actual cross-filesystem-safe copy into contentDir/dist as an
72
- // explicit final step once the build itself is done.
73
- const packageRoot = canonicalPath(process.env.WRITEDOCS_PACKAGE_ROOT || path.dirname(fileURLToPath(import.meta.url)));
74
- // Where this package's dependencies are: the node_modules folder that
75
- // contains an installed package (<project>/node_modules/@writedocs/
76
- // generator -> <project>/node_modules), or packageRoot itself in a checkout,
77
- // whose own node_modules is inside it. Used for the dev server's file-serving
78
- // allow list below.
79
- const nodeModulesAt = packageRoot.lastIndexOf(`${path.sep}node_modules${path.sep}`);
80
- const dependencyRoot = nodeModulesAt === -1 ? packageRoot : packageRoot.slice(0, nodeModulesAt + `${path.sep}node_modules`.length);
81
-
82
- // Read here (rather than deferred to page-render time, where
83
- // loadDocsConfig() is also called from [...slug].astro) specifically so
84
- // a site's writedocs.json can pick its own Shiki theme names - astro.config.mjs
85
- // is where Shiki itself actually gets configured, and dev.js/build.js
86
- // already guarantee writedocs.json exists and is valid JSON (preflightCheck())
87
- // before runAstro() ever gets this far, so letting loadDocsConfig() throw
88
- // its own validation error on a malformed writedocs.json here is consistent
89
- // with how every other consumer of it in this codebase behaves - no
90
- // special-casing needed.
91
- const docsConfig = loadDocsConfig(contentDir);
92
- // resolveCodeblockTheme() is the single source of truth for the
93
- // github-light/github-dark fallback - also used by ApiReferencePanel.astro
94
- // for its own separate <Code/> usages (which don't inherit
95
- // markdown.shikiConfig at all), so both stay in sync off the same
96
- // writedocs.json field.
97
- const codeblockTheme = resolveCodeblockTheme(docsConfig);
98
- // resolveCodeblockLangAlias() - see its own comment in lib/config.ts for
99
- // why this exists: some bundled Shiki grammars (mdx, notably) parse
100
- // without error but produce no real token differentiation under this
101
- // theme, so a ```lang fence renders as one flat color instead of
102
- // highlighted. Remaps a fence's language tag to a better-behaved grammar
103
- // before Shiki ever sees it - built-in mdx -> jsx default, plus whatever
104
- // a site adds of its own under writedocs.json's styles.codeblocks.langAlias.
105
- const codeblockLangAlias = resolveCodeblockLangAlias(docsConfig);
106
-
107
- // publicDir defaults relative to Astro's --root (always the writedocs
108
- // package itself - see src/cli/run-astro.js), not the content directory
109
- // being built. Point it at <contentDir>/public instead so a site's own
110
- // static assets (logos, favicons, ...) actually get copied/served -
111
- // falling back to Astro's normal default (<packageRoot>/public, which
112
- // doesn't exist in this package) when a site has no public/ of its own,
113
- // since passing a nonexistent publicDir is a hard Astro error.
114
- const contentPublicDir = path.join(contentDir, 'public');
115
-
116
- // Sitemap generation needs an absolute origin to build absolute <loc>
117
- // entries against - writedocs.json's `domain` field (see resolveSiteUrl() in
118
- // lib/config.ts) is the single source of truth for that, shared with the
119
- // canonical/OG/Twitter URL tags BaseLayout.astro renders per-page. A site
120
- // with no `domain` set (most fixtures, local-only builds) just doesn't
121
- // get a sitemap.xml at all - @astrojs/sitemap requires Astro's own `site`
122
- // config to be set and would otherwise throw, and a sitemap of
123
- // document-relative URLs isn't meaningful anyway.
124
- const siteUrl = resolveSiteUrl(docsConfig);
125
- // writedocs.json's `basePath` ("" when unset) - see lib/base-path.js. Astro's
126
- // own `base` gets it (bundled assets, the dev server's address), and so do
127
- // the page scripts, as __WD_BASE__ (vite.define below).
128
- const basePath = resolveBasePath(docsConfig);
129
- if (!siteUrl) {
130
- report(
131
- 'info',
132
- 'No "domain" set in writedocs.json, so no sitemap.xml was generated, and llms.txt, the MCP server\'s page URLs and the "Open in…" links in the page menu use relative addresses or the address the page is opened from. Set "domain" to the site\'s address, like "docs.example.com".'
133
- );
134
- }
135
-
136
- /** Recursively lists every .md/.mdx file under `baseDir` (Node 20's
137
- * recursive readdir, no extra glob dependency needed - matches the
138
- * plain-fs-walk style already used by generate-api-pages.js's
139
- * findHandWrittenOverrides()), or an empty list if the directory doesn't
140
- * exist (e.g. a site with no OpenAPI groups has no generated-docs/ at
141
- * all under writedocsTempDir()). */
142
- function walkMdFiles(baseDir) {
143
- if (!fs.existsSync(baseDir)) return [];
144
- return fs
145
- .readdirSync(baseDir, { recursive: true })
146
- .filter((f) => /\.mdx?$/i.test(f))
147
- .map((f) => path.join(baseDir, f));
148
- }
149
-
150
- /** The set of normalized page ids (see normalizeEntryId()) whose
151
- * frontmatter sets `seo.noindex: true` - excluded from sitemap.xml below,
152
- * since listing a page there while also telling crawlers not to index it
153
- * (BaseLayout.astro's <meta name="robots" content="noindex..."> for the
154
- * same flag) would be self-contradictory. Reads frontmatter directly via
155
- * gray-matter rather than astro:content, which doesn't exist yet this
156
- * early in Astro's own startup - the same reason
157
- * generate-api-pages.js's own frontmatter scanning does the same thing.
158
- *
159
- * Reuses findAllPages() from lib/config.ts (rather than its own
160
- * hand-rolled walk) for the hand-written-page half of this scan, so it
161
- * always sees exactly the same file set that actually becomes a page in
162
- * the `pages` collection - no risk of the two independently drifting
163
- * apart on which directories get excluded. The fallback id
164
- * (`relativeId` with its extension and any trailing `/index` segment
165
- * stripped) mirrors fileIdForEntry()'s own algorithm in lib/config.ts,
166
- * for a page with no explicit `slug` override. */
167
- function collectNoindexIds(rootContentDir) {
168
- const generatedDocsDir = path.join(writedocsTempDir(rootContentDir), 'generated-docs');
169
- const ids = new Set();
170
- // Whether some page is served at "/" itself. When none is, "/" is the
171
- // redirect-only route [...slug].astro synthesizes (noindex, pointing at
172
- // the first page) - which doesn't belong in the sitemap either.
173
- let rootIsPage = false;
174
- const pageIds = [];
175
- // When each page last changed, for <lastmod> - see lib/last-modified.js.
176
- const fileDates = gitLastModified(rootContentDir);
177
-
178
- for (const relativeId of findAllPages(rootContentDir)) {
179
- const file = path.join(rootContentDir, relativeId);
180
- const { data } = matter(fs.readFileSync(file, 'utf-8'));
181
- const pageId = normalizeEntryId(data?.slug ?? relativeId.replace(/\.mdx?$/i, '').replace(/\/index$/, ''));
182
- if (pageId === 'index') rootIsPage = true;
183
- pageIds.push(pageId);
184
- const changed = fileDates?.get(relativeId.split(path.sep).join('/'));
185
- if (changed) lastModifiedById.set(pageId, changed);
186
- // Top-level `noindex` is Mintlify's spelling, and a Mintlify `hidden`
187
- // page is noindexed too - content.config.ts folds both into
188
- // `seo.noindex` the same way (an explicit value wins).
189
- // A frontmatter `url` page's route only redirects to that link, so it
190
- // doesn't belong in the sitemap either - nor does a page whose
191
- // canonical URL is another address (the sitemap lists canonical ones).
192
- const canonical = data?.seo?.canonical ?? data?.canonical;
193
- const pagePath = pageId === 'index' ? '/' : `/${pageId}/`;
194
- if (!frontmatterNoindex(data) && !data?.url && !canonicalIsElsewhere(siteUrl, pagePath, canonical)) continue;
195
- ids.add(pageId);
196
- }
197
- // Generated OpenAPI stub pages always set an explicit `slug` (see
198
- // generate-api-pages.js) - there's no file-path-derived id to fall back
199
- // to the way there is for a hand-written page.
200
- const specsChanged = fileDates ? newestDate([...readSpecPaths(rootContentDir)].map((spec) => fileDates.get(spec))) : undefined;
201
- for (const file of walkMdFiles(generatedDocsDir)) {
202
- const { data } = matter(fs.readFileSync(file, 'utf-8'));
203
- if (data?.slug && normalizeEntryId(data.slug) === 'index') rootIsPage = true;
204
- if (data?.slug) pageIds.push(normalizeEntryId(data.slug));
205
- // A generated API page changes when a spec does. Which spec it came
206
- // from isn't recorded on the page, so it gets the newest of them.
207
- if (data?.slug && specsChanged) lastModifiedById.set(normalizeEntryId(data.slug), specsChanged);
208
- if (frontmatterNoindex(data) && data.slug) ids.add(normalizeEntryId(data.slug));
209
- }
210
- if (!rootIsPage) ids.add('index');
211
- // Folder addresses with no page of their own redirect to one under them
212
- // (lib/folder-redirects.js) - redirects, so not in the sitemap either.
213
- for (const folder of folderAddresses(pageIds)) ids.add(folder);
214
- return ids;
215
- }
216
-
217
- // Page id -> ISO date of its file's last commit; filled by
218
- // collectNoindexIds(), which reads every page anyway.
219
- const lastModifiedById = new Map();
220
- const noindexIds = siteUrl ? collectNoindexIds(contentDir) : new Set();
221
-
222
- /** O @astrojs/sitemap sempre grava um sitemap-index.xml apontando para
223
- * sitemap-0.xml, sitemap-1.xml, ... - mesmo quando há um arquivo só, que é
224
- * o caso de todo site de docs abaixo de 50.000 páginas. Aqui o único
225
- * sitemap-0.xml vira sitemap.xml (o endereço que crawler e ferramenta de
226
- * SEO procuram primeiro) e o índice é apagado. Com mais de um arquivo o
227
- * índice é necessário (o protocolo não permite um único arquivo acima de
228
- * 50.000 URLs), então tudo fica como o plugin gravou. Um sitemap.xml
229
- * do próprio projeto (na raiz ou em public/ - já copiado para o build por
230
- * publishProjectFiles() ou pelo Astro) também não é sobrescrito. */
231
- function singleSitemapFile() {
232
- return {
233
- name: 'writedocs-single-sitemap',
234
- hooks: {
235
- 'astro:build:done': ({ dir }) => {
236
- const outDir = fileURLToPath(dir);
237
- const chunks = fs.readdirSync(outDir).filter((f) => /^sitemap-\d+\.xml$/.test(f));
238
- const target = path.join(outDir, 'sitemap.xml');
239
- if (chunks.length !== 1) {
240
- report('debug', `${chunks.length} sitemap files generated - keeping sitemap-index.xml.`);
241
- return;
242
- }
243
- if (fs.existsSync(target)) {
244
- report('info', "The project has its own sitemap.xml, so it was kept - the generated sitemap is sitemap-index.xml.");
245
- return;
246
- }
247
- fs.renameSync(path.join(outDir, chunks[0]), target);
248
- fs.rmSync(path.join(outDir, 'sitemap-index.xml'), { force: true });
249
- // O próprio plugin acabou de logar "sitemap-index.xml created"; esta
250
- // linha diz o que de fato ficou no build.
251
- report('debug', `Replaced ${chunks[0]} + sitemap-index.xml with a single sitemap.xml.`);
252
- },
253
- },
254
- };
255
- }
256
-
257
- // writedocs.json's `redirects` array -> Astro's own `redirects` config option
258
- // (a plain `{ [source]: destination }` record - see redirectSchema in
259
- // lib/config.ts for why there's no `permanent`/status-code field: this
260
- // package always builds `output: 'static'` with no adapter installed, and
261
- // Astro's own docs say a static redirect is always a client-side
262
- // `<meta http-equiv="refresh">` page regardless of what status is asked
263
- // for). Omitted entirely (rather than passed as `{}`) when a site has no
264
- // redirects configured, matching the `siteUrl ? [...] : []` pattern above
265
- // of only opting into a feature's config surface when it's actually used.
266
- // Generated API pages that moved to a new address (lib/moved-api-pages.js)
267
- // redirect from the old one the same way; a redirect the site wrote itself
268
- // for the same address comes later in the list, and wins.
269
- const movedApiPages = readMovedApiPages(contentDir);
270
- // With a basePath, Astro serves a redirect's source under the base itself,
271
- // but writes its destination as given - so a destination inside the site
272
- // gets the base here (lib/base-path.js).
273
- const redirectsConfig = Object.fromEntries([...movedApiPages, ...docsConfig.redirects].map((r) => [r.source, withBase(basePath, r.destination)]));
274
-
275
- /** Tailwind only scans the Vite root for class names - this package, not
276
- * the site being built, which is usually somewhere else entirely - so a
277
- * utility class written in a site's own MDX or snippet (Mintlify content
278
- * uses them freely, e.g. className="block dark:hidden") never got
279
- * generated. Appends an @source for the site's content files to
280
- * global.css before Tailwind compiles it. Forward slashes, since
281
- * Tailwind reads the path as a glob. */
282
- function contentTailwindSource() {
283
- const sourceGlob = `${contentDir.split(path.sep).join('/')}/**/*.{md,mdx,jsx,tsx}`;
284
- return {
285
- name: 'writedocs:content-tailwind-source',
286
- enforce: 'pre',
287
- transform(code, id) {
288
- if (!id.split('?')[0].replace(/\\/g, '/').endsWith('/src/styles/global.css')) return null;
289
- return { code: `${code}\n@source ${JSON.stringify(sourceGlob)};\n`, map: null };
290
- },
291
- };
292
- }
293
-
294
- export default defineConfig({
295
- // The origin alone: Astro adds `base` to it itself (the sitemap's URLs).
296
- ...(siteUrl ? { site: resolveSiteOrigin(docsConfig) } : {}),
297
- // Only with a basePath: without one the config is exactly what it was.
298
- ...(basePath ? { base: basePath } : {}),
299
- ...(Object.keys(redirectsConfig).length ? { redirects: redirectsConfig } : {}),
300
- // Astro's own dev-mode toolbar (the floating pill in the bottom center
301
- // of every page - inspect/audit/settings) is a tool for authoring
302
- // Astro itself, not something a writedocs site's own reader/author
303
- // should see while running `writedocs dev` - it's not exposed as a
304
- // writedocs.json option (nothing site-specific to configure here) since
305
- // there's no scenario where a writedocs project actually wants it on.
306
- // Off in every environment (build never shows it anyway, since it's a
307
- // dev-only overlay Astro strips from production output regardless).
308
- devToolbar: { enabled: false },
309
- // Not contentDir/dist directly - see writedocsBuildStagingDir()'s own
310
- // comment (writedocs-temp-dir.js) for why, and build.js for the copy
311
- // step that actually gets a finished build from here into the real
312
- // <contentDir>/dist a reader/host ever sees. Irrelevant to `astro dev`
313
- // (no build output involved), so this applies unconditionally rather
314
- // than branching on which CLI command is running.
315
- outDir: writedocsBuildStagingDir(packageRoot, contentDir),
316
- cacheDir: path.join(writedocsTempDir(contentDir), 'cache'),
317
- ...(fs.existsSync(contentPublicDir) ? { publicDir: contentPublicDir } : {}),
318
- // icon() reads from whatever @iconify-json/* collections are installed
319
- // (see package.json) and inlines only the specific icons a build
320
- // actually references as <svg> - the installed collections don't
321
- // affect output size beyond that. No `include` config needed: astro-icon
322
- // resolves "collection:icon-name" against any installed collection
323
- // automatically.
324
- integrations: [
325
- // markdown.processor (below) carries remarkAutoHydrateSnippets - see
326
- // its own comment there for why it's attached there and not here.
327
- // Auto-adds `client:load` to every usage of a component imported from
328
- // a .jsx/.tsx file (a snippet - see docs/dev/docs/snippets.mdx) that
329
- // doesn't already carry its own `client:*` attribute, so a snippet
330
- // just works when dropped into a page - nobody using it needs to know
331
- // Astro's hydration-directive syntax exists at all, only someone who
332
- // wants a *different* strategy (client:visible/idle/only) needs to
333
- // write one explicitly.
334
- mdx(),
335
- // Lets a site's own snippets (see docs/dev/docs/snippets.mdx) be real
336
- // .jsx/.tsx React components - hooks and all - dropped straight into
337
- // MDX and hydrated client-side as an Astro island (automatically -
338
- // see remarkAutoHydrateSnippets above). writedocs' own built-in
339
- // components (Callout, Card, ...) stay plain .astro files - this is
340
- // purely for snippets a site author writes themselves.
341
- react(),
342
- icon(),
343
- // A project's own files, published as they are (robots.txt, sitemap.xml,
344
- // a PDF...) - before the sitemap integration, see
345
- // lib/project-files-integration.js.
346
- publishProjectFiles(contentDir),
347
- ...(siteUrl
348
- ? [
349
- sitemap({
350
- // Teto do protocolo de sitemap por arquivo (o default do
351
- // @astrojs/sitemap é 45.000). Até aqui, tudo cabe num único
352
- // sitemap.xml - ver singleSitemapFile() abaixo.
353
- entryLimit: 50000,
354
- // The plugin's URLs carry the base ("/docs/guides/a/") - the
355
- // ids here don't.
356
- filter: (page) => {
357
- const pathname = withoutBase(basePath, new URL(page).pathname) ?? '/';
358
- const id = normalizeEntryId(pathname);
359
- return !noindexIds.has(id);
360
- },
361
- // <lastmod>, for the pages git has a date for.
362
- serialize: (item) => {
363
- const changed = lastModifiedById.get(normalizeEntryId(withoutBase(basePath, new URL(item.url).pathname) ?? '/'));
364
- return changed ? { ...item, lastmod: changed } : item;
365
- },
366
- }),
367
- // Precisa vir depois do sitemap(): o Astro roda os hooks
368
- // astro:build:done na ordem deste array, um de cada vez.
369
- singleSitemapFile(),
370
- ]
371
- : []),
372
- // After the sitemap: the generated robots.txt names the sitemap file.
373
- generatedRobotsTxt({ siteUrl, seo: docsConfig.seo, basePath }),
374
- // Lets styles.favicon/styles.logo/styles.background.images/seo.ogImage/
375
- // styles.fonts.*.source resolve from anywhere in the project, not just
376
- // public/ - see collectConfiguredAssetPaths() (lib/config.ts) for the
377
- // field list and styles-asset-integration.js for how it's actually
378
- // served/copied.
379
- stylesAssetFallback(contentDir, { basePath }),
380
- // /mcp in `writedocs dev`, as the build's dist/_worker.js serves it -
381
- // see src/lib/mcp-dev-integration.js.
382
- mcpDevServer({ version: JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8')).version, basePath }),
383
- // writedocs dev: an edit to writedocs.json reloads the open tab.
384
- configReload({ configPath: path.join(contentDir, 'writedocs.json') }),
385
- // writedocs dev: an edit to an OpenAPI spec regenerates its pages.
386
- openapiReload({ contentDir, packageRoot }),
387
- // writedocs dev, installed: a change to a page's entry (its title, an
388
- // API page renamed) reaches the open tab.
389
- contentStoreReload({ packageRoot }),
390
- ],
391
- output: 'static',
392
- // Dual Shiki themes for fenced code blocks (```) in MDX content, so
393
- // they switch with the site's own [data-theme] toggle instead of
394
- // always rendering Astro's single default (github-dark) regardless of
395
- // light/dark mode. Defaults to github-light/github-dark, overridable
396
- // per-site via writedocs.json's styles.codeblocks.{light,dark} (any Shiki
397
- // theme *name* - see https://shiki.style/themes for the built-in
398
- // list - not a custom theme object/JSON file, at least for now).
399
- // Astro bakes the "light" theme's colors as the element's base inline
400
- // style and adds --shiki-dark/--shiki-dark-bg (etc.) custom
401
- // properties alongside it - see the
402
- // [data-theme='dark'] :global(.astro-code) override in
403
- // BaseLayout.astro that actually swaps to them.
404
- markdown: {
405
- // Excludes ```mermaid fences from Shiki's own tokenization entirely -
406
- // they reach rehypeMermaid (below) as plain, un-highlighted text,
407
- // which is what mermaid.js needs to parse and render them into an
408
- // actual diagram client-side (see [...slug].astro's initMermaid()).
409
- // Syntax-highlighting mermaid's own pseudo-language as if it were
410
- // source code would be actively wrong here - the goal is a rendered
411
- // diagram, not colored diagram-description text.
412
- syntaxHighlight: { type: 'shiki', excludeLangs: ['mermaid'] },
413
- // Astro 7's markdown.rehypePlugins (top-level) is deprecated in favor
414
- // of passing plugins straight to the `unified` processor itself -
415
- // functionally identical (Astro's own deprecated-option shim used to
416
- // just forward the top-level array into this exact processor), just
417
- // explicit instead of relying on that shim (and the console warning
418
- // it prints on every build/dev run). Astro still runs this *after*
419
- // its own internal Shiki step (see @astrojs/markdown-remark's
420
- // index.js) regardless of which processor plugins are attached to,
421
- // so rehypeMermaid still always sees the excluded ```mermaid block
422
- // completely untouched by Shiki - exactly the plain
423
- // <pre><code class="language-mermaid"> shape it expects to reshape
424
- // into mermaid.js's <div class="mermaid"> form.
425
- // remarkInjectBuiltinComponents/remarkAutoHydrateSnippets only ever
426
- // match JSX/import nodes that exist solely in MDX's extended syntax
427
- // tree (see mdx-inject-builtins.js/mdx-auto-hydrate.js) - running them
428
- // here rather than passing them to mdx({ remarkPlugins }) avoids that
429
- // option's own deprecation warning ("pass it to unified()... MDX will
430
- // inherit it" - extendMarkdownConfig defaults to true, so mdx() below
431
- // already picks this processor up automatically). Harmless no-op on
432
- // plain .md content, which never has an mdxjsEsm/mdxJsxFlowElement
433
- // node to match in the first place.
434
- // remarkSubstituteVariables is a parameterized plugin (an "attacher"
435
- // that takes writedocs.json's `variables` map as its options and returns
436
- // the actual transformer) - passed as a unified [attacher, options]
437
- // tuple, *not* pre-called (`remarkSubstituteVariables(docsConfig.variables)`
438
- // directly in this array). unified's own `use()` always calls
439
- // whatever it finds in this array as if it were the attacher itself;
440
- // handing it an already-produced transformer function makes unified
441
- // invoke *that* with zero arguments during its `freeze()` setup pass,
442
- // which crashes deep inside unist-util-visit ("Cannot use 'in'
443
- // operator to search for 'children' in undefined") the first time any
444
- // MDX page actually builds - a real bug hit and fixed while testing
445
- // 25-site-config, not a hypothetical. remarkInjectBuiltinComponents/
446
- // remarkAutoHydrateSnippets don't need this tuple form since neither
447
- // takes options - they're valid attachers as bare function references.
448
- // A site with no `variables` set still gets this plugin instance
449
- // (which then no-ops on every file - see its own early-return) rather
450
- // than being conditionally omitted, keeping this array's shape static
451
- // regardless of writedocs.json content.
452
- processor: unified({
453
- // remarkMath goes first: it parses $inline$ and standalone $$block$$
454
- // math into their own `inlineMath`/`math` mdast node types (mdast-
455
- // util-to-hast has built-in support for both, turning them into a
456
- // <span>/<div> carrying the raw LaTeX source as a "language-math"
457
- // code-like payload for rehypeKatex, below, to render). Running it
458
- // before remarkSubstituteVariables means a $...$ span's raw LaTeX
459
- // source is no longer a plain `text` node by the time that plugin's
460
- // visitor runs (it only visits `text` nodes - see its own comment) -
461
- // not that `[[key]]` syntax inside actual LaTeX is a realistic thing
462
- // to write, but this keeps the two plugins' node-type boundaries
463
- // clean rather than leaving it to chance which one sees a math span
464
- // as raw text first.
465
- remarkPlugins: [
466
- remarkMath,
467
- // Mintlify's Markdown-list <Tree> and <Prompt> source text - see
468
- // lib/mdx-mintlify.js. Before remarkInjectBuiltinComponents, so
469
- // the <Tree.Folder>/<Tree.File> elements they add are already in
470
- // the tree when it looks for components to import.
471
- remarkMintlifyTreeLists,
472
- remarkMintlifyPromptText,
473
- // An inline component that calls React hooks moves into a generated
474
- // .jsx file so it runs as real React (and hydrates) - see
475
- // lib/mdx-inline-react.js. Before remarkMintlifyReactHooks, which
476
- // imports any hooks the page itself still calls (Mintlify
477
- // pre-injects them), and before remarkAutoHydrateSnippets, which
478
- // hydrates the component through its new .jsx import.
479
- remarkExtractInlineReactComponents,
480
- remarkMintlifyReactHooks,
481
- // An unknown component becomes a fragment (its children still
482
- // render) with a warning, instead of failing the whole build - see
483
- // lib/mdx-unknown-components.js. After remarkMintlifyTreeLists, so
484
- // the <Tree.Folder>/<Tree.File> elements it adds count as known.
485
- remarkUnknownComponentFallback,
486
- remarkInjectBuiltinComponents,
487
- // Runs after remarkInjectBuiltinComponents (order doesn't actually
488
- // matter between them - that plugin only ever prepends an import
489
- // statement, never touches an existing JSX node's attributes) but
490
- // grouped right next to it since both deal with the same set of
491
- // built-in component tag names. See its own comment for why this
492
- // has to be a whole-document pass rather than logic living inside
493
- // Callout.astro/Accordion.astro themselves.
494
- remarkTitleAnchorIds,
495
- remarkAutoHydrateSnippets,
496
- [remarkSubstituteVariables, docsConfig.variables],
497
- ],
498
- // rehypeKatex renders every math/inlineMath node remarkMath produced
499
- // into real KaTeX markup (a <span class="katex">...</span> tree of
500
- // MathML + HTML, not an image or client-rendered widget) - fully at
501
- // build time, so unlike Mermaid there's no client-side JS or runtime
502
- // cost at all, just the one katex.min.css import (BaseLayout.astro)
503
- // for layout/glyph styling. Order relative to rehypeMermaid doesn't
504
- // matter - they walk disjoint hast node shapes (pre>code.language-
505
- // mermaid vs. remarkMath's own math/inlineMath-derived nodes) and
506
- // neither plugin's output is visible to the other.
507
- // rehypeImageLoading: lazy loading and sizes for content images - see
508
- // lib/rehype-image-loading.js.
509
- // rehypeBasePath: the basePath in front of the content's own links and
510
- // pictures (lib/rehype-base-path.js) - last, since rehypeImageLoading
511
- // finds an image's file by the address as written.
512
- rehypePlugins: [rehypeMermaid, rehypeKatex, [rehypeImageLoading, { contentDir }], [rehypeBasePath, { base: basePath }]],
513
- }),
514
- shikiConfig: {
515
- themes: codeblockTheme,
516
- langAlias: codeblockLangAlias,
517
- // The official @shikijs/transformers annotation transformers -
518
- // enabled sitewide so any fenced code block can use their meta-
519
- // string/comment syntax without per-page opt-in:
520
- // ```js {1,3-5} -> transformerMetaHighlight
521
- // ```js /someWord/ -> transformerMetaWordHighlight
522
- // // [!code highlight] -> transformerNotationHighlight
523
- // // [!code word:someWord] -> transformerNotationWordHighlight
524
- // // [!code focus] -> transformerNotationFocus
525
- // // [!code ++] / // [!code --] -> transformerNotationDiff
526
- // // [!code error] / [!code warning] -> transformerNotationErrorLevel
527
- // (comment syntax adapts to the language - # for Python/bash, //
528
- // for JS/etc - see each transformer's own docs at shiki.style).
529
- // Plus codeBlockTransformer, writedocs' own transformer for the
530
- // copy button, an optional title bar, and wrap/lines/expandable
531
- // meta flags - see src/lib/shiki-code-block.js. It runs last so
532
- // its `root` hook wraps the <pre> only after every class the
533
- // transformers above added to it is already in place - though in
534
- // practice this doesn't matter, since all `pre`/`line` hooks
535
- // across every transformer run to completion before any `root`
536
- // hook runs at all (two separate passes, not interleaved).
537
- transformers: [
538
- transformerMetaHighlight(),
539
- transformerMetaWordHighlight(),
540
- transformerNotationHighlight(),
541
- transformerNotationWordHighlight(),
542
- transformerNotationFocus(),
543
- transformerNotationDiff(),
544
- transformerNotationErrorLevel(),
545
- codeBlockTransformer(),
546
- ],
547
- },
548
- },
549
- // Tailwind is available for future/custom content (e.g. hand-authored
550
- // MDX) but nothing in writedocs' own components has been migrated to
551
- // it - they still use scoped <style> blocks + the --wd-* CSS variables
552
- // so per-site writedocs.json theming (colors, and now dark mode) keeps
553
- // working. See src/styles/global.css for the one @import that wires
554
- // Tailwind's utilities in.
555
- vite: {
556
- // The base for page scripts and components: "" or "/docs". A constant
557
- // rather than import.meta.env.BASE_URL ("/" with no base, "/docs" or
558
- // "/docs/" with one), so `__WD_BASE__ + "/pagefind/..."` folds to the
559
- // same string the bundle had before basePath existed.
560
- define: { __WD_BASE__: JSON.stringify(basePath) },
561
- // The dev server only serves files under its workspace root by default.
562
- // A site's own snippets live in its content directory, and inline React
563
- // components moved out of pages (lib/mdx-inline-react.js) in writedocs'
564
- // temp directory - both need to reach the browser to hydrate. Setting
565
- // `allow` replaces Vite's default rather than adding to it, so the
566
- // package's dependencies must stay reachable too: when writedocs is
567
- // installed, they sit next to it in the node_modules folder that
568
- // contains it (React's own hydration client included), not inside
569
- // packageRoot - see dependencyRoot above.
570
- server: {
571
- fs: {
572
- allow: [packageRoot, dependencyRoot, contentDir, writedocsTempDir(contentDir)],
573
- },
574
- },
575
- // contentTailwindSource() must come before tailwindcss(): both are
576
- // enforce: 'pre' transforms, which Vite runs in array order, and
577
- // Tailwind has to see the added @source when it compiles global.css.
578
- // mintlifyReactHooksPlugin() does for a site's .jsx/.tsx snippets what
579
- // remarkMintlifyReactHooks does for its MDX pages.
580
- // iconDataFromFile() (writedocs dev only): astro-icon's ~15 MB of icon
581
- // data read from a file rather than passed through Vite - about 5 s of
582
- // every dev preview's first page (see src/lib/icon-data-dev.js).
583
- plugins: [contentTailwindSource(), tailwindcss(), mintlifyReactHooksPlugin(contentDir), iconDataFromFile(writedocsTempDir(contentDir))],
584
- // `writedocs dev`: Vite only prepares for the browser the dependencies
585
- // it finds by scanning the project's own source - and when writedocs is
586
- // installed, its source sits in node_modules, which the scan skips. The
587
- // page script's `import("mermaid")` ([...slug].astro) was then served
588
- // as it is, and its CommonJS dependencies failed in the browser ("dayjs
589
- // ... does not provide an export named 'default'"): diagrams stayed as
590
- // text in dev, while builds were fine. Naming it here prepares it always.
591
- optimizeDeps: {
592
- include: ['mermaid'],
593
- },
594
- resolve: {
595
- alias: [
596
- // Lets a page's MDX write `import Foo from '/snippets/foo.mdx'`
597
- // (Mintlify's own snippet-import convention) instead of a
598
- // relative path whose "../" depth depends on how deeply nested
599
- // the importing page happens to be - see docs/dev/docs/snippets.mdx
600
- // for the full feature writeup. Vite's project root is always
601
- // packageRoot (this package itself - see run-astro.js), not
602
- // contentDir, so a real leading-slash import would otherwise
603
- // resolve (and fail to find anything) inside this package
604
- // instead of the site's own content directory; this alias
605
- // redirects just that one prefix to contentDir/snippets/ instead.
606
- { find: /^\/snippets\//, replacement: path.join(contentDir, 'snippets') + '/' },
607
- // remarkInjectBuiltinComponents (mdx-inject-builtins.js) auto-
608
- // injects `import { Callout, ... } from 'writedocs/components'`
609
- // into any .mdx file that uses a built-in component tag without
610
- // importing it itself - a real bare specifier Vite has to resolve
611
- // as if the .mdx file had written it. package.json's own
612
- // `exports: { "./components": "./src/components/index.ts" }`
613
- // makes that specifier valid *in principle* (Node's package
614
- // self-reference feature - a package importing its own name), but
615
- // self-reference only resolves when the importing file is a
616
- // descendant of this package's own package.json - true for every
617
- // existing fixture (always built from inside this repo/package
618
- // tree) but never true for a real consumer's content, which lives
619
- // in a completely separate directory in the actual product
620
- // architecture (see docs/dev/docs/architecture.mdx) - walking up
621
- // from such a file never finds a package.json named "writedocs",
622
- // so self-reference fails and Vite reports the bare specifier as
623
- // unresolvable ("Rolldown failed to resolve import
624
- // 'writedocs/components'").
625
- // This alias bypasses self-reference resolution entirely for
626
- // that one specifier - Vite's alias matching is a plain string
627
- // match against the specifier itself, independent of which file
628
- // imported it, so it resolves correctly regardless of where the
629
- // content directory actually lives. WRITEDOCS_PACKAGE_ROOT is the
630
- // same packageRoot value already set by run-astro.js for
631
- // lib/config.ts's fileIdForEntry() to consume - reusing it here
632
- // instead of recomputing via import.meta.url keeps there being
633
- // exactly one source of truth for "where this package lives" per
634
- // astro subprocess. Falls back to this file's own directory
635
- // (astro.config.mjs always lives at packageRoot) for anything
636
- // that ever imports this config outside that subprocess, e.g. a
637
- // future test harness.
638
- {
639
- find: 'writedocs/components',
640
- replacement: path.join(packageRoot, 'src/components/index.ts'),
641
- },
642
- ],
643
- },
644
- },
645
- });
1
+ import { defineConfig } from 'astro/config';
2
+ import mdx from '@astrojs/mdx';
3
+ import react from '@astrojs/react';
4
+ import icon from 'astro-icon';
5
+ import sitemap from '@astrojs/sitemap';
6
+ import tailwindcss from '@tailwindcss/vite';
7
+ import path from 'node:path';
8
+ import fs from 'node:fs';
9
+ import { fileURLToPath } from 'node:url';
10
+ import matter from 'gray-matter';
11
+ import { unified } from '@astrojs/markdown-remark';
12
+ import {
13
+ transformerMetaHighlight,
14
+ transformerMetaWordHighlight,
15
+ transformerNotationHighlight,
16
+ transformerNotationWordHighlight,
17
+ transformerNotationFocus,
18
+ transformerNotationDiff,
19
+ transformerNotationErrorLevel,
20
+ } from '@shikijs/transformers';
21
+ import { codeBlockTransformer } from './src/lib/shiki-code-block.js';
22
+ import { rehypeMermaid } from './src/lib/mermaid-rehype.js';
23
+ import remarkMath from 'remark-math';
24
+ import rehypeKatex from 'rehype-katex';
25
+ import { remarkAutoHydrateSnippets } from './src/lib/mdx-auto-hydrate.js';
26
+ import { remarkInjectBuiltinComponents } from './src/lib/mdx-inject-builtins.js';
27
+ import { remarkTitleAnchorIds } from './src/lib/mdx-title-anchor-ids.js';
28
+ import { remarkSubstituteVariables } from './src/lib/mdx-substitute-variables.js';
29
+ import {
30
+ remarkMintlifyTreeLists,
31
+ remarkMintlifyPromptText,
32
+ remarkMintlifyReactHooks,
33
+ mintlifyReactHooksPlugin,
34
+ } from './src/lib/mdx-mintlify.js';
35
+ import { remarkUnknownComponentFallback } from './src/lib/mdx-unknown-components.js';
36
+ import { remarkExtractInlineReactComponents } from './src/lib/mdx-inline-react.js';
37
+ import { writedocsTempDir, writedocsBuildStagingDir } from './src/lib/writedocs-temp-dir.js';
38
+ import { stylesAssetFallback } from './src/lib/styles-asset-integration.js';
39
+ import { mcpDevServer } from './src/lib/mcp-dev-integration.js';
40
+ import { configReload } from './src/lib/config-reload-integration.js';
41
+ import { openapiReload } from './src/lib/openapi-reload-integration.js';
42
+ import { contentStoreReload } from './src/lib/content-store-reload-integration.js';
43
+ import { iconDataFromFile } from './src/lib/icon-data-dev.js';
44
+ import { canonicalPath } from './src/lib/canonical-path.js';
45
+ import { withBase, withoutBase } from './src/lib/base-path.js';
46
+ import { folderAddresses } from './src/lib/folder-redirects.js';
47
+ import { report } from './src/lib/cli-report.js';
48
+ import { publishProjectFiles, generatedRobotsTxt } from './src/lib/project-files-integration.js';
49
+ import { frontmatterNoindex, canonicalIsElsewhere } from './src/lib/seo-tags.js';
50
+ import { readMovedApiPages } from './src/lib/moved-api-pages.js';
51
+ import { rehypeImageLoading } from './src/lib/rehype-image-loading.js';
52
+ import { rehypeBasePath } from './src/lib/rehype-base-path.js';
53
+ import { gitLastModified, newestDate } from './src/lib/last-modified.js';
54
+ import { readSpecPaths } from './src/lib/project-files.js';
55
+ import {
56
+ loadDocsConfig,
57
+ resolveCodeblockTheme,
58
+ resolveCodeblockLangAlias,
59
+ resolveSiteUrl,
60
+ resolveSiteOrigin,
61
+ resolveBasePath,
62
+ normalizeEntryId,
63
+ findAllPages,
64
+ } from './src/lib/config.ts';
65
+
66
+ const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
67
+ // See writedocsBuildStagingDir()'s own comment (writedocs-temp-dir.js) for
68
+ // why `outDir` below points here instead of directly at contentDir/dist -
69
+ // short version: keeps Astro's own build executing inside the package (so
70
+ // its dependencies' own module resolution keeps working), while build.js
71
+ // does the actual cross-filesystem-safe copy into contentDir/dist as an
72
+ // explicit final step once the build itself is done.
73
+ const packageRoot = canonicalPath(process.env.WRITEDOCS_PACKAGE_ROOT || path.dirname(fileURLToPath(import.meta.url)));
74
+ // Where this package's dependencies are: the node_modules folder that
75
+ // contains an installed package (<project>/node_modules/@writedocs/
76
+ // generator -> <project>/node_modules), or packageRoot itself in a checkout,
77
+ // whose own node_modules is inside it. Used for the dev server's file-serving
78
+ // allow list below.
79
+ const nodeModulesAt = packageRoot.lastIndexOf(`${path.sep}node_modules${path.sep}`);
80
+ const dependencyRoot = nodeModulesAt === -1 ? packageRoot : packageRoot.slice(0, nodeModulesAt + `${path.sep}node_modules`.length);
81
+
82
+ // Read here (rather than deferred to page-render time, where
83
+ // loadDocsConfig() is also called from [...slug].astro) specifically so
84
+ // a site's writedocs.json can pick its own Shiki theme names - astro.config.mjs
85
+ // is where Shiki itself actually gets configured, and dev.js/build.js
86
+ // already guarantee writedocs.json exists and is valid JSON (preflightCheck())
87
+ // before runAstro() ever gets this far, so letting loadDocsConfig() throw
88
+ // its own validation error on a malformed writedocs.json here is consistent
89
+ // with how every other consumer of it in this codebase behaves - no
90
+ // special-casing needed.
91
+ const docsConfig = loadDocsConfig(contentDir);
92
+ // resolveCodeblockTheme() is the single source of truth for the
93
+ // github-light/github-dark fallback - also used by ApiReferencePanel.astro
94
+ // for its own separate <Code/> usages (which don't inherit
95
+ // markdown.shikiConfig at all), so both stay in sync off the same
96
+ // writedocs.json field.
97
+ const codeblockTheme = resolveCodeblockTheme(docsConfig);
98
+ // resolveCodeblockLangAlias() - see its own comment in lib/config.ts for
99
+ // why this exists: some bundled Shiki grammars (mdx, notably) parse
100
+ // without error but produce no real token differentiation under this
101
+ // theme, so a ```lang fence renders as one flat color instead of
102
+ // highlighted. Remaps a fence's language tag to a better-behaved grammar
103
+ // before Shiki ever sees it - built-in mdx -> jsx default, plus whatever
104
+ // a site adds of its own under writedocs.json's styles.codeblocks.langAlias.
105
+ const codeblockLangAlias = resolveCodeblockLangAlias(docsConfig);
106
+
107
+ // publicDir defaults relative to Astro's --root (always the writedocs
108
+ // package itself - see src/cli/run-astro.js), not the content directory
109
+ // being built. Point it at <contentDir>/public instead so a site's own
110
+ // static assets (logos, favicons, ...) actually get copied/served -
111
+ // falling back to Astro's normal default (<packageRoot>/public, which
112
+ // doesn't exist in this package) when a site has no public/ of its own,
113
+ // since passing a nonexistent publicDir is a hard Astro error.
114
+ const contentPublicDir = path.join(contentDir, 'public');
115
+
116
+ // Sitemap generation needs an absolute origin to build absolute <loc>
117
+ // entries against - writedocs.json's `domain` field (see resolveSiteUrl() in
118
+ // lib/config.ts) is the single source of truth for that, shared with the
119
+ // canonical/OG/Twitter URL tags BaseLayout.astro renders per-page. A site
120
+ // with no `domain` set (most fixtures, local-only builds) just doesn't
121
+ // get a sitemap.xml at all - @astrojs/sitemap requires Astro's own `site`
122
+ // config to be set and would otherwise throw, and a sitemap of
123
+ // document-relative URLs isn't meaningful anyway.
124
+ const siteUrl = resolveSiteUrl(docsConfig);
125
+ // writedocs.json's `basePath` ("" when unset) - see lib/base-path.js. Astro's
126
+ // own `base` gets it (bundled assets, the dev server's address), and so do
127
+ // the page scripts, as __WD_BASE__ (vite.define below).
128
+ const basePath = resolveBasePath(docsConfig);
129
+ if (!siteUrl) {
130
+ report(
131
+ 'info',
132
+ 'No "domain" set in writedocs.json, so no sitemap.xml was generated, and llms.txt, the MCP server\'s page URLs and the "Open in…" links in the page menu use relative addresses or the address the page is opened from. Set "domain" to the site\'s address, like "docs.example.com".'
133
+ );
134
+ }
135
+
136
+ /** Recursively lists every .md/.mdx file under `baseDir` (Node 20's
137
+ * recursive readdir, no extra glob dependency needed - matches the
138
+ * plain-fs-walk style already used by generate-api-pages.js's
139
+ * findHandWrittenOverrides()), or an empty list if the directory doesn't
140
+ * exist (e.g. a site with no OpenAPI groups has no generated-docs/ at
141
+ * all under writedocsTempDir()). */
142
+ function walkMdFiles(baseDir) {
143
+ if (!fs.existsSync(baseDir)) return [];
144
+ return fs
145
+ .readdirSync(baseDir, { recursive: true })
146
+ .filter((f) => /\.mdx?$/i.test(f))
147
+ .map((f) => path.join(baseDir, f));
148
+ }
149
+
150
+ /** The set of normalized page ids (see normalizeEntryId()) whose
151
+ * frontmatter sets `seo.noindex: true` - excluded from sitemap.xml below,
152
+ * since listing a page there while also telling crawlers not to index it
153
+ * (BaseLayout.astro's <meta name="robots" content="noindex..."> for the
154
+ * same flag) would be self-contradictory. Reads frontmatter directly via
155
+ * gray-matter rather than astro:content, which doesn't exist yet this
156
+ * early in Astro's own startup - the same reason
157
+ * generate-api-pages.js's own frontmatter scanning does the same thing.
158
+ *
159
+ * Reuses findAllPages() from lib/config.ts (rather than its own
160
+ * hand-rolled walk) for the hand-written-page half of this scan, so it
161
+ * always sees exactly the same file set that actually becomes a page in
162
+ * the `pages` collection - no risk of the two independently drifting
163
+ * apart on which directories get excluded. The fallback id
164
+ * (`relativeId` with its extension and any trailing `/index` segment
165
+ * stripped) mirrors fileIdForEntry()'s own algorithm in lib/config.ts,
166
+ * for a page with no explicit `slug` override. */
167
+ function collectNoindexIds(rootContentDir) {
168
+ const generatedDocsDir = path.join(writedocsTempDir(rootContentDir), 'generated-docs');
169
+ const ids = new Set();
170
+ // Whether some page is served at "/" itself. When none is, "/" is the
171
+ // redirect-only route [...slug].astro synthesizes (noindex, pointing at
172
+ // the first page) - which doesn't belong in the sitemap either.
173
+ let rootIsPage = false;
174
+ const pageIds = [];
175
+ // When each page last changed, for <lastmod> - see lib/last-modified.js.
176
+ const fileDates = gitLastModified(rootContentDir);
177
+
178
+ for (const relativeId of findAllPages(rootContentDir)) {
179
+ const file = path.join(rootContentDir, relativeId);
180
+ const { data } = matter(fs.readFileSync(file, 'utf-8'));
181
+ const pageId = normalizeEntryId(data?.slug ?? relativeId.replace(/\.mdx?$/i, '').replace(/\/index$/, ''));
182
+ if (pageId === 'index') rootIsPage = true;
183
+ pageIds.push(pageId);
184
+ const changed = fileDates?.get(relativeId.split(path.sep).join('/'));
185
+ if (changed) lastModifiedById.set(pageId, changed);
186
+ // Top-level `noindex` is Mintlify's spelling, and a Mintlify `hidden`
187
+ // page is noindexed too - content.config.ts folds both into
188
+ // `seo.noindex` the same way (an explicit value wins).
189
+ // A frontmatter `url` page's route only redirects to that link, so it
190
+ // doesn't belong in the sitemap either - nor does a page whose
191
+ // canonical URL is another address (the sitemap lists canonical ones).
192
+ const canonical = data?.seo?.canonical ?? data?.canonical;
193
+ const pagePath = pageId === 'index' ? '/' : `/${pageId}/`;
194
+ if (!frontmatterNoindex(data) && !data?.url && !canonicalIsElsewhere(siteUrl, pagePath, canonical)) continue;
195
+ ids.add(pageId);
196
+ }
197
+ // Generated OpenAPI stub pages always set an explicit `slug` (see
198
+ // generate-api-pages.js) - there's no file-path-derived id to fall back
199
+ // to the way there is for a hand-written page.
200
+ const specsChanged = fileDates ? newestDate([...readSpecPaths(rootContentDir)].map((spec) => fileDates.get(spec))) : undefined;
201
+ for (const file of walkMdFiles(generatedDocsDir)) {
202
+ const { data } = matter(fs.readFileSync(file, 'utf-8'));
203
+ if (data?.slug && normalizeEntryId(data.slug) === 'index') rootIsPage = true;
204
+ if (data?.slug) pageIds.push(normalizeEntryId(data.slug));
205
+ // A generated API page changes when a spec does. Which spec it came
206
+ // from isn't recorded on the page, so it gets the newest of them.
207
+ if (data?.slug && specsChanged) lastModifiedById.set(normalizeEntryId(data.slug), specsChanged);
208
+ if (frontmatterNoindex(data) && data.slug) ids.add(normalizeEntryId(data.slug));
209
+ }
210
+ if (!rootIsPage) ids.add('index');
211
+ // Folder addresses with no page of their own redirect to one under them
212
+ // (lib/folder-redirects.js) - redirects, so not in the sitemap either.
213
+ for (const folder of folderAddresses(pageIds)) ids.add(folder);
214
+ return ids;
215
+ }
216
+
217
+ // Page id -> ISO date of its file's last commit; filled by
218
+ // collectNoindexIds(), which reads every page anyway.
219
+ const lastModifiedById = new Map();
220
+ const noindexIds = siteUrl ? collectNoindexIds(contentDir) : new Set();
221
+
222
+ /** O @astrojs/sitemap sempre grava um sitemap-index.xml apontando para
223
+ * sitemap-0.xml, sitemap-1.xml, ... - mesmo quando há um arquivo só, que é
224
+ * o caso de todo site de docs abaixo de 50.000 páginas. Aqui o único
225
+ * sitemap-0.xml vira sitemap.xml (o endereço que crawler e ferramenta de
226
+ * SEO procuram primeiro) e o índice é apagado. Com mais de um arquivo o
227
+ * índice é necessário (o protocolo não permite um único arquivo acima de
228
+ * 50.000 URLs), então tudo fica como o plugin gravou. Um sitemap.xml
229
+ * do próprio projeto (na raiz ou em public/ - já copiado para o build por
230
+ * publishProjectFiles() ou pelo Astro) também não é sobrescrito. */
231
+ function singleSitemapFile() {
232
+ return {
233
+ name: 'writedocs-single-sitemap',
234
+ hooks: {
235
+ 'astro:build:done': ({ dir }) => {
236
+ const outDir = fileURLToPath(dir);
237
+ const chunks = fs.readdirSync(outDir).filter((f) => /^sitemap-\d+\.xml$/.test(f));
238
+ const target = path.join(outDir, 'sitemap.xml');
239
+ if (chunks.length !== 1) {
240
+ report('debug', `${chunks.length} sitemap files generated - keeping sitemap-index.xml.`);
241
+ return;
242
+ }
243
+ if (fs.existsSync(target)) {
244
+ report('info', "The project has its own sitemap.xml, so it was kept - the generated sitemap is sitemap-index.xml.");
245
+ return;
246
+ }
247
+ fs.renameSync(path.join(outDir, chunks[0]), target);
248
+ fs.rmSync(path.join(outDir, 'sitemap-index.xml'), { force: true });
249
+ // O próprio plugin acabou de logar "sitemap-index.xml created"; esta
250
+ // linha diz o que de fato ficou no build.
251
+ report('debug', `Replaced ${chunks[0]} + sitemap-index.xml with a single sitemap.xml.`);
252
+ },
253
+ },
254
+ };
255
+ }
256
+
257
+ // writedocs.json's `redirects` array -> Astro's own `redirects` config option
258
+ // (a plain `{ [source]: destination }` record - see redirectSchema in
259
+ // lib/config.ts for why there's no `permanent`/status-code field: this
260
+ // package always builds `output: 'static'` with no adapter installed, and
261
+ // Astro's own docs say a static redirect is always a client-side
262
+ // `<meta http-equiv="refresh">` page regardless of what status is asked
263
+ // for). Omitted entirely (rather than passed as `{}`) when a site has no
264
+ // redirects configured, matching the `siteUrl ? [...] : []` pattern above
265
+ // of only opting into a feature's config surface when it's actually used.
266
+ // Generated API pages that moved to a new address (lib/moved-api-pages.js)
267
+ // redirect from the old one the same way; a redirect the site wrote itself
268
+ // for the same address comes later in the list, and wins.
269
+ const movedApiPages = readMovedApiPages(contentDir);
270
+ // With a basePath, Astro serves a redirect's source under the base itself,
271
+ // but writes its destination as given - so a destination inside the site
272
+ // gets the base here (lib/base-path.js).
273
+ const redirectsConfig = Object.fromEntries([...movedApiPages, ...docsConfig.redirects].map((r) => [r.source, withBase(basePath, r.destination)]));
274
+
275
+ /** Tailwind only scans the Vite root for class names - this package, not
276
+ * the site being built, which is usually somewhere else entirely - so a
277
+ * utility class written in a site's own MDX or snippet (Mintlify content
278
+ * uses them freely, e.g. className="block dark:hidden") never got
279
+ * generated. Appends an @source for the site's content files to
280
+ * global.css before Tailwind compiles it. Forward slashes, since
281
+ * Tailwind reads the path as a glob. */
282
+ function contentTailwindSource() {
283
+ const sourceGlob = `${contentDir.split(path.sep).join('/')}/**/*.{md,mdx,jsx,tsx}`;
284
+ return {
285
+ name: 'writedocs:content-tailwind-source',
286
+ enforce: 'pre',
287
+ transform(code, id) {
288
+ if (!id.split('?')[0].replace(/\\/g, '/').endsWith('/src/styles/global.css')) return null;
289
+ return { code: `${code}\n@source ${JSON.stringify(sourceGlob)};\n`, map: null };
290
+ },
291
+ };
292
+ }
293
+
294
+ export default defineConfig({
295
+ // The origin alone: Astro adds `base` to it itself (the sitemap's URLs).
296
+ ...(siteUrl ? { site: resolveSiteOrigin(docsConfig) } : {}),
297
+ // Only with a basePath: without one the config is exactly what it was.
298
+ ...(basePath ? { base: basePath } : {}),
299
+ ...(Object.keys(redirectsConfig).length ? { redirects: redirectsConfig } : {}),
300
+ // Astro's own dev-mode toolbar (the floating pill in the bottom center
301
+ // of every page - inspect/audit/settings) is a tool for authoring
302
+ // Astro itself, not something a writedocs site's own reader/author
303
+ // should see while running `writedocs dev` - it's not exposed as a
304
+ // writedocs.json option (nothing site-specific to configure here) since
305
+ // there's no scenario where a writedocs project actually wants it on.
306
+ // Off in every environment (build never shows it anyway, since it's a
307
+ // dev-only overlay Astro strips from production output regardless).
308
+ devToolbar: { enabled: false },
309
+ // Not contentDir/dist directly - see writedocsBuildStagingDir()'s own
310
+ // comment (writedocs-temp-dir.js) for why, and build.js for the copy
311
+ // step that actually gets a finished build from here into the real
312
+ // <contentDir>/dist a reader/host ever sees. Irrelevant to `astro dev`
313
+ // (no build output involved), so this applies unconditionally rather
314
+ // than branching on which CLI command is running.
315
+ outDir: writedocsBuildStagingDir(packageRoot, contentDir),
316
+ cacheDir: path.join(writedocsTempDir(contentDir), 'cache'),
317
+ ...(fs.existsSync(contentPublicDir) ? { publicDir: contentPublicDir } : {}),
318
+ // icon() reads from whatever @iconify-json/* collections are installed
319
+ // (see package.json) and inlines only the specific icons a build
320
+ // actually references as <svg> - the installed collections don't
321
+ // affect output size beyond that. No `include` config needed: astro-icon
322
+ // resolves "collection:icon-name" against any installed collection
323
+ // automatically.
324
+ integrations: [
325
+ // markdown.processor (below) carries remarkAutoHydrateSnippets - see
326
+ // its own comment there for why it's attached there and not here.
327
+ // Auto-adds `client:load` to every usage of a component imported from
328
+ // a .jsx/.tsx file (a snippet - see docs/dev/docs/snippets.mdx) that
329
+ // doesn't already carry its own `client:*` attribute, so a snippet
330
+ // just works when dropped into a page - nobody using it needs to know
331
+ // Astro's hydration-directive syntax exists at all, only someone who
332
+ // wants a *different* strategy (client:visible/idle/only) needs to
333
+ // write one explicitly.
334
+ mdx(),
335
+ // Lets a site's own snippets (see docs/dev/docs/snippets.mdx) be real
336
+ // .jsx/.tsx React components - hooks and all - dropped straight into
337
+ // MDX and hydrated client-side as an Astro island (automatically -
338
+ // see remarkAutoHydrateSnippets above). writedocs' own built-in
339
+ // components (Callout, Card, ...) stay plain .astro files - this is
340
+ // purely for snippets a site author writes themselves.
341
+ react(),
342
+ icon(),
343
+ // A project's own files, published as they are (robots.txt, sitemap.xml,
344
+ // a PDF...) - before the sitemap integration, see
345
+ // lib/project-files-integration.js.
346
+ publishProjectFiles(contentDir),
347
+ ...(siteUrl
348
+ ? [
349
+ sitemap({
350
+ // Teto do protocolo de sitemap por arquivo (o default do
351
+ // @astrojs/sitemap é 45.000). Até aqui, tudo cabe num único
352
+ // sitemap.xml - ver singleSitemapFile() abaixo.
353
+ entryLimit: 50000,
354
+ // The plugin's URLs carry the base ("/docs/guides/a/") - the
355
+ // ids here don't.
356
+ filter: (page) => {
357
+ const pathname = withoutBase(basePath, new URL(page).pathname) ?? '/';
358
+ const id = normalizeEntryId(pathname);
359
+ return !noindexIds.has(id);
360
+ },
361
+ // <lastmod>, for the pages git has a date for.
362
+ serialize: (item) => {
363
+ const changed = lastModifiedById.get(normalizeEntryId(withoutBase(basePath, new URL(item.url).pathname) ?? '/'));
364
+ return changed ? { ...item, lastmod: changed } : item;
365
+ },
366
+ }),
367
+ // Precisa vir depois do sitemap(): o Astro roda os hooks
368
+ // astro:build:done na ordem deste array, um de cada vez.
369
+ singleSitemapFile(),
370
+ ]
371
+ : []),
372
+ // After the sitemap: the generated robots.txt names the sitemap file.
373
+ generatedRobotsTxt({ siteUrl, seo: docsConfig.seo, basePath }),
374
+ // Lets styles.favicon/styles.logo/styles.background.images/seo.ogImage/
375
+ // styles.fonts.*.source resolve from anywhere in the project, not just
376
+ // public/ - see collectConfiguredAssetPaths() (lib/config.ts) for the
377
+ // field list and styles-asset-integration.js for how it's actually
378
+ // served/copied.
379
+ stylesAssetFallback(contentDir, { basePath }),
380
+ // /mcp in `writedocs dev`, as the build's dist/_worker.js serves it -
381
+ // see src/lib/mcp-dev-integration.js.
382
+ mcpDevServer({ version: JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8')).version, basePath }),
383
+ // writedocs dev: an edit to writedocs.json reloads the open tab.
384
+ configReload({ configPath: path.join(contentDir, 'writedocs.json') }),
385
+ // writedocs dev: an edit to an OpenAPI spec regenerates its pages.
386
+ openapiReload({ contentDir, packageRoot }),
387
+ // writedocs dev, installed: a change to a page's entry (its title, an
388
+ // API page renamed) reaches the open tab.
389
+ contentStoreReload({ packageRoot }),
390
+ ],
391
+ output: 'static',
392
+ // Dual Shiki themes for fenced code blocks (```) in MDX content, so
393
+ // they switch with the site's own [data-theme] toggle instead of
394
+ // always rendering Astro's single default (github-dark) regardless of
395
+ // light/dark mode. Defaults to github-light/github-dark, overridable
396
+ // per-site via writedocs.json's styles.codeblocks.{light,dark} (any Shiki
397
+ // theme *name* - see https://shiki.style/themes for the built-in
398
+ // list - not a custom theme object/JSON file, at least for now).
399
+ // Astro bakes the "light" theme's colors as the element's base inline
400
+ // style and adds --shiki-dark/--shiki-dark-bg (etc.) custom
401
+ // properties alongside it - see the
402
+ // [data-theme='dark'] :global(.astro-code) override in
403
+ // BaseLayout.astro that actually swaps to them.
404
+ markdown: {
405
+ // Excludes ```mermaid fences from Shiki's own tokenization entirely -
406
+ // they reach rehypeMermaid (below) as plain, un-highlighted text,
407
+ // which is what mermaid.js needs to parse and render them into an
408
+ // actual diagram client-side (see [...slug].astro's initMermaid()).
409
+ // Syntax-highlighting mermaid's own pseudo-language as if it were
410
+ // source code would be actively wrong here - the goal is a rendered
411
+ // diagram, not colored diagram-description text.
412
+ syntaxHighlight: { type: 'shiki', excludeLangs: ['mermaid'] },
413
+ // Astro 7's markdown.rehypePlugins (top-level) is deprecated in favor
414
+ // of passing plugins straight to the `unified` processor itself -
415
+ // functionally identical (Astro's own deprecated-option shim used to
416
+ // just forward the top-level array into this exact processor), just
417
+ // explicit instead of relying on that shim (and the console warning
418
+ // it prints on every build/dev run). Astro still runs this *after*
419
+ // its own internal Shiki step (see @astrojs/markdown-remark's
420
+ // index.js) regardless of which processor plugins are attached to,
421
+ // so rehypeMermaid still always sees the excluded ```mermaid block
422
+ // completely untouched by Shiki - exactly the plain
423
+ // <pre><code class="language-mermaid"> shape it expects to reshape
424
+ // into mermaid.js's <div class="mermaid"> form.
425
+ // remarkInjectBuiltinComponents/remarkAutoHydrateSnippets only ever
426
+ // match JSX/import nodes that exist solely in MDX's extended syntax
427
+ // tree (see mdx-inject-builtins.js/mdx-auto-hydrate.js) - running them
428
+ // here rather than passing them to mdx({ remarkPlugins }) avoids that
429
+ // option's own deprecation warning ("pass it to unified()... MDX will
430
+ // inherit it" - extendMarkdownConfig defaults to true, so mdx() below
431
+ // already picks this processor up automatically). Harmless no-op on
432
+ // plain .md content, which never has an mdxjsEsm/mdxJsxFlowElement
433
+ // node to match in the first place.
434
+ // remarkSubstituteVariables is a parameterized plugin (an "attacher"
435
+ // that takes writedocs.json's `variables` map as its options and returns
436
+ // the actual transformer) - passed as a unified [attacher, options]
437
+ // tuple, *not* pre-called (`remarkSubstituteVariables(docsConfig.variables)`
438
+ // directly in this array). unified's own `use()` always calls
439
+ // whatever it finds in this array as if it were the attacher itself;
440
+ // handing it an already-produced transformer function makes unified
441
+ // invoke *that* with zero arguments during its `freeze()` setup pass,
442
+ // which crashes deep inside unist-util-visit ("Cannot use 'in'
443
+ // operator to search for 'children' in undefined") the first time any
444
+ // MDX page actually builds - a real bug hit and fixed while testing
445
+ // 25-site-config, not a hypothetical. remarkInjectBuiltinComponents/
446
+ // remarkAutoHydrateSnippets don't need this tuple form since neither
447
+ // takes options - they're valid attachers as bare function references.
448
+ // A site with no `variables` set still gets this plugin instance
449
+ // (which then no-ops on every file - see its own early-return) rather
450
+ // than being conditionally omitted, keeping this array's shape static
451
+ // regardless of writedocs.json content.
452
+ processor: unified({
453
+ // remarkMath goes first: it parses $inline$ and standalone $$block$$
454
+ // math into their own `inlineMath`/`math` mdast node types (mdast-
455
+ // util-to-hast has built-in support for both, turning them into a
456
+ // <span>/<div> carrying the raw LaTeX source as a "language-math"
457
+ // code-like payload for rehypeKatex, below, to render). Running it
458
+ // before remarkSubstituteVariables means a $...$ span's raw LaTeX
459
+ // source is no longer a plain `text` node by the time that plugin's
460
+ // visitor runs (it only visits `text` nodes - see its own comment) -
461
+ // not that `[[key]]` syntax inside actual LaTeX is a realistic thing
462
+ // to write, but this keeps the two plugins' node-type boundaries
463
+ // clean rather than leaving it to chance which one sees a math span
464
+ // as raw text first.
465
+ remarkPlugins: [
466
+ remarkMath,
467
+ // Mintlify's Markdown-list <Tree> and <Prompt> source text - see
468
+ // lib/mdx-mintlify.js. Before remarkInjectBuiltinComponents, so
469
+ // the <Tree.Folder>/<Tree.File> elements they add are already in
470
+ // the tree when it looks for components to import.
471
+ remarkMintlifyTreeLists,
472
+ remarkMintlifyPromptText,
473
+ // An inline component that calls React hooks moves into a generated
474
+ // .jsx file so it runs as real React (and hydrates) - see
475
+ // lib/mdx-inline-react.js. Before remarkMintlifyReactHooks, which
476
+ // imports any hooks the page itself still calls (Mintlify
477
+ // pre-injects them), and before remarkAutoHydrateSnippets, which
478
+ // hydrates the component through its new .jsx import.
479
+ remarkExtractInlineReactComponents,
480
+ remarkMintlifyReactHooks,
481
+ // An unknown component becomes a fragment (its children still
482
+ // render) with a warning, instead of failing the whole build - see
483
+ // lib/mdx-unknown-components.js. After remarkMintlifyTreeLists, so
484
+ // the <Tree.Folder>/<Tree.File> elements it adds count as known.
485
+ remarkUnknownComponentFallback,
486
+ remarkInjectBuiltinComponents,
487
+ // Runs after remarkInjectBuiltinComponents (order doesn't actually
488
+ // matter between them - that plugin only ever prepends an import
489
+ // statement, never touches an existing JSX node's attributes) but
490
+ // grouped right next to it since both deal with the same set of
491
+ // built-in component tag names. See its own comment for why this
492
+ // has to be a whole-document pass rather than logic living inside
493
+ // Callout.astro/Accordion.astro themselves.
494
+ remarkTitleAnchorIds,
495
+ remarkAutoHydrateSnippets,
496
+ [remarkSubstituteVariables, docsConfig.variables],
497
+ ],
498
+ // rehypeKatex renders every math/inlineMath node remarkMath produced
499
+ // into real KaTeX markup (a <span class="katex">...</span> tree of
500
+ // MathML + HTML, not an image or client-rendered widget) - fully at
501
+ // build time, so unlike Mermaid there's no client-side JS or runtime
502
+ // cost at all, just the one katex.min.css import (BaseLayout.astro)
503
+ // for layout/glyph styling. Order relative to rehypeMermaid doesn't
504
+ // matter - they walk disjoint hast node shapes (pre>code.language-
505
+ // mermaid vs. remarkMath's own math/inlineMath-derived nodes) and
506
+ // neither plugin's output is visible to the other.
507
+ // rehypeImageLoading: lazy loading and sizes for content images - see
508
+ // lib/rehype-image-loading.js.
509
+ // rehypeBasePath: the basePath in front of the content's own links and
510
+ // pictures (lib/rehype-base-path.js) - last, since rehypeImageLoading
511
+ // finds an image's file by the address as written.
512
+ rehypePlugins: [rehypeMermaid, rehypeKatex, [rehypeImageLoading, { contentDir }], [rehypeBasePath, { base: basePath }]],
513
+ }),
514
+ shikiConfig: {
515
+ themes: codeblockTheme,
516
+ langAlias: codeblockLangAlias,
517
+ // The official @shikijs/transformers annotation transformers -
518
+ // enabled sitewide so any fenced code block can use their meta-
519
+ // string/comment syntax without per-page opt-in:
520
+ // ```js {1,3-5} -> transformerMetaHighlight
521
+ // ```js /someWord/ -> transformerMetaWordHighlight
522
+ // // [!code highlight] -> transformerNotationHighlight
523
+ // // [!code word:someWord] -> transformerNotationWordHighlight
524
+ // // [!code focus] -> transformerNotationFocus
525
+ // // [!code ++] / // [!code --] -> transformerNotationDiff
526
+ // // [!code error] / [!code warning] -> transformerNotationErrorLevel
527
+ // (comment syntax adapts to the language - # for Python/bash, //
528
+ // for JS/etc - see each transformer's own docs at shiki.style).
529
+ // Plus codeBlockTransformer, writedocs' own transformer for the
530
+ // copy button, an optional title bar, and wrap/lines/expandable
531
+ // meta flags - see src/lib/shiki-code-block.js. It runs last so
532
+ // its `root` hook wraps the <pre> only after every class the
533
+ // transformers above added to it is already in place - though in
534
+ // practice this doesn't matter, since all `pre`/`line` hooks
535
+ // across every transformer run to completion before any `root`
536
+ // hook runs at all (two separate passes, not interleaved).
537
+ transformers: [
538
+ transformerMetaHighlight(),
539
+ transformerMetaWordHighlight(),
540
+ transformerNotationHighlight(),
541
+ transformerNotationWordHighlight(),
542
+ transformerNotationFocus(),
543
+ transformerNotationDiff(),
544
+ transformerNotationErrorLevel(),
545
+ codeBlockTransformer(),
546
+ ],
547
+ },
548
+ },
549
+ // Tailwind is available for future/custom content (e.g. hand-authored
550
+ // MDX) but nothing in writedocs' own components has been migrated to
551
+ // it - they still use scoped <style> blocks + the --wd-* CSS variables
552
+ // so per-site writedocs.json theming (colors, and now dark mode) keeps
553
+ // working. See src/styles/global.css for the one @import that wires
554
+ // Tailwind's utilities in.
555
+ vite: {
556
+ // The base for page scripts and components: "" or "/docs". A constant
557
+ // rather than import.meta.env.BASE_URL ("/" with no base, "/docs" or
558
+ // "/docs/" with one), so `__WD_BASE__ + "/pagefind/..."` folds to the
559
+ // same string the bundle had before basePath existed.
560
+ define: { __WD_BASE__: JSON.stringify(basePath) },
561
+ // The dev server only serves files under its workspace root by default.
562
+ // A site's own snippets live in its content directory, and inline React
563
+ // components moved out of pages (lib/mdx-inline-react.js) in writedocs'
564
+ // temp directory - both need to reach the browser to hydrate. Setting
565
+ // `allow` replaces Vite's default rather than adding to it, so the
566
+ // package's dependencies must stay reachable too: when writedocs is
567
+ // installed, they sit next to it in the node_modules folder that
568
+ // contains it (React's own hydration client included), not inside
569
+ // packageRoot - see dependencyRoot above.
570
+ server: {
571
+ fs: {
572
+ allow: [packageRoot, dependencyRoot, contentDir, writedocsTempDir(contentDir)],
573
+ },
574
+ },
575
+ // contentTailwindSource() must come before tailwindcss(): both are
576
+ // enforce: 'pre' transforms, which Vite runs in array order, and
577
+ // Tailwind has to see the added @source when it compiles global.css.
578
+ // mintlifyReactHooksPlugin() does for a site's .jsx/.tsx snippets what
579
+ // remarkMintlifyReactHooks does for its MDX pages.
580
+ // iconDataFromFile() (writedocs dev only): astro-icon's ~15 MB of icon
581
+ // data read from a file rather than passed through Vite - about 5 s of
582
+ // every dev preview's first page (see src/lib/icon-data-dev.js).
583
+ plugins: [contentTailwindSource(), tailwindcss(), mintlifyReactHooksPlugin(contentDir), iconDataFromFile(writedocsTempDir(contentDir))],
584
+ // `writedocs dev`: Vite only prepares for the browser the dependencies
585
+ // it finds by scanning the project's own source - and when writedocs is
586
+ // installed, its source sits in node_modules, which the scan skips. The
587
+ // page script's `import("mermaid")` ([...slug].astro) was then served
588
+ // as it is, and its CommonJS dependencies failed in the browser ("dayjs
589
+ // ... does not provide an export named 'default'"): diagrams stayed as
590
+ // text in dev, while builds were fine. Naming it here prepares it always.
591
+ optimizeDeps: {
592
+ include: ['mermaid'],
593
+ },
594
+ resolve: {
595
+ alias: [
596
+ // Lets a page's MDX write `import Foo from '/snippets/foo.mdx'`
597
+ // (Mintlify's own snippet-import convention) instead of a
598
+ // relative path whose "../" depth depends on how deeply nested
599
+ // the importing page happens to be - see docs/dev/docs/snippets.mdx
600
+ // for the full feature writeup. Vite's project root is always
601
+ // packageRoot (this package itself - see run-astro.js), not
602
+ // contentDir, so a real leading-slash import would otherwise
603
+ // resolve (and fail to find anything) inside this package
604
+ // instead of the site's own content directory; this alias
605
+ // redirects just that one prefix to contentDir/snippets/ instead.
606
+ { find: /^\/snippets\//, replacement: path.join(contentDir, 'snippets') + '/' },
607
+ // remarkInjectBuiltinComponents (mdx-inject-builtins.js) auto-
608
+ // injects `import { Callout, ... } from 'writedocs/components'`
609
+ // into any .mdx file that uses a built-in component tag without
610
+ // importing it itself - a real bare specifier Vite has to resolve
611
+ // as if the .mdx file had written it. package.json's own
612
+ // `exports: { "./components": "./src/components/index.ts" }`
613
+ // makes that specifier valid *in principle* (Node's package
614
+ // self-reference feature - a package importing its own name), but
615
+ // self-reference only resolves when the importing file is a
616
+ // descendant of this package's own package.json - true for every
617
+ // existing fixture (always built from inside this repo/package
618
+ // tree) but never true for a real consumer's content, which lives
619
+ // in a completely separate directory in the actual product
620
+ // architecture (see docs/dev/docs/architecture.mdx) - walking up
621
+ // from such a file never finds a package.json named "writedocs",
622
+ // so self-reference fails and Vite reports the bare specifier as
623
+ // unresolvable ("Rolldown failed to resolve import
624
+ // 'writedocs/components'").
625
+ // This alias bypasses self-reference resolution entirely for
626
+ // that one specifier - Vite's alias matching is a plain string
627
+ // match against the specifier itself, independent of which file
628
+ // imported it, so it resolves correctly regardless of where the
629
+ // content directory actually lives. WRITEDOCS_PACKAGE_ROOT is the
630
+ // same packageRoot value already set by run-astro.js for
631
+ // lib/config.ts's fileIdForEntry() to consume - reusing it here
632
+ // instead of recomputing via import.meta.url keeps there being
633
+ // exactly one source of truth for "where this package lives" per
634
+ // astro subprocess. Falls back to this file's own directory
635
+ // (astro.config.mjs always lives at packageRoot) for anything
636
+ // that ever imports this config outside that subprocess, e.g. a
637
+ // future test harness.
638
+ {
639
+ find: 'writedocs/components',
640
+ replacement: path.join(packageRoot, 'src/components/index.ts'),
641
+ },
642
+ ],
643
+ },
644
+ },
645
+ });