doccupine 0.0.158 → 0.0.160

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 (158) hide show
  1. package/README.md +56 -4
  2. package/dist/generator/app-scaffolder.js +11 -3
  3. package/dist/generator/generated-page-publisher.d.ts +6 -6
  4. package/dist/generator/generated-page-publisher.js +7 -5
  5. package/dist/generator/mdx-pass-builder.d.ts +4 -4
  6. package/dist/generator/mdx-pass-builder.js +8 -1
  7. package/dist/generator/mdx-reconciliation-coordinator.d.ts +23 -9
  8. package/dist/generator/mdx-reconciliation-coordinator.js +63 -9
  9. package/dist/generator/page-catalog.d.ts +2 -4
  10. package/dist/generator/page-catalog.js +7 -2
  11. package/dist/generator/page-renderer.d.ts +15 -5
  12. package/dist/generator/page-renderer.js +38 -11
  13. package/dist/generator/project-config-repository.d.ts +4 -1
  14. package/dist/generator/project-config-repository.js +26 -0
  15. package/dist/generator/public-asset-manager.d.ts +10 -0
  16. package/dist/generator/public-asset-manager.js +63 -3
  17. package/dist/generator/section-index-generator.d.ts +10 -1
  18. package/dist/generator/section-index-generator.js +43 -15
  19. package/dist/generator/section-resolver.d.ts +8 -0
  20. package/dist/generator/site-artifacts.d.ts +4 -3
  21. package/dist/generator/site-artifacts.js +94 -9
  22. package/dist/generator/watch-coordinator.js +6 -1
  23. package/dist/lib/generated-artifacts.d.ts +3 -0
  24. package/dist/lib/generated-artifacts.js +36 -0
  25. package/dist/lib/layout.d.ts +6 -3
  26. package/dist/lib/layout.js +107 -4
  27. package/dist/lib/metadata.d.ts +7 -0
  28. package/dist/lib/metadata.js +33 -10
  29. package/dist/lib/structures.js +20 -0
  30. package/dist/lib/types.d.ts +28 -0
  31. package/dist/lib/ui-strings.d.ts +44 -0
  32. package/dist/lib/ui-strings.js +48 -0
  33. package/dist/lib/variants.d.ts +91 -0
  34. package/dist/lib/variants.js +411 -0
  35. package/dist/mdx-to-nextjs-generator.d.ts +22 -5
  36. package/dist/mdx-to-nextjs-generator.js +89 -10
  37. package/dist/templates/app/api/mcp/route.d.ts +1 -1
  38. package/dist/templates/app/api/mcp/route.js +14 -1
  39. package/dist/templates/app/api/rag/route.d.ts +1 -1
  40. package/dist/templates/app/api/rag/route.js +13 -2
  41. package/dist/templates/app/api/search/route.d.ts +1 -1
  42. package/dist/templates/app/api/search/route.js +16 -1
  43. package/dist/templates/app/sitemap.d.ts +2 -0
  44. package/dist/templates/app/sitemap.js +48 -3
  45. package/dist/templates/components/Chat.d.ts +1 -1
  46. package/dist/templates/components/Chat.js +40 -12
  47. package/dist/templates/components/Docs.d.ts +1 -1
  48. package/dist/templates/components/Docs.js +5 -2
  49. package/dist/templates/components/DocsSideBar.d.ts +1 -1
  50. package/dist/templates/components/DocsSideBar.js +3 -1
  51. package/dist/templates/components/SearchDocs.d.ts +1 -1
  52. package/dist/templates/components/SearchDocs.js +17 -3
  53. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  54. package/dist/templates/components/SearchModalContent.js +22 -14
  55. package/dist/templates/components/SectionNavProvider.d.ts +1 -1
  56. package/dist/templates/components/SectionNavProvider.js +32 -20
  57. package/dist/templates/components/SideBar.d.ts +1 -1
  58. package/dist/templates/components/SideBar.js +26 -12
  59. package/dist/templates/components/layout/ActionBar.d.ts +1 -1
  60. package/dist/templates/components/layout/ActionBar.js +9 -7
  61. package/dist/templates/components/layout/Code.d.ts +1 -1
  62. package/dist/templates/components/layout/Code.js +6 -3
  63. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  64. package/dist/templates/components/layout/DocsComponents.js +38 -5
  65. package/dist/templates/components/layout/DocsNavigation.d.ts +1 -1
  66. package/dist/templates/components/layout/DocsNavigation.js +4 -2
  67. package/dist/templates/components/layout/Dropdown.d.ts +1 -0
  68. package/dist/templates/components/layout/Dropdown.js +308 -0
  69. package/dist/templates/components/layout/FocusModeToggle.d.ts +1 -1
  70. package/dist/templates/components/layout/FocusModeToggle.js +7 -4
  71. package/dist/templates/components/layout/Footer.d.ts +1 -1
  72. package/dist/templates/components/layout/Footer.js +4 -2
  73. package/dist/templates/components/layout/Header.d.ts +1 -1
  74. package/dist/templates/components/layout/Header.js +18 -8
  75. package/dist/templates/components/layout/SectionBar.d.ts +1 -1
  76. package/dist/templates/components/layout/SectionBar.js +16 -10
  77. package/dist/templates/components/layout/VariantSwitchers.d.ts +1 -0
  78. package/dist/templates/components/layout/VariantSwitchers.js +313 -0
  79. package/dist/templates/components/useStrings.d.ts +1 -0
  80. package/dist/templates/components/useStrings.js +10 -0
  81. package/dist/templates/components/useVariant.d.ts +1 -0
  82. package/dist/templates/components/useVariant.js +13 -0
  83. package/dist/templates/env.example.d.ts +1 -1
  84. package/dist/templates/env.example.js +2 -1
  85. package/dist/templates/llms/llmsIndex.d.ts +13 -0
  86. package/dist/templates/llms/llmsIndex.js +18 -3
  87. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  88. package/dist/templates/mdx/ai-assistant.mdx.js +9 -3
  89. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  90. package/dist/templates/mdx/api-playground.mdx.js +2 -0
  91. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  92. package/dist/templates/mdx/commands.mdx.js +1 -1
  93. package/dist/templates/mdx/fonts.mdx.d.ts +1 -1
  94. package/dist/templates/mdx/fonts.mdx.js +1 -1
  95. package/dist/templates/mdx/footer-links.mdx.d.ts +1 -1
  96. package/dist/templates/mdx/footer-links.mdx.js +1 -1
  97. package/dist/templates/mdx/index.mdx.d.ts +1 -1
  98. package/dist/templates/mdx/index.mdx.js +2 -0
  99. package/dist/templates/mdx/languages.mdx.d.ts +1 -0
  100. package/dist/templates/mdx/languages.mdx.js +94 -0
  101. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  102. package/dist/templates/mdx/media-and-assets.mdx.js +1 -1
  103. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  104. package/dist/templates/mdx/model-context-protocol.mdx.js +6 -0
  105. package/dist/templates/mdx/navigation.mdx.d.ts +1 -1
  106. package/dist/templates/mdx/navigation.mdx.js +2 -0
  107. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  108. package/dist/templates/mdx/platform/ai-assistant.mdx.js +2 -0
  109. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  110. package/dist/templates/mdx/platform/api-playground.mdx.js +2 -0
  111. package/dist/templates/mdx/platform/file-editor.mdx.d.ts +1 -1
  112. package/dist/templates/mdx/platform/file-editor.mdx.js +2 -0
  113. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  114. package/dist/templates/mdx/platform/index.mdx.js +1 -1
  115. package/dist/templates/mdx/platform/languages.mdx.d.ts +1 -0
  116. package/dist/templates/mdx/platform/languages.mdx.js +50 -0
  117. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  118. package/dist/templates/mdx/platform/mcp.mdx.js +2 -0
  119. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  120. package/dist/templates/mdx/platform/navigation-settings.mdx.js +2 -0
  121. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  122. package/dist/templates/mdx/platform/publishing.mdx.js +4 -0
  123. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  124. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +2 -0
  125. package/dist/templates/mdx/platform/versions.mdx.d.ts +1 -0
  126. package/dist/templates/mdx/platform/versions.mdx.js +33 -0
  127. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  128. package/dist/templates/mdx/sections.mdx.js +1 -1
  129. package/dist/templates/mdx/theme.mdx.d.ts +1 -1
  130. package/dist/templates/mdx/theme.mdx.js +1 -1
  131. package/dist/templates/mdx/versions.mdx.d.ts +1 -0
  132. package/dist/templates/mdx/versions.mdx.js +78 -0
  133. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  134. package/dist/templates/mdx/what-is-doccupine.mdx.js +1 -1
  135. package/dist/templates/package.js +20 -20
  136. package/dist/templates/prettierignore.d.ts +1 -1
  137. package/dist/templates/prettierignore.js +2 -0
  138. package/dist/templates/services/llm/config.d.ts +1 -1
  139. package/dist/templates/services/llm/config.js +50 -3
  140. package/dist/templates/services/llm/factory.d.ts +1 -1
  141. package/dist/templates/services/llm/factory.js +6 -3
  142. package/dist/templates/services/llm/types.d.ts +1 -1
  143. package/dist/templates/services/llm/types.js +2 -1
  144. package/dist/templates/services/mcp/server.d.ts +1 -1
  145. package/dist/templates/services/mcp/server.js +54 -10
  146. package/dist/templates/services/mcp/tools.d.ts +1 -1
  147. package/dist/templates/services/mcp/tools.js +81 -6
  148. package/dist/templates/services/mcp/types.d.ts +1 -1
  149. package/dist/templates/services/mcp/types.js +10 -0
  150. package/dist/templates/services/search.d.ts +1 -1
  151. package/dist/templates/services/search.js +34 -4
  152. package/dist/templates/utils/orderNavItems.d.ts +1 -1
  153. package/dist/templates/utils/orderNavItems.js +2 -0
  154. package/dist/templates/utils/strings.d.ts +1 -0
  155. package/dist/templates/utils/strings.js +27 -0
  156. package/dist/templates/utils/variants.d.ts +1 -0
  157. package/dist/templates/utils/variants.js +170 -0
  158. package/package.json +11 -11
package/README.md CHANGED
@@ -161,6 +161,52 @@ Each entry has:
161
161
  ]
162
162
  ```
163
163
 
164
+ ## Languages
165
+
166
+ Translate your docs by adding a `languages.json` file in your project root and one folder per language inside the docs directory. The default language stays at the docs root with unprefixed URLs; every other language lives in a folder named after its code, which is also its URL prefix:
167
+
168
+ ```json
169
+ [
170
+ { "code": "en", "label": "English", "default": true },
171
+ { "code": "de", "label": "Deutsch" }
172
+ ]
173
+ ```
174
+
175
+ ```text
176
+ docs/
177
+ guides/intro.mdx -> /guides/intro
178
+ de/guides/intro.mdx -> /de/guides/intro
179
+ ```
180
+
181
+ - `code` - a lowercase URL segment (`en`, `de`, `pt-br`); the folder name, the URL prefix, and the `lang`/`hreflang` value
182
+ - `label` - the name shown in the sidebar's language dropdown, on the footer row with the focus-mode and theme toggles
183
+ - `default` - exactly one entry; its pages live at the docs root
184
+ - `strings` (optional) - overrides for the generated site's own labels in that language (search box, sidebar, "On this page", previous/next, action bar, code blocks, AI chat, footer); the key list is documented on the generated site's Languages page
185
+
186
+ Only translated pages exist in a language (an untranslated page is a 404 under that prefix, and the switcher falls back to the language's home). The sidebar, search, AI chat, and `llms.txt` are scoped to the current language; translated pages carry `hreflang` alternates with an `x-default`, and the sitemap lists them. A language code must not collide with a section slug, a version slug, or the reserved segments `api`, `gate`, `mcp`, and `ingest`.
187
+
188
+ ## Versions
189
+
190
+ Keep older releases online by adding a `versions.json` file in your project root and one folder per older version. The default version is the docs root; every other version is a folder named after its slug holding a full copy of the docs as they were:
191
+
192
+ ```json
193
+ [
194
+ { "label": "v2.0", "default": true },
195
+ { "slug": "v1", "label": "v1.0" }
196
+ ]
197
+ ```
198
+
199
+ ```text
200
+ docs/
201
+ guides/intro.mdx -> /guides/intro
202
+ v1/guides/intro.mdx -> /v1/guides/intro
203
+ de/v1/guides/intro.mdx -> /de/v1/guides/intro
204
+ ```
205
+
206
+ The default entry has no `slug`. Versions combine with languages; the language folder comes first. The sidebar shows a version dropdown on the footer row with the focus-mode and theme toggles, and the sidebar, search, AI chat, and `llms.txt` are scoped to the current version. The API reference generated from an OpenAPI spec is published in the default language and version only.
207
+
208
+ For both features, `navigation.json` in object form is keyed by URL prefix: `""`, `"api"`, `"de"`, `"de/api"`, `"v1"`, `"de/v1/api"`. Existing files keyed by section slug keep working.
209
+
164
210
  ## API Reference
165
211
 
166
212
  Point Doccupine at an OpenAPI document (`.json`, `.yaml`, or `.yml`, OpenAPI 3.0/3.1) and it generates an interactive API reference: a directory at `/api-reference` linking every operation, plus one page per operation with a live playground for sending requests. Set the `openapi` field in `doccupine.json`:
@@ -206,6 +252,8 @@ Place these JSON files in your project root (where you run `doccupine`). They ar
206
252
  | `links.json` | Static header/footer links |
207
253
  | `fonts.json` | Font configuration (Google Fonts or local) |
208
254
  | `sections.json` | Section definitions for tabbed doc groups (see [Sections](#sections)) |
255
+ | `languages.json` | Languages and their folders (see [Languages](#languages)) |
256
+ | `versions.json` | Documentation versions and their folders (see [Versions](#versions)) |
209
257
  | `analytics.json` | Analytics provider configuration (PostHog supported) |
210
258
 
211
259
  ## Public Directory
@@ -235,6 +283,8 @@ Doccupine generates [llms.txt](https://llmstxt.org) artifacts so AI agents can d
235
283
  | `llms-full.txt` | Full-text bundle: every page's body concatenated for one-shot ingestion |
236
284
  | `public/<slug>.md` | Per-page Markdown mirror of each MDX page, suitable for direct fetching at `/<slug>.md` |
237
285
 
286
+ With [languages](#languages) or [versions](#versions) configured, the root `llms.txt` and `llms-full.txt` describe the default language and version and link to the other variants, each of which has its own pair under its URL prefix (`/de/llms.txt`, `/v1/llms-full.txt`).
287
+
238
288
  The site name and description used in `llms.txt` come from `config.json` (`name`, `description`). Page URLs are absolute when `url` is set in `config.json` (or via `NEXT_PUBLIC_SITE_URL`), and root-relative otherwise.
239
289
 
240
290
  A `.doccupine-artifacts.json` file in the generated app tracks generated route ownership and per-page mirrors so renamed or deleted sources clean up only their own outputs. Don't commit this file; it is regenerated automatically.
@@ -259,14 +309,16 @@ If `LLM_PROVIDER` is not set, the chat component is hidden automatically.
259
309
  ### Optional overrides
260
310
 
261
311
  ```env
262
- LLM_CHAT_MODEL=gpt-4.1-nano # Override the default chat model
312
+ LLM_CHAT_MODEL=gpt-4.1-mini # Override the default chat model
263
313
  LLM_EMBEDDING_MODEL=text-embedding-3-small # Override the default embedding model
264
- LLM_TEMPERATURE=0 # Set temperature (0-1, default: 0)
314
+ LLM_TEMPERATURE=0 # Set temperature (default: 0; "default" sends none)
265
315
  LLM_EMBEDDING_DIMS=512 # Dimensions for the prebuilt search index (default: 512)
266
316
  RAG_RUNTIME_EMBED_MAX_CHUNKS=400 # Max chunks embedded on demand in production (default: 400; 0 requires a prebuilt index)
267
317
  # RAG_API_KEY=... # Optional bearer auth for direct /api/rag requests
268
318
  ```
269
319
 
320
+ `LLM_TEMPERATURE` accepts 0 to 1 for Anthropic and 0 to 2 for OpenAI and Google; an invalid value is ignored with a warning. OpenAI's reasoning models (`o3`, `o4-mini`) and its GPT-5 models onwards reject a custom temperature, so none is sent to them.
321
+
270
322
  `LLM_EMBEDDING_DIMS` Matryoshka-truncates document vectors so the prebuilt search index stays small; lower values shrink the index at a slight cost to recall. `RAG_RUNTIME_EMBED_MAX_CHUNKS` caps how many chunks the chat will embed on demand in production before requiring a prebuilt index (it's unlimited under `next dev`).
271
323
 
272
324
  Public documentation leaves browser chat available by default. Setting `RAG_API_KEY` requires a bearer token for `/api/rag` and is intended for server-to-server use; the built-in browser cannot safely hold that secret. Use `SITE_PASSWORD` instead when authenticated browser visitors should retain chat access.
@@ -275,7 +327,7 @@ Default models per provider:
275
327
 
276
328
  | Provider | Chat model | Embedding model |
277
329
  | --------- | ---------------------------- | ------------------------ |
278
- | OpenAI | `gpt-4.1-nano` | `text-embedding-3-small` |
330
+ | OpenAI | `gpt-4.1-mini` | `text-embedding-3-small` |
279
331
  | Anthropic | `claude-sonnet-4-5-20250929` | OpenAI fallback |
280
332
  | Google | `gemini-2.5-flash-lite` | `gemini-embedding-001` |
281
333
 
@@ -287,7 +339,7 @@ The generated app exposes an MCP endpoint at `/api/mcp` with three tools:
287
339
  - `get_doc` - retrieve a specific document by path
288
340
  - `list_docs` - list all available documents
289
341
 
290
- This lets AI agents (Claude, ChatGPT, etc.) query your docs programmatically. Semantic `search_docs` requires the AI setup above for embeddings; `get_doc` and `list_docs` work from the generated content manifest without an embedding provider.
342
+ This lets AI agents (Claude, ChatGPT, etc.) query your docs programmatically. Semantic `search_docs` requires the AI setup above for embeddings; `get_doc` and `list_docs` work from the generated content manifest without an embedding provider. On a site with [languages](#languages) or [versions](#versions), `search_docs` and `list_docs` accept optional `language` and `version` parameters and default to the default language and version; the `docs://list` resource lists every variant.
291
343
 
292
344
  ## Password Protection
293
345
 
@@ -16,6 +16,12 @@ export class AppScaffolder {
16
16
  return resolveOutputPath(this.outputDir, ...segments);
17
17
  }
18
18
  async createNextJsStructure(analyticsConfig, callbacks) {
19
+ // Render the layouts before touching the output: both read the docs
20
+ // sources and abort on a broken project (route collision, misplaced
21
+ // language folder), and a promise created eagerly here would reject as
22
+ // unhandled while the loop below is still writing earlier files.
23
+ const rootLayout = await callbacks.generateRootLayout();
24
+ const siteLayout = await callbacks.generateSiteLayout();
19
25
  // Everything under app/ is generated, so clear stale routes before writing
20
26
  // the current structure. Other generated directories remain untouched.
21
27
  await fs.remove(this.outputPath("app"));
@@ -28,18 +34,20 @@ export class AppScaffolder {
28
34
  "analytics.json": `{}\n`,
29
35
  "config.json": `{}\n`,
30
36
  "icons.json": `{}\n`,
37
+ "languages.json": `[]\n`,
31
38
  "links.json": `[]\n`,
32
39
  "navigation.json": `[]\n`,
33
40
  "sections.json": `[]\n`,
34
41
  "theme.json": `{}\n`,
42
+ "versions.json": `[]\n`,
35
43
  "app/robots.ts": robotsTemplate,
36
- "app/layout.tsx": callbacks.generateRootLayout(),
37
- "app/(site)/layout.tsx": callbacks.generateSiteLayout(),
44
+ "app/layout.tsx": rootLayout,
45
+ "app/(site)/layout.tsx": siteLayout,
38
46
  };
39
47
  for (const [filePath, content] of Object.entries(structure)) {
40
48
  const fullPath = this.outputPath(filePath);
41
49
  await fs.ensureDir(path.dirname(fullPath));
42
- await writeFileAtomic(fullPath, String(await content));
50
+ await writeFileAtomic(fullPath, content);
43
51
  }
44
52
  await callbacks.updateSitemap();
45
53
  await callbacks.updateLlmsFiles();
@@ -1,6 +1,6 @@
1
1
  import type { MDXFile } from "../lib/types.js";
2
2
  import type { OperationDescriptor } from "../lib/openapi-types.js";
3
- import { type HomepageSource } from "./page-renderer.js";
3
+ import { type HomepageSource, type RenderPageOptions, type RenderVariantOptions } from "./page-renderer.js";
4
4
  import { GeneratedRouteManager } from "./generated-route-manager.js";
5
5
  export interface GeneratedPageCommit {
6
6
  rollback(): Promise<void>;
@@ -13,9 +13,9 @@ export declare class GeneratedPagePublisher {
13
13
  private readGeneratedFile;
14
14
  private restoreGeneratedFile;
15
15
  private commitRenderedPage;
16
- generatePageFromMdx(mdxFile: MDXFile, options?: {
17
- apiOperation?: OperationDescriptor;
18
- }): Promise<GeneratedPageCommit>;
19
- updateHomepage(source: HomepageSource | null, apiOperation?: OperationDescriptor): Promise<GeneratedPageCommit>;
20
- updateSectionIndex(sectionSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string): Promise<GeneratedPageCommit>;
16
+ generatePageFromMdx(mdxFile: MDXFile, options?: RenderPageOptions): Promise<GeneratedPageCommit>;
17
+ updateHomepage(source: HomepageSource | null, apiOperation?: OperationDescriptor, options?: RenderVariantOptions): Promise<GeneratedPageCommit>;
18
+ /** `routeSlug` is the full route of the section index (`api`, or
19
+ * `de/api` inside a language folder), not just the section slug. */
20
+ updateSectionIndex(routeSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string, options?: RenderVariantOptions): Promise<GeneratedPageCommit>;
21
21
  }
@@ -109,15 +109,17 @@ export class GeneratedPagePublisher {
109
109
  await fs.ensureDir(path.dirname(pagePath));
110
110
  return this.commitRenderedPage(pagePath, rendered);
111
111
  }
112
- async updateHomepage(source, apiOperation) {
113
- const rendered = renderHomepage(source, apiOperation);
112
+ async updateHomepage(source, apiOperation, options = {}) {
113
+ const rendered = renderHomepage(source, apiOperation, options);
114
114
  const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", "page.tsx");
115
115
  await fs.ensureDir(path.dirname(pagePath));
116
116
  return this.commitRenderedPage(pagePath, rendered);
117
117
  }
118
- async updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath) {
119
- const rendered = renderSectionPage(sectionSlug, frontmatter, mdxContent, sourcePath);
120
- const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", sectionSlug, "page.tsx");
118
+ /** `routeSlug` is the full route of the section index (`api`, or
119
+ * `de/api` inside a language folder), not just the section slug. */
120
+ async updateSectionIndex(routeSlug, frontmatter, mdxContent, sourcePath, options = {}) {
121
+ const rendered = renderSectionPage(routeSlug, frontmatter, mdxContent, sourcePath, options);
122
+ const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", routeSlug, "page.tsx");
121
123
  await fs.ensureDir(path.dirname(pagePath));
122
124
  return this.commitRenderedPage(pagePath, rendered);
123
125
  }
@@ -1,5 +1,7 @@
1
1
  import type { Stats } from "node:fs";
2
2
  import type { PageMeta, SectionConfig } from "../lib/types.js";
3
+ import { type VariantSet } from "../lib/variants.js";
4
+ import { type ResolvedPageRoute } from "./section-resolver.js";
3
5
  import { SecureSourceFs } from "./secure-source-fs.js";
4
6
  export interface MdxSourceSnapshot {
5
7
  content: string;
@@ -17,11 +19,9 @@ interface MdxPassBuilderOptions {
17
19
  getSections(): SectionConfig[] | null;
18
20
  loadSectionsConfig(): Promise<SectionConfig[] | null>;
19
21
  withApiReferenceSection(sections: SectionConfig[] | null): SectionConfig[] | null;
20
- determineSectionForFile(filePath: string, frontmatter: Record<string, any>, sections: SectionConfig[] | null): {
21
- sectionSlug: string;
22
- pageSlug: string;
23
- };
22
+ determineSectionForFile(filePath: string, frontmatter: Record<string, any>, sections: SectionConfig[] | null): ResolvedPageRoute;
24
23
  resolveHttpMethod(reference: string): string | undefined;
24
+ getVariants(): VariantSet;
25
25
  }
26
26
  export declare class MdxPassBuilder {
27
27
  private readonly options;
@@ -1,6 +1,7 @@
1
1
  import { safeMatter } from "../lib/utils.js";
2
+ import { assertVariantLayout, assertVariantsDisjoint, } from "../lib/variants.js";
2
3
  import { buildRealPagesMeta, parseMdxPageMeta } from "./page-catalog.js";
3
- import { discoverSections } from "./section-resolver.js";
4
+ import { discoverSections, } from "./section-resolver.js";
4
5
  export class MdxPassBuilder {
5
6
  options;
6
7
  constructor(options) {
@@ -34,6 +35,12 @@ export class MdxPassBuilder {
34
35
  sections = this.options.withApiReferenceSection(discoverSections(documents));
35
36
  }
36
37
  }
38
+ // Variant folders are resolved before sections, so a layout mistake or a
39
+ // section that claims a variant's folder aborts the pass the same way a
40
+ // route collision does, before any page is written.
41
+ const { languages, versions } = this.options.getVariants();
42
+ assertVariantLayout(resolvedFiles, languages, versions);
43
+ assertVariantsDisjoint(languages, versions, sections);
37
44
  const pages = await buildRealPagesMeta(resolvedFiles, async (file) => {
38
45
  const source = sources.get(file.replace(/\\/g, "/"));
39
46
  if (!source)
@@ -1,9 +1,11 @@
1
1
  import type { RouteArtifact } from "../lib/generated-artifacts.js";
2
2
  import type { OperationDescriptor } from "../lib/openapi-types.js";
3
3
  import type { MDXFile, PageMeta, SectionConfig } from "../lib/types.js";
4
+ import { type VariantSet } from "../lib/variants.js";
4
5
  import type { GeneratedPageCommit } from "./generated-page-publisher.js";
5
6
  import { GeneratedRouteManager } from "./generated-route-manager.js";
6
- import { type HomepageSource } from "./page-renderer.js";
7
+ import { type HomepageSource, type RenderPageOptions, type RenderVariantOptions } from "./page-renderer.js";
8
+ import type { ResolvedPageRoute } from "./section-resolver.js";
7
9
  import { SecureSourceFs } from "./secure-source-fs.js";
8
10
  interface MdxReconciliationCoordinatorOptions {
9
11
  sourceFs: SecureSourceFs;
@@ -13,10 +15,8 @@ interface MdxReconciliationCoordinatorOptions {
13
15
  setSections(sections: SectionConfig[] | null): void;
14
16
  loadSectionsConfig(): Promise<SectionConfig[] | null>;
15
17
  withApiReferenceSection(sections: SectionConfig[] | null): SectionConfig[] | null;
16
- determineSectionForFile(filePath: string, frontmatter: Record<string, any>, sections?: SectionConfig[] | null): {
17
- sectionSlug: string;
18
- pageSlug: string;
19
- };
18
+ determineSectionForFile(filePath: string, frontmatter: Record<string, any>, sections?: SectionConfig[] | null): ResolvedPageRoute;
19
+ getVariants(): VariantSet;
20
20
  lookupOpenApi(reference: string): OperationDescriptor | undefined;
21
21
  isOpenApiRegistryEmpty(): boolean;
22
22
  syntheticOpenApiPages(): PageMeta[];
@@ -26,10 +26,8 @@ interface MdxReconciliationCoordinatorOptions {
26
26
  source: string;
27
27
  slug: string;
28
28
  }>): Promise<void>;
29
- generatePageFromMdx(mdxFile: MDXFile, options?: {
30
- apiOperation?: OperationDescriptor;
31
- }): Promise<GeneratedPageCommit>;
32
- updateSectionIndex(sectionSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string): Promise<GeneratedPageCommit>;
29
+ generatePageFromMdx(mdxFile: MDXFile, options?: RenderPageOptions): Promise<GeneratedPageCommit>;
30
+ updateSectionIndex(routeSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string, options?: RenderVariantOptions): Promise<GeneratedPageCommit>;
33
31
  writeApiPages(realPages?: PageMeta[]): Promise<Map<string, string>>;
34
32
  updatePagesIndex(pages?: readonly PageMeta[]): Promise<void>;
35
33
  updateRootLayout(pages?: PageMeta[]): Promise<void>;
@@ -49,8 +47,24 @@ export declare class MdxReconciliationCoordinator {
49
47
  private successfulMdxContent;
50
48
  private successfulMdxSourcesBySlug;
51
49
  private collisionBlockedMdxSources;
50
+ /** hreflang alternates of the current pass, by page slug (languages.json). */
51
+ private currentAlternates;
52
52
  constructor(options: MdxReconciliationCoordinatorOptions);
53
+ /**
54
+ * Synthetic API-reference pages have no source folder, so they belong to
55
+ * the default variant. They carry that variant explicitly (like every real
56
+ * page does) only when a variant file is configured, so their serialized
57
+ * shape is unchanged for every other site.
58
+ */
59
+ private withDefaultVariant;
53
60
  resetForInitialPublication(): void;
61
+ private refreshAlternates;
62
+ /**
63
+ * Whether a page's hreflang set differs from the previous pass. A page
64
+ * embeds the set of its translations, so adding or removing one language
65
+ * of a page has to re-render its siblings in the other languages.
66
+ */
67
+ private alternatesChanged;
54
68
  successfulPages(): PageMeta[];
55
69
  occupiedSlugs(): Set<string>;
56
70
  blockOpenApiPages(realPages: PageMeta[]): PageMeta[];
@@ -1,5 +1,6 @@
1
1
  import chalk from "chalk";
2
2
  import { getFullSlug, safeMatter } from "../lib/utils.js";
3
+ import { buildLanguageAlternates, defaultLanguage, joinVariantSlug, } from "../lib/variants.js";
3
4
  import { MdxPassBuilder, } from "./mdx-pass-builder.js";
4
5
  import { mergePages, RouteCollisionError } from "./page-catalog.js";
5
6
  export class MdxReconciliationCoordinator {
@@ -11,6 +12,8 @@ export class MdxReconciliationCoordinator {
11
12
  successfulMdxContent = new Map();
12
13
  successfulMdxSourcesBySlug = new Map();
13
14
  collisionBlockedMdxSources = new Set();
15
+ /** hreflang alternates of the current pass, by page slug (languages.json). */
16
+ currentAlternates = new Map();
14
17
  constructor(options) {
15
18
  this.options = options;
16
19
  this.mdxPassBuilder = new MdxPassBuilder({
@@ -21,11 +24,41 @@ export class MdxReconciliationCoordinator {
21
24
  withApiReferenceSection: (sections) => options.withApiReferenceSection(sections),
22
25
  determineSectionForFile: (filePath, frontmatter, sections) => options.determineSectionForFile(filePath, frontmatter, sections),
23
26
  resolveHttpMethod: (reference) => options.lookupOpenApi(reference)?.method,
27
+ getVariants: () => options.getVariants(),
24
28
  });
25
29
  }
30
+ /**
31
+ * Synthetic API-reference pages have no source folder, so they belong to
32
+ * the default variant. They carry that variant explicitly (like every real
33
+ * page does) only when a variant file is configured, so their serialized
34
+ * shape is unchanged for every other site.
35
+ */
36
+ withDefaultVariant(pages) {
37
+ const { languages, versions } = this.options.getVariants();
38
+ if (!languages && !versions)
39
+ return pages;
40
+ const locale = defaultLanguage(languages)?.code;
41
+ return pages.map((page) => ({
42
+ ...page,
43
+ ...(locale !== undefined ? { locale } : {}),
44
+ ...(versions ? { version: "" } : {}),
45
+ }));
46
+ }
26
47
  resetForInitialPublication() {
27
48
  this.retainExistingMdxOutput = false;
28
49
  }
50
+ refreshAlternates(pages) {
51
+ this.currentAlternates = buildLanguageAlternates(pages, this.options.getVariants().languages);
52
+ }
53
+ /**
54
+ * Whether a page's hreflang set differs from the previous pass. A page
55
+ * embeds the set of its translations, so adding or removing one language
56
+ * of a page has to re-render its siblings in the other languages.
57
+ */
58
+ alternatesChanged(previous, slug) {
59
+ return (JSON.stringify(previous.get(slug) ?? null) !==
60
+ JSON.stringify(this.currentAlternates.get(slug) ?? null));
61
+ }
29
62
  successfulPages() {
30
63
  return [...this.successfulMdxPages.values()];
31
64
  }
@@ -59,9 +92,9 @@ export class MdxReconciliationCoordinator {
59
92
  mergeAllPagesMeta(real, declaredRealSlugs = new Set(real.map((page) => page.slug))) {
60
93
  return mergePages(real, this.options.isOpenApiRegistryEmpty()
61
94
  ? []
62
- : this.options
95
+ : this.withDefaultVariant(this.options
63
96
  .syntheticOpenApiPages()
64
- .filter((page) => !declaredRealSlugs.has(page.slug)));
97
+ .filter((page) => !declaredRealSlugs.has(page.slug))));
65
98
  }
66
99
  successfulPagesInSourceOrder(realPages) {
67
100
  const currentSources = new Set(realPages.map((page) => page.path.replace(/\\/g, "/")));
@@ -119,6 +152,7 @@ export class MdxReconciliationCoordinator {
119
152
  this.collisionBlockedMdxSources = state.collisionBlockedSources;
120
153
  this.options.setSections(state.sections);
121
154
  this.mdxSnapshotInitialized = state.snapshotInitialized;
155
+ this.refreshAlternates([...state.pages.values()]);
122
156
  }
123
157
  async rollbackPageCommits(commits) {
124
158
  const errors = [];
@@ -252,10 +286,11 @@ export class MdxReconciliationCoordinator {
252
286
  async writePageForFile(filePath, content) {
253
287
  const commits = [];
254
288
  const { data: frontmatter, content: mdxContent } = safeMatter(content, filePath);
255
- const { sectionSlug, pageSlug } = this.options.determineSectionForFile(filePath, frontmatter);
256
- const fullSlug = getFullSlug(pageSlug, sectionSlug);
289
+ const { sectionSlug, pageSlug, prefix = "", locale, version, } = this.options.determineSectionForFile(filePath, frontmatter);
290
+ const fullSlug = joinVariantSlug(prefix, getFullSlug(pageSlug, sectionSlug));
257
291
  const isIndex = filePath === "index.mdx" || filePath === "./index.mdx";
258
292
  const isSectionIndex = this.options.getSections() && pageSlug === "" && sectionSlug !== "";
293
+ const alternateLanguages = this.currentAlternates.get(fullSlug);
259
294
  try {
260
295
  if (isIndex) {
261
296
  // The homepage is emitted by updatePagesIndex() in the aggregate pass,
@@ -268,6 +303,8 @@ export class MdxReconciliationCoordinator {
268
303
  content: mdxContent,
269
304
  frontmatter,
270
305
  slug: fullSlug,
306
+ ...(locale !== undefined ? { locale } : {}),
307
+ ...(version !== undefined ? { version } : {}),
271
308
  };
272
309
  let apiOperation;
273
310
  if (frontmatter.openapi) {
@@ -276,10 +313,20 @@ export class MdxReconciliationCoordinator {
276
313
  console.error(chalk.red(`❌ openapi frontmatter "${frontmatter.openapi}" in ${filePath} not found in any spec`));
277
314
  }
278
315
  }
279
- commits.push(await this.options.generatePageFromMdx(mdxFile, apiOperation ? { apiOperation } : undefined));
316
+ const renderOptions = {
317
+ ...(apiOperation ? { apiOperation } : {}),
318
+ ...(alternateLanguages ? { alternateLanguages } : {}),
319
+ };
320
+ commits.push(await this.options.generatePageFromMdx(mdxFile, Object.keys(renderOptions).length > 0 ? renderOptions : undefined));
280
321
  }
281
322
  if (isSectionIndex) {
282
- commits.push(await this.options.updateSectionIndex(sectionSlug, frontmatter, mdxContent, filePath));
323
+ // The section index route carries the variant prefix, so
324
+ // `docs/de/api/index.mdx` lands on `/de/api` and never overwrites
325
+ // the default variant's `/api`.
326
+ commits.push(await this.options.updateSectionIndex(joinVariantSlug(prefix, sectionSlug), frontmatter, mdxContent, filePath, {
327
+ ...(locale !== undefined ? { locale } : {}),
328
+ ...(alternateLanguages ? { alternateLanguages } : {}),
329
+ }));
283
330
  }
284
331
  return commits;
285
332
  }
@@ -334,6 +381,8 @@ export class MdxReconciliationCoordinator {
334
381
  if (!currentPage)
335
382
  throw new Error(`Unable to resolve ${filePath}`);
336
383
  this.options.setSections(snapshot.sections);
384
+ const previousAlternates = this.currentAlternates;
385
+ this.refreshAlternates(realPages);
337
386
  try {
338
387
  pageCommits.push(...(await this.writePageForFile(filePath, changedSource.content)));
339
388
  this.recordSuccessfulMdxPage(currentPage, changedSource.content);
@@ -350,8 +399,9 @@ export class MdxReconciliationCoordinator {
350
399
  await this.refreshMdxDerivedOutput(realPages, successfulPages);
351
400
  throw error;
352
401
  }
353
- await this.retryMdxPages(snapshot, (source) => source !== normalizedSource &&
354
- this.collisionBlockedMdxSources.has(source), pageCommits);
402
+ await this.retryMdxPages(snapshot, (source, page) => source !== normalizedSource &&
403
+ (this.collisionBlockedMdxSources.has(source) ||
404
+ this.alternatesChanged(previousAlternates, page.slug)), pageCommits);
355
405
  let successfulPages = [];
356
406
  try {
357
407
  successfulPages = await this.commitMdxSnapshot(realPages);
@@ -392,8 +442,11 @@ export class MdxReconciliationCoordinator {
392
442
  this.collisionBlockedMdxSources.delete(normalizedSource);
393
443
  this.options.setSections(snapshot.sections);
394
444
  const realPages = snapshot.pages;
445
+ const previousAlternates = this.currentAlternates;
446
+ this.refreshAlternates(realPages);
395
447
  await this.retryMdxPages(snapshot, (source, page) => this.collisionBlockedMdxSources.has(source) ||
396
- this.successfulMdxPages.get(source)?.slug !== page.slug, pageCommits);
448
+ this.successfulMdxPages.get(source)?.slug !== page.slug ||
449
+ this.alternatesChanged(previousAlternates, page.slug), pageCommits);
397
450
  let successfulPages = [];
398
451
  try {
399
452
  successfulPages = await this.commitMdxSnapshot(realPages);
@@ -432,6 +485,7 @@ export class MdxReconciliationCoordinator {
432
485
  }
433
486
  this.options.setSections(snapshot.sections);
434
487
  const realPages = snapshot.pages;
488
+ this.refreshAlternates(realPages);
435
489
  const pagesBySource = new Map(realPages.map((page) => [page.path.replace(/\\/g, "/"), page]));
436
490
  for (const file of files) {
437
491
  console.log(chalk.cyan(`📝 Processing: ${file}`));
@@ -1,14 +1,12 @@
1
1
  import type { PageMeta } from "../lib/types.js";
2
+ import type { ResolvedPageRoute } from "./section-resolver.js";
2
3
  type ReadMdxSource = (filePath: string) => Promise<{
3
4
  content: string;
4
5
  stat: {
5
6
  mtime: Date;
6
7
  };
7
8
  }>;
8
- type ResolveSectionRoute = (filePath: string, frontmatter: Record<string, any>) => {
9
- sectionSlug: string;
10
- pageSlug: string;
11
- };
9
+ type ResolveSectionRoute = (filePath: string, frontmatter: Record<string, any>) => ResolvedPageRoute;
12
10
  type ResolveHttpMethod = (reference: string) => string | undefined;
13
11
  export declare function parseMdxPageMeta(filePath: string, readMdxSource: ReadMdxSource, resolveSectionRoute: ResolveSectionRoute, resolveHttpMethod: ResolveHttpMethod): Promise<PageMeta>;
14
12
  export declare class RouteCollisionError extends Error {
@@ -1,10 +1,11 @@
1
1
  import chalk from "chalk";
2
2
  import { getFullSlug, safeMatter } from "../lib/utils.js";
3
+ import { joinVariantSlug } from "../lib/variants.js";
3
4
  export async function parseMdxPageMeta(filePath, readMdxSource, resolveSectionRoute, resolveHttpMethod) {
4
5
  const { content, stat } = await readMdxSource(filePath);
5
6
  const { data: frontmatter } = safeMatter(content, filePath);
6
- const { sectionSlug, pageSlug } = resolveSectionRoute(filePath, frontmatter);
7
- const fullSlug = getFullSlug(pageSlug, sectionSlug);
7
+ const { sectionSlug, pageSlug, prefix, locale, version } = resolveSectionRoute(filePath, frontmatter);
8
+ const fullSlug = joinVariantSlug(prefix ?? "", getFullSlug(pageSlug, sectionSlug));
8
9
  let lastModified;
9
10
  const authoredLastModified = frontmatter.updated ?? frontmatter.date;
10
11
  if (authoredLastModified) {
@@ -35,6 +36,10 @@ export async function parseMdxPageMeta(filePath, readMdxSource, resolveSectionRo
35
36
  ? { categoryIcon: String(frontmatter.categoryIcon) }
36
37
  : {}),
37
38
  ...(httpMethod ? { httpMethod } : {}),
39
+ // Present only when languages.json / versions.json are configured, so
40
+ // the serialized nav objects of every other site stay unchanged.
41
+ ...(locale !== undefined ? { locale } : {}),
42
+ ...(version !== undefined ? { version } : {}),
38
43
  lastModified,
39
44
  };
40
45
  }
@@ -1,5 +1,15 @@
1
1
  import type { OperationDescriptor } from "../lib/openapi-types.js";
2
2
  import type { MDXFile } from "../lib/types.js";
3
+ export interface RenderPageOptions {
4
+ apiOperation?: OperationDescriptor;
5
+ /** hreflang -> path of this page in each language, incl. "x-default". */
6
+ alternateLanguages?: Record<string, string>;
7
+ }
8
+ export interface RenderVariantOptions {
9
+ /** Language of the page content (languages.json). */
10
+ locale?: string;
11
+ alternateLanguages?: Record<string, string>;
12
+ }
3
13
  export type RssRouteState = {
4
14
  action: "write";
5
15
  content: string;
@@ -24,8 +34,8 @@ export interface HomepageSource {
24
34
  openapi?: string;
25
35
  rss?: boolean;
26
36
  }
27
- export declare function renderMdxPage(mdxFile: MDXFile, options?: {
28
- apiOperation?: OperationDescriptor;
29
- }): RenderedPage;
30
- export declare function renderHomepage(indexMDX: HomepageSource | null, apiOperation?: OperationDescriptor): RenderedPage;
31
- export declare function renderSectionPage(sectionSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string): RenderedPage;
37
+ export declare function renderMdxPage(mdxFile: MDXFile, options?: RenderPageOptions): RenderedPage;
38
+ export declare function renderHomepage(indexMDX: HomepageSource | null, apiOperation?: OperationDescriptor, options?: RenderVariantOptions): RenderedPage;
39
+ /** `routeSlug` is the full route of the section index (`api`, or `de/api`
40
+ * inside a language folder). */
41
+ export declare function renderSectionPage(routeSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string, options?: RenderVariantOptions): RenderedPage;