doccupine 0.0.140 → 0.0.142

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 (145) hide show
  1. package/README.md +14 -7
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.js +191 -0
  4. package/dist/index.d.ts +3 -7
  5. package/dist/index.js +5 -1894
  6. package/dist/lib/config-manager.d.ts +1 -0
  7. package/dist/lib/config-manager.js +63 -3
  8. package/dist/lib/generated-artifacts.d.ts +26 -0
  9. package/dist/lib/generated-artifacts.js +147 -0
  10. package/dist/lib/layout.js +30 -30
  11. package/dist/lib/metadata.js +58 -30
  12. package/dist/lib/openapi-types.d.ts +2 -2
  13. package/dist/lib/openapi.d.ts +6 -3
  14. package/dist/lib/openapi.js +330 -50
  15. package/dist/lib/output-safety.d.ts +15 -0
  16. package/dist/lib/output-safety.js +428 -0
  17. package/dist/lib/structures.js +11 -0
  18. package/dist/lib/utils.d.ts +10 -5
  19. package/dist/lib/utils.js +108 -5
  20. package/dist/mdx-to-nextjs-generator.d.ts +166 -0
  21. package/dist/mdx-to-nextjs-generator.js +2229 -0
  22. package/dist/templates/app/api/gate/route.d.ts +1 -1
  23. package/dist/templates/app/api/gate/route.js +18 -6
  24. package/dist/templates/app/api/mcp/route.d.ts +1 -1
  25. package/dist/templates/app/api/mcp/route.js +181 -111
  26. package/dist/templates/app/api/playground/route.d.ts +1 -1
  27. package/dist/templates/app/api/playground/route.js +45 -13
  28. package/dist/templates/app/api/rag/route.d.ts +1 -1
  29. package/dist/templates/app/api/rag/route.js +72 -20
  30. package/dist/templates/app/api/search/route.d.ts +1 -1
  31. package/dist/templates/app/api/search/route.js +5 -0
  32. package/dist/templates/app/robots.d.ts +1 -1
  33. package/dist/templates/app/robots.js +1 -26
  34. package/dist/templates/app/theme.d.ts +1 -1
  35. package/dist/templates/app/theme.js +31 -19
  36. package/dist/templates/components/Chat.d.ts +1 -1
  37. package/dist/templates/components/Chat.js +342 -34
  38. package/dist/templates/components/SearchDocs.d.ts +1 -1
  39. package/dist/templates/components/SearchDocs.js +63 -11
  40. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  41. package/dist/templates/components/SearchModalContent.js +191 -49
  42. package/dist/templates/components/SideBar.d.ts +1 -1
  43. package/dist/templates/components/SideBar.js +8 -2
  44. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  45. package/dist/templates/components/layout/Accordion.js +26 -3
  46. package/dist/templates/components/layout/Badge.d.ts +1 -1
  47. package/dist/templates/components/layout/Badge.js +1 -1
  48. package/dist/templates/components/layout/Button.d.ts +1 -1
  49. package/dist/templates/components/layout/Button.js +4 -4
  50. package/dist/templates/components/layout/Callout.d.ts +1 -1
  51. package/dist/templates/components/layout/Callout.js +6 -6
  52. package/dist/templates/components/layout/Card.d.ts +1 -1
  53. package/dist/templates/components/layout/Card.js +9 -4
  54. package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
  55. package/dist/templates/components/layout/CherryThemeProvider.js +63 -12
  56. package/dist/templates/components/layout/Code.d.ts +1 -1
  57. package/dist/templates/components/layout/Code.js +5 -5
  58. package/dist/templates/components/layout/CopyButton.d.ts +1 -1
  59. package/dist/templates/components/layout/CopyButton.js +1 -1
  60. package/dist/templates/components/layout/DemoTheme.d.ts +1 -1
  61. package/dist/templates/components/layout/DemoTheme.js +8 -28
  62. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  63. package/dist/templates/components/layout/DocsComponents.js +57 -6
  64. package/dist/templates/components/layout/GlobalStyles.d.ts +1 -1
  65. package/dist/templates/components/layout/GlobalStyles.js +15 -9
  66. package/dist/templates/components/layout/Prompt.d.ts +1 -1
  67. package/dist/templates/components/layout/Prompt.js +4 -7
  68. package/dist/templates/components/layout/Steps.d.ts +1 -1
  69. package/dist/templates/components/layout/Steps.js +7 -1
  70. package/dist/templates/components/layout/Tabs.d.ts +1 -1
  71. package/dist/templates/components/layout/Tabs.js +108 -19
  72. package/dist/templates/env.example.d.ts +1 -1
  73. package/dist/templates/env.example.js +11 -0
  74. package/dist/templates/eslint.config.d.ts +1 -1
  75. package/dist/templates/eslint.config.js +20 -0
  76. package/dist/templates/gitignore.d.ts +1 -1
  77. package/dist/templates/gitignore.js +4 -3
  78. package/dist/templates/lib/access.d.ts +1 -0
  79. package/dist/templates/lib/access.js +41 -0
  80. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  81. package/dist/templates/mdx/ai-assistant.mdx.js +17 -1
  82. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  83. package/dist/templates/mdx/api-playground.mdx.js +5 -3
  84. package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
  85. package/dist/templates/mdx/authentication.mdx.js +5 -3
  86. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  87. package/dist/templates/mdx/commands.mdx.js +20 -6
  88. package/dist/templates/mdx/components.mdx.d.ts +1 -1
  89. package/dist/templates/mdx/components.mdx.js +3 -0
  90. package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
  91. package/dist/templates/mdx/deployment-and-hosting.mdx.js +2 -2
  92. package/dist/templates/mdx/globals.mdx.d.ts +1 -1
  93. package/dist/templates/mdx/globals.mdx.js +14 -11
  94. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  95. package/dist/templates/mdx/model-context-protocol.mdx.js +22 -35
  96. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  97. package/dist/templates/mdx/platform/ai-assistant.mdx.js +23 -0
  98. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  99. package/dist/templates/mdx/platform/api-playground.mdx.js +7 -0
  100. package/dist/templates/mdx/platform/authentication.mdx.d.ts +1 -0
  101. package/dist/templates/mdx/platform/authentication.mdx.js +63 -0
  102. package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -1
  103. package/dist/templates/mdx/platform/import-from-github.mdx.js +2 -2
  104. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  105. package/dist/templates/mdx/platform/index.mdx.js +1 -0
  106. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  107. package/dist/templates/mdx/platform/mcp.mdx.js +2 -1
  108. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  109. package/dist/templates/mdx/platform/navigation-settings.mdx.js +12 -1
  110. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  111. package/dist/templates/mdx/platform/publishing.mdx.js +43 -10
  112. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  113. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +48 -9
  114. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  115. package/dist/templates/mdx/sections.mdx.js +4 -0
  116. package/dist/templates/mdx/space.mdx.d.ts +1 -0
  117. package/dist/templates/mdx/space.mdx.js +125 -0
  118. package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
  119. package/dist/templates/mdx/tabs.mdx.js +4 -0
  120. package/dist/templates/next.config.js +20 -8
  121. package/dist/templates/package.js +3 -3
  122. package/dist/templates/prettierignore.d.ts +1 -1
  123. package/dist/templates/prettierignore.js +1 -0
  124. package/dist/templates/proxy.js +47 -19
  125. package/dist/templates/scripts/build-docs-index.d.ts +1 -1
  126. package/dist/templates/scripts/build-docs-index.js +1 -0
  127. package/dist/templates/services/mcp/docsContentStub.d.ts +1 -0
  128. package/dist/templates/services/mcp/docsContentStub.js +1 -0
  129. package/dist/templates/services/mcp/server.d.ts +1 -1
  130. package/dist/templates/services/mcp/server.js +140 -83
  131. package/dist/templates/services/mcp/tools.d.ts +1 -1
  132. package/dist/templates/services/mcp/tools.js +65 -137
  133. package/dist/templates/utils/playgroundAllowlist.d.ts +1 -1
  134. package/dist/templates/utils/playgroundAllowlist.js +13 -4
  135. package/dist/templates/utils/rateLimit.d.ts +1 -1
  136. package/dist/templates/utils/rateLimit.js +40 -3
  137. package/dist/templates/utils/requestBody.d.ts +1 -0
  138. package/dist/templates/utils/requestBody.js +56 -0
  139. package/dist/templates/utils/ssrfGuard.d.ts +1 -1
  140. package/dist/templates/utils/ssrfGuard.js +138 -33
  141. package/package.json +13 -5
  142. package/dist/lib/mdxToMarkdown.d.ts +0 -1
  143. package/dist/lib/mdxToMarkdown.js +0 -134
  144. package/dist/templates/mdx/image-and-embeds.mdx.d.ts +0 -1
  145. package/dist/templates/mdx/image-and-embeds.mdx.js +0 -118
package/dist/index.js CHANGED
@@ -1,1903 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import { program } from "commander";
3
- import chokidar from "chokidar";
4
2
  import fs from "fs-extra";
5
- import path from "path";
6
3
  import { fileURLToPath } from "url";
7
- import chalk from "chalk";
8
- import { appStructure, obsoleteFiles, startingDocsStructure, } from "./lib/structures.js";
9
- import { rootLayoutTemplate, siteLayoutTemplate } from "./lib/layout.js";
10
- import { ConfigManager, normalizeOpenApiConfig } from "./lib/config-manager.js";
11
- import { OpenApiRegistry, DEFAULT_API_BASE_SLUG, buildEndpointDoc, } from "./lib/openapi.js";
12
- import { findAvailablePort, generateSlug, getFullSlug, escapeTemplateContent, toJsStringLiteral, resolvePackageManager, safeMatter, } from "./lib/utils.js";
13
- import { generateMetadataBlock, generateRuntimeOnlyMetadataBlock, generateJsonLdScript, } from "./lib/metadata.js";
14
- import { parseUpdateBlocks } from "./lib/rss.js";
15
- import { nextConfigTemplate } from "./templates/next.config.js";
16
- import { pnpmWorkspaceTemplate } from "./templates/pnpmWorkspace.js";
17
- import { proxyTemplate } from "./templates/proxy.js";
18
- import { robotsTemplate } from "./templates/app/robots.js";
19
- import { rssRouteTemplate } from "./templates/app/rssRoute.js";
20
- import { sitemapTemplate } from "./templates/app/sitemap.js";
21
- import { llmsIndexTemplate } from "./templates/llms/llmsIndex.js";
22
- import { llmsFullTemplate, } from "./templates/llms/llmsFull.js";
23
- import { llmsPageTemplate } from "./templates/llms/llmsPage.js";
24
- import { siteDocsSlug, skillMdTemplate } from "./templates/llms/skillMd.js";
25
4
  export { generateSlug, getFullSlug, escapeTemplateContent, toJsStringLiteral, } from "./lib/utils.js";
5
+ export { MDXToNextJSGenerator } from "./mdx-to-nextjs-generator.js";
26
6
  const __filename = fileURLToPath(import.meta.url);
27
- const __dirname = path.dirname(__filename);
28
- const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf8"));
29
- const version = packageJson.version;
30
- class MDXToNextJSGenerator {
31
- watchDir;
32
- outputDir;
33
- rootDir;
34
- watcher = null;
35
- configWatcher = null;
36
- fontWatcher = null;
37
- publicWatcher = null;
38
- rootDirWatcher = null;
39
- analyticsWatcher = null;
40
- openApiWatcher = null;
41
- doccupineConfigWatcher = null;
42
- doccupineConfigFile = "doccupine.json";
43
- configFiles = [
44
- "theme.json",
45
- "navigation.json",
46
- "config.json",
47
- "links.json",
48
- "sections.json",
49
- ];
50
- fontConfigFile = "fonts.json";
51
- analyticsConfigFile = "analytics.json";
52
- analyticsConfig = null;
53
- sectionsConfig = null;
54
- /** Guards against recursive reprocessing when maybeUpdateSections() triggers processAllMDXFiles() */
55
- isReprocessing = false;
56
- /** Tracks per-page .md files written under public/ so we can clean up stale ones on rename/delete */
57
- generatedLlmsPagePaths = new Set();
58
- /** OpenAPI specs (build config) that drive the generated API reference. */
59
- openApiSpecs;
60
- apiBaseSlug = DEFAULT_API_BASE_SLUG;
61
- apiRegistry = new OpenApiRegistry();
62
- /** Route slugs of the endpoint pages written last pass, for stale cleanup. */
63
- generatedApiPageSlugs = new Set();
64
- /** Section slugs whose index redirect we wrote this session, for cleanup. */
65
- generatedSectionIndexSlugs = new Set();
66
- constructor(watchDir, outputDir, openApiSpecs = []) {
67
- this.watchDir = path.resolve(watchDir);
68
- this.outputDir = path.resolve(outputDir);
69
- this.rootDir = process.cwd();
70
- this.openApiSpecs = openApiSpecs;
71
- }
72
- async init() {
73
- console.log(chalk.blue("šŸš€ Initializing MDX to Next.js generator..."));
74
- await fs.ensureDir(this.watchDir);
75
- await fs.ensureDir(this.outputDir);
76
- this.sectionsConfig = await this.resolveSections();
77
- this.analyticsConfig = await this.loadAnalyticsConfig();
78
- if (this.analyticsConfig) {
79
- console.log(chalk.blue(`šŸ“Š Analytics enabled: ${this.analyticsConfig.provider}`));
80
- }
81
- // Parse OpenAPI spec(s) before generating structure so the synthetic
82
- // endpoint pages flow into the very first layout/sitemap/llms pass.
83
- await this.loadOpenApiRegistry();
84
- await this.createNextJSStructure();
85
- await this.createStartingDocs();
86
- await this.copyCustomConfigFiles();
87
- await this.copyFontConfig();
88
- await this.copyAnalyticsConfig();
89
- await this.copyPublicFiles();
90
- // createStartingDocs() may have written the sample docs - which carry
91
- // section frontmatter - after the initial resolveSections() ran against an
92
- // empty watch dir. Re-resolve now that every MDX file is on disk so the
93
- // build applies the correct sections in a single O(n) pass, instead of
94
- // rediscovering them per file (the old O(n²) behavior).
95
- this.sectionsConfig = await this.resolveSections();
96
- if (this.sectionsConfig) {
97
- console.log(chalk.blue(`šŸ“‘ Found ${this.sectionsConfig.length} section(s): ${this.sectionsConfig.map((s) => s.label).join(", ")}`));
98
- }
99
- // Write the endpoint pages + request allowlist before the MDX pass so its
100
- // aggregate refresh (nav/sitemap/llms) already sees them on disk and in the
101
- // registry.
102
- await this.writeApiPages();
103
- await this.processAllMDXFiles();
104
- console.log(chalk.green("āœ… Initial setup complete!"));
105
- console.log(chalk.cyan("šŸ’” To start the Next.js dev server:"));
106
- console.log(chalk.white(` cd ${path.relative(process.cwd(), this.outputDir)}`));
107
- console.log(chalk.white(" npm install && npm run dev"));
108
- }
109
- async createNextJSStructure() {
110
- // Clear the generated app/ directory first so a fresh run never inherits
111
- // stale routes from a previous version (e.g. pages left at their old paths
112
- // after a route-group move would collide with the newly generated ones).
113
- // Everything under app/ is regenerated below and by processAllMDXFiles /
114
- // generateSectionIndexPages, so nothing here is user-authored. Config JSONs
115
- // and other generated dirs live outside app/ and are untouched.
116
- await fs.remove(path.join(this.outputDir, "app"));
117
- // Drop files that earlier CLI versions generated but no longer exist in
118
- // the template set, so upgraded projects don't keep stale copies.
119
- await Promise.all(obsoleteFiles.map((file) => fs.remove(path.join(this.outputDir, file))));
120
- const siteUrl = await this.loadSiteUrl();
121
- const structure = {
122
- ...appStructure,
123
- "next.config.ts": nextConfigTemplate(this.analyticsConfig),
124
- "pnpm-workspace.yaml": pnpmWorkspaceTemplate,
125
- "proxy.ts": proxyTemplate(this.analyticsConfig),
126
- "analytics.json": `{}\n`,
127
- "config.json": `{}\n`,
128
- "links.json": `[]\n`,
129
- "navigation.json": `[]\n`,
130
- "sections.json": `[]\n`,
131
- "theme.json": `{}\n`,
132
- "app/robots.ts": robotsTemplate(siteUrl !== null),
133
- "app/layout.tsx": this.generateRootLayout(),
134
- "app/(site)/layout.tsx": this.generateSiteLayout(),
135
- };
136
- for (const [filePath, content] of Object.entries(structure)) {
137
- const fullPath = path.join(this.outputDir, filePath);
138
- await fs.ensureDir(path.dirname(fullPath));
139
- await fs.writeFile(fullPath, String(await content), "utf8");
140
- }
141
- await this.updateSitemap();
142
- await this.updateLlmsFiles();
143
- }
144
- async createStartingDocs() {
145
- const structure = startingDocsStructure;
146
- const indexMdxExists = await fs.pathExists(path.join(this.watchDir, "index.mdx"));
147
- if (!indexMdxExists) {
148
- for (const [filePath, content] of Object.entries(structure)) {
149
- const fullPath = path.join(this.watchDir, filePath);
150
- await fs.ensureDir(path.dirname(fullPath));
151
- await fs.writeFile(fullPath, String(content), "utf8");
152
- }
153
- }
154
- }
155
- async copyCustomConfigFiles() {
156
- console.log(chalk.blue(`šŸ” Checking for config files in: ${this.watchDir}`));
157
- for (const configFile of this.configFiles) {
158
- const sourcePath = path.join(this.rootDir, configFile);
159
- const destPath = path.join(this.outputDir, configFile);
160
- console.log(chalk.gray(` Checking ${configFile}...`));
161
- if (await fs.pathExists(sourcePath)) {
162
- await fs.copy(sourcePath, destPath);
163
- console.log(chalk.green(` āœ“ Copied ${configFile} to Next.js app`));
164
- }
165
- else {
166
- console.log(chalk.gray(` āœ— ${configFile} not found, skipping`));
167
- }
168
- }
169
- }
170
- async copyFontConfig() {
171
- console.log(chalk.blue(`šŸ” Checking for font configuration...`));
172
- const sourcePath = path.join(this.rootDir, this.fontConfigFile);
173
- const destPath = path.join(this.outputDir, this.fontConfigFile);
174
- if (await fs.pathExists(sourcePath)) {
175
- await fs.copy(sourcePath, destPath);
176
- console.log(chalk.green(` āœ“ Copied ${this.fontConfigFile} to Next.js app`));
177
- }
178
- else {
179
- console.log(chalk.gray(` āœ— ${this.fontConfigFile} not found, skipping`));
180
- }
181
- }
182
- async loadFontConfig() {
183
- const fontPath = path.join(this.rootDir, this.fontConfigFile);
184
- try {
185
- if (await fs.pathExists(fontPath)) {
186
- const fontContent = await fs.readFile(fontPath, "utf8");
187
- return JSON.parse(fontContent);
188
- }
189
- }
190
- catch (error) {
191
- console.warn(chalk.yellow(`āš ļø Error reading ${this.fontConfigFile}`), error);
192
- }
193
- return null;
194
- }
195
- async loadAnalyticsConfig() {
196
- const analyticsPath = path.join(this.rootDir, this.analyticsConfigFile);
197
- try {
198
- if (await fs.pathExists(analyticsPath)) {
199
- const content = await fs.readFile(analyticsPath, "utf8");
200
- const parsed = JSON.parse(content);
201
- if (parsed?.provider === "posthog" && parsed.posthog?.key) {
202
- return parsed;
203
- }
204
- }
205
- }
206
- catch (error) {
207
- console.warn(chalk.yellow(`āš ļø Error reading ${this.analyticsConfigFile}`), error);
208
- }
209
- return null;
210
- }
211
- async copyAnalyticsConfig() {
212
- console.log(chalk.blue(`šŸ” Checking for analytics configuration...`));
213
- const sourcePath = path.join(this.rootDir, this.analyticsConfigFile);
214
- const destPath = path.join(this.outputDir, this.analyticsConfigFile);
215
- if (await fs.pathExists(sourcePath)) {
216
- await fs.copy(sourcePath, destPath);
217
- console.log(chalk.green(` āœ“ Copied ${this.analyticsConfigFile} to Next.js app`));
218
- }
219
- else {
220
- console.log(chalk.gray(` āœ— ${this.analyticsConfigFile} not found, skipping`));
221
- }
222
- }
223
- async loadSectionsConfig() {
224
- const sectionsPath = path.join(this.rootDir, "sections.json");
225
- try {
226
- if (await fs.pathExists(sectionsPath)) {
227
- const content = await fs.readFile(sectionsPath, "utf8");
228
- const parsed = JSON.parse(content);
229
- if (Array.isArray(parsed) && parsed.length > 0) {
230
- return parsed;
231
- }
232
- }
233
- }
234
- catch (error) {
235
- console.warn(chalk.yellow("āš ļø Error reading sections.json"), error);
236
- }
237
- return null;
238
- }
239
- async discoverSectionsFromFrontmatter() {
240
- const files = await this.getAllMDXFiles();
241
- const sectionMap = new Map();
242
- let hasUnsectionedPages = false;
243
- let defaultSectionLabel = "Docs";
244
- for (const file of files) {
245
- const fullPath = path.join(this.watchDir, file);
246
- const content = await fs.readFile(fullPath, "utf8");
247
- const { data: frontmatter } = safeMatter(content, file);
248
- if (frontmatter.section) {
249
- const label = frontmatter.section;
250
- const order = frontmatter.sectionOrder || 0;
251
- const existing = sectionMap.get(label);
252
- if (!existing || order < existing.order) {
253
- sectionMap.set(label, { label, order });
254
- }
255
- }
256
- else {
257
- hasUnsectionedPages = true;
258
- }
259
- if ((file === "index.mdx" || file === "./index.mdx") &&
260
- frontmatter.sectionLabel) {
261
- defaultSectionLabel = frontmatter.sectionLabel;
262
- }
263
- }
264
- if (sectionMap.size === 0)
265
- return null;
266
- const sorted = [...sectionMap.values()].sort((a, b) => a.order - b.order);
267
- const sections = [];
268
- // Implicit root entry for pages without a section field
269
- if (hasUnsectionedPages) {
270
- sections.push({ label: defaultSectionLabel, slug: "" });
271
- }
272
- for (const s of sorted) {
273
- sections.push({
274
- label: s.label,
275
- slug: s.label.toLowerCase().replace(/\s+/g, "-"),
276
- });
277
- }
278
- return sections;
279
- }
280
- async resolveSections() {
281
- const fromFile = await this.loadSectionsConfig();
282
- const base = fromFile ?? (await this.discoverSectionsFromFrontmatter());
283
- return this.withApiReferenceSection(base);
284
- }
285
- /**
286
- * Promotes the generated OpenAPI endpoints into a dedicated "API Reference"
287
- * section so they get their own top-level nav, separate from hand-written
288
- * docs. When the site had no sections, a root "Documentation" section is added
289
- * for the existing pages so both appear in the section switcher.
290
- */
291
- withApiReferenceSection(sections) {
292
- if (this.apiRegistry.isEmpty)
293
- return sections;
294
- const apiSection = {
295
- label: "API Reference",
296
- slug: this.apiBaseSlug,
297
- };
298
- if (!sections || sections.length === 0) {
299
- return [{ label: "Documentation", slug: "" }, apiSection];
300
- }
301
- if (sections.some((s) => s.slug === this.apiBaseSlug))
302
- return sections;
303
- return [...sections, apiSection];
304
- }
305
- async reloadSections() {
306
- console.log(chalk.cyan("šŸ“‘ Sections configuration changed"));
307
- this.sectionsConfig = await this.resolveSections();
308
- await this.processAllMDXFiles();
309
- }
310
- async maybeUpdateSections() {
311
- if (this.isReprocessing)
312
- return;
313
- // Skip if sections.json exists (explicit config takes priority)
314
- const fromFile = await this.loadSectionsConfig();
315
- if (fromFile)
316
- return;
317
- const newSections = this.withApiReferenceSection(await this.discoverSectionsFromFrontmatter());
318
- const changed = JSON.stringify(newSections) !== JSON.stringify(this.sectionsConfig);
319
- if (changed) {
320
- console.log(chalk.cyan(newSections
321
- ? `šŸ“‘ Sections updated from frontmatter: ${newSections.map((s) => s.label).join(", ")}`
322
- : "šŸ“‘ Sections cleared (no section frontmatter found)"));
323
- this.sectionsConfig = newSections;
324
- this.isReprocessing = true;
325
- try {
326
- // processAllMDXFiles() already refreshes section index pages via its
327
- // aggregate pass, so no separate generateSectionIndexPages() here.
328
- await this.processAllMDXFiles();
329
- }
330
- finally {
331
- this.isReprocessing = false;
332
- }
333
- }
334
- }
335
- determineSectionForFile(filePath, frontmatter) {
336
- if (!this.sectionsConfig || this.sectionsConfig.length === 0) {
337
- return { sectionSlug: "", pageSlug: generateSlug(filePath) };
338
- }
339
- const normalizedPath = filePath.replace(/\\/g, "/");
340
- const firstDir = normalizedPath.includes("/")
341
- ? normalizedPath.split("/")[0]
342
- : "";
343
- // Explicit directory matching (entries with a directory field)
344
- for (const section of this.sectionsConfig) {
345
- if (!section.directory)
346
- continue;
347
- const dirPrefix = section.directory + "/";
348
- if (normalizedPath.startsWith(dirPrefix)) {
349
- return {
350
- sectionSlug: section.slug,
351
- pageSlug: generateSlug(normalizedPath.slice(dirPrefix.length)),
352
- };
353
- }
354
- }
355
- // Directory matches section slug (auto-detect)
356
- if (firstDir) {
357
- const match = this.sectionsConfig.find((s) => s.slug === firstDir);
358
- if (match) {
359
- const pathForSlug = normalizedPath.slice(firstDir.length + 1);
360
- return {
361
- sectionSlug: match.slug,
362
- pageSlug: generateSlug(pathForSlug),
363
- };
364
- }
365
- }
366
- // Frontmatter section field
367
- if (frontmatter.section) {
368
- const label = frontmatter.section;
369
- const match = this.sectionsConfig.find((s) => s.label === label);
370
- if (match) {
371
- // Strip the directory if it matches the section slug
372
- let pathForSlug = filePath;
373
- if (firstDir && firstDir === match.slug) {
374
- pathForSlug = normalizedPath.slice(firstDir.length + 1);
375
- }
376
- return {
377
- sectionSlug: match.slug,
378
- pageSlug: generateSlug(pathForSlug),
379
- };
380
- }
381
- }
382
- // No section match - page stays at root
383
- return {
384
- sectionSlug: "",
385
- pageSlug: generateSlug(filePath),
386
- };
387
- }
388
- async handleConfigFileChange(filePath) {
389
- const fileName = path.basename(filePath);
390
- if (this.configFiles.includes(fileName)) {
391
- const sourcePath = path.join(this.rootDir, fileName);
392
- const destPath = path.join(this.outputDir, fileName);
393
- try {
394
- await fs.copy(sourcePath, destPath);
395
- console.log(chalk.green(`šŸ“‹ Updated ${fileName} in Next.js app`));
396
- if (fileName === "sections.json") {
397
- await this.reloadSections();
398
- }
399
- if (fileName === "config.json") {
400
- await this.updateSitemap();
401
- await this.updateRobots();
402
- await this.updateLlmsFiles();
403
- }
404
- }
405
- catch (error) {
406
- console.error(chalk.red(`āŒ Error copying ${fileName}:`), error);
407
- }
408
- }
409
- }
410
- async handleConfigFileDelete(filePath) {
411
- const fileName = path.basename(filePath);
412
- if (this.configFiles.includes(fileName)) {
413
- const destPath = path.join(this.outputDir, fileName);
414
- try {
415
- if (await fs.pathExists(destPath)) {
416
- await fs.remove(destPath);
417
- console.log(chalk.yellow(`šŸ—‘ļø Removed ${fileName} from Next.js app`));
418
- }
419
- if (fileName === "sections.json") {
420
- await this.reloadSections();
421
- }
422
- if (fileName === "config.json") {
423
- await this.updateSitemap();
424
- await this.updateRobots();
425
- await this.updateLlmsFiles();
426
- }
427
- }
428
- catch (error) {
429
- console.error(chalk.red(`āŒ Error removing ${fileName}:`), error);
430
- }
431
- }
432
- }
433
- async handleFontConfigChange() {
434
- console.log(chalk.cyan(`šŸ”¤ Font configuration changed`));
435
- const sourcePath = path.join(this.rootDir, this.fontConfigFile);
436
- const destPath = path.join(this.outputDir, this.fontConfigFile);
437
- try {
438
- await fs.copy(sourcePath, destPath);
439
- console.log(chalk.green(`šŸ“‹ Updated ${this.fontConfigFile} in Next.js app`));
440
- await this.updateRootLayout();
441
- console.log(chalk.green(`āœ… Layout updated with new font configuration`));
442
- }
443
- catch (error) {
444
- console.error(chalk.red(`āŒ Error updating font configuration:`), error);
445
- }
446
- }
447
- async handleFontConfigDelete() {
448
- console.log(chalk.red(`šŸ—‘ļø Font configuration deleted`));
449
- const destPath = path.join(this.outputDir, this.fontConfigFile);
450
- try {
451
- if (await fs.pathExists(destPath)) {
452
- await fs.remove(destPath);
453
- console.log(chalk.yellow(`šŸ—‘ļø Removed ${this.fontConfigFile} from Next.js app`));
454
- await this.updateRootLayout();
455
- console.log(chalk.green(`āœ… Layout updated without font configuration`));
456
- }
457
- }
458
- catch (error) {
459
- console.error(chalk.red(`āŒ Error removing font configuration:`), error);
460
- }
461
- }
462
- async handleAnalyticsConfigChange() {
463
- console.log(chalk.cyan(`šŸ“Š Analytics configuration changed`));
464
- const sourcePath = path.join(this.rootDir, this.analyticsConfigFile);
465
- const destPath = path.join(this.outputDir, this.analyticsConfigFile);
466
- try {
467
- await fs.copy(sourcePath, destPath);
468
- console.log(chalk.green(`šŸ“‹ Updated ${this.analyticsConfigFile} in Next.js app`));
469
- this.analyticsConfig = await this.loadAnalyticsConfig();
470
- // Regenerate dynamic templates that depend on analytics config
471
- await fs.writeFile(path.join(this.outputDir, "next.config.ts"), nextConfigTemplate(this.analyticsConfig), "utf8");
472
- await fs.writeFile(path.join(this.outputDir, "proxy.ts"), proxyTemplate(this.analyticsConfig), "utf8");
473
- await this.updateRootLayout();
474
- console.log(chalk.green(`āœ… Analytics configuration updated`));
475
- if (this.analyticsConfig) {
476
- console.log(chalk.yellow(`āš ļø Next.js dev server restart may be required for analytics proxy changes`));
477
- }
478
- }
479
- catch (error) {
480
- console.error(chalk.red(`āŒ Error updating analytics configuration:`), error);
481
- }
482
- }
483
- async handleAnalyticsConfigDelete() {
484
- console.log(chalk.red(`šŸ—‘ļø Analytics configuration deleted`));
485
- const destPath = path.join(this.outputDir, this.analyticsConfigFile);
486
- try {
487
- // Write empty analytics.json so runtime imports don't break
488
- await fs.writeFile(destPath, `{}\n`, "utf8");
489
- this.analyticsConfig = null;
490
- // Regenerate dynamic templates without analytics
491
- await fs.writeFile(path.join(this.outputDir, "next.config.ts"), nextConfigTemplate(null), "utf8");
492
- await fs.writeFile(path.join(this.outputDir, "proxy.ts"), proxyTemplate(null), "utf8");
493
- await this.updateRootLayout();
494
- console.log(chalk.green(`āœ… Analytics removed from Next.js app`));
495
- }
496
- catch (error) {
497
- console.error(chalk.red(`āŒ Error removing analytics configuration:`), error);
498
- }
499
- }
500
- async copyPublicFiles() {
501
- const publicDir = path.join(this.rootDir, "public");
502
- const destDir = path.join(this.outputDir, "public");
503
- console.log(chalk.blue(`šŸ” Checking for public directory...`));
504
- if (await fs.pathExists(publicDir)) {
505
- await fs.copy(publicDir, destDir);
506
- console.log(chalk.green(` āœ“ Copied public directory to Next.js app`));
507
- }
508
- else {
509
- console.log(chalk.gray(` āœ— public directory not found, skipping`));
510
- }
511
- }
512
- async handlePublicFileChange(filePath) {
513
- const publicDir = path.join(this.rootDir, "public");
514
- const relativePath = path.relative(publicDir, filePath);
515
- const destPath = path.join(this.outputDir, "public", relativePath);
516
- try {
517
- await fs.ensureDir(path.dirname(destPath));
518
- await fs.copy(filePath, destPath);
519
- console.log(chalk.green(`šŸ“‹ Updated public/${relativePath} in Next.js app`));
520
- }
521
- catch (error) {
522
- console.error(chalk.red(`āŒ Error copying public/${relativePath}:`), error);
523
- }
524
- }
525
- async handlePublicFileDelete(filePath) {
526
- const publicDir = path.join(this.rootDir, "public");
527
- const relativePath = path.relative(publicDir, filePath);
528
- const destPath = path.join(this.outputDir, "public", relativePath);
529
- try {
530
- if (await fs.pathExists(destPath)) {
531
- await fs.remove(destPath);
532
- console.log(chalk.yellow(`šŸ—‘ļø Removed public/${relativePath} from Next.js app`));
533
- }
534
- }
535
- catch (error) {
536
- console.error(chalk.red(`āŒ Error removing public/${relativePath}:`), error);
537
- }
538
- }
539
- async startWatching() {
540
- console.log(chalk.yellow(`šŸ‘€ Watching for changes in: ${this.watchDir}`));
541
- this.watcher = chokidar.watch(this.watchDir, {
542
- persistent: true,
543
- ignoreInitial: true,
544
- ignored: (filePath, stats) => {
545
- const isFile = stats?.isFile() ?? path.extname(filePath) !== "";
546
- const fileName = path.basename(filePath);
547
- if (this.configFiles.includes(fileName)) {
548
- return true;
549
- }
550
- if (isFile && !filePath.endsWith(".mdx")) {
551
- return true;
552
- }
553
- return false;
554
- },
555
- });
556
- this.watcher
557
- .on("add", (filePath) => {
558
- const relativePath = path.relative(this.watchDir, filePath);
559
- this.handleFileChange("added", relativePath);
560
- })
561
- .on("change", (filePath) => {
562
- const relativePath = path.relative(this.watchDir, filePath);
563
- this.handleFileChange("changed", relativePath);
564
- })
565
- .on("unlink", (filePath) => {
566
- const relativePath = path.relative(this.watchDir, filePath);
567
- this.handleFileDelete(relativePath);
568
- })
569
- .on("ready", () => {
570
- console.log(chalk.green("šŸ“ Initial scan complete. Ready for changes..."));
571
- })
572
- .on("error", (error) => {
573
- console.error(chalk.red("āŒ Watcher error:"), error);
574
- });
575
- const configPaths = this.configFiles.map((f) => path.join(this.rootDir, f));
576
- this.configWatcher = chokidar.watch(configPaths, {
577
- persistent: true,
578
- ignoreInitial: true,
579
- });
580
- this.configWatcher
581
- .on("add", (filePath) => {
582
- console.log(chalk.cyan(`šŸ“ Config file added: ${path.basename(filePath)}`));
583
- this.handleConfigFileChange(filePath);
584
- })
585
- .on("change", (filePath) => {
586
- console.log(chalk.cyan(`šŸ“ Config file changed: ${path.basename(filePath)}`));
587
- this.handleConfigFileChange(filePath);
588
- })
589
- .on("unlink", (filePath) => {
590
- console.log(chalk.red(`šŸ—‘ļø Config file deleted: ${path.basename(filePath)}`));
591
- this.handleConfigFileDelete(filePath);
592
- })
593
- .on("error", (error) => {
594
- console.error(chalk.red("āŒ Config watcher error:"), error);
595
- });
596
- const fontPath = path.join(this.rootDir, this.fontConfigFile);
597
- this.fontWatcher = chokidar.watch(fontPath, {
598
- persistent: true,
599
- ignoreInitial: true,
600
- });
601
- this.fontWatcher
602
- .on("add", () => {
603
- console.log(chalk.cyan(`šŸ”¤ Font configuration added`));
604
- this.handleFontConfigChange();
605
- })
606
- .on("change", () => {
607
- this.handleFontConfigChange();
608
- })
609
- .on("unlink", () => {
610
- this.handleFontConfigDelete();
611
- })
612
- .on("error", (error) => {
613
- console.error(chalk.red("āŒ Font watcher error:"), error);
614
- });
615
- const analyticsPath = path.join(this.rootDir, this.analyticsConfigFile);
616
- this.analyticsWatcher = chokidar.watch(analyticsPath, {
617
- persistent: true,
618
- ignoreInitial: true,
619
- });
620
- this.analyticsWatcher
621
- .on("add", () => {
622
- console.log(chalk.cyan(`šŸ“Š Analytics configuration added`));
623
- this.handleAnalyticsConfigChange();
624
- })
625
- .on("change", () => {
626
- this.handleAnalyticsConfigChange();
627
- })
628
- .on("unlink", () => {
629
- this.handleAnalyticsConfigDelete();
630
- })
631
- .on("error", (error) => {
632
- console.error(chalk.red("āŒ Analytics watcher error:"), error);
633
- });
634
- await this.syncOpenApiSpecWatcher();
635
- const doccupineConfigPath = path.join(this.rootDir, this.doccupineConfigFile);
636
- this.doccupineConfigWatcher = chokidar.watch(doccupineConfigPath, {
637
- persistent: true,
638
- ignoreInitial: true,
639
- });
640
- this.doccupineConfigWatcher
641
- .on("add", () => this.handleDoccupineConfigChange())
642
- .on("change", () => this.handleDoccupineConfigChange())
643
- .on("error", (error) => {
644
- console.error(chalk.red("āŒ doccupine.json watcher error:"), error);
645
- });
646
- const publicDir = path.join(this.rootDir, "public");
647
- if (await fs.pathExists(publicDir)) {
648
- this.setupPublicWatcher();
649
- }
650
- // Watch rootDir for public directory creation
651
- this.rootDirWatcher = chokidar.watch(this.rootDir, {
652
- persistent: true,
653
- ignoreInitial: true,
654
- depth: 0,
655
- });
656
- this.rootDirWatcher
657
- .on("addDir", async (dirPath) => {
658
- if (path.basename(dirPath) === "public" &&
659
- path.dirname(dirPath) === this.rootDir &&
660
- !this.publicWatcher) {
661
- console.log(chalk.cyan("šŸ“ Public directory created"));
662
- await this.copyPublicFiles();
663
- this.setupPublicWatcher();
664
- }
665
- })
666
- .on("error", (error) => {
667
- console.error(chalk.red("āŒ Root dir watcher error:"), error);
668
- });
669
- }
670
- setupPublicWatcher() {
671
- if (this.publicWatcher) {
672
- return;
673
- }
674
- const publicDir = path.join(this.rootDir, "public");
675
- this.publicWatcher = chokidar.watch(publicDir, {
676
- persistent: true,
677
- ignoreInitial: true,
678
- });
679
- this.publicWatcher
680
- .on("add", (filePath) => {
681
- console.log(chalk.cyan(`šŸ“ Public file added: ${path.relative(publicDir, filePath)}`));
682
- this.handlePublicFileChange(filePath);
683
- })
684
- .on("change", (filePath) => {
685
- console.log(chalk.cyan(`šŸ“ Public file changed: ${path.relative(publicDir, filePath)}`));
686
- this.handlePublicFileChange(filePath);
687
- })
688
- .on("unlink", (filePath) => {
689
- console.log(chalk.red(`šŸ—‘ļø Public file deleted: ${path.relative(publicDir, filePath)}`));
690
- this.handlePublicFileDelete(filePath);
691
- })
692
- .on("error", (error) => {
693
- console.error(chalk.red("āŒ Public watcher error:"), error);
694
- });
695
- }
696
- async parseMDXFile(file) {
697
- const fullPath = path.join(this.watchDir, file);
698
- const content = await fs.readFile(fullPath, "utf8");
699
- const { data: frontmatter } = safeMatter(content, file);
700
- const { sectionSlug, pageSlug } = this.determineSectionForFile(file, frontmatter);
701
- const fullSlug = getFullSlug(pageSlug, sectionSlug);
702
- let lastModified;
703
- if (frontmatter.date) {
704
- const parsed = new Date(frontmatter.date);
705
- if (!Number.isNaN(parsed.getTime())) {
706
- lastModified = parsed.toISOString();
707
- }
708
- }
709
- if (!lastModified) {
710
- try {
711
- const stats = await fs.stat(fullPath);
712
- lastModified = stats.mtime.toISOString();
713
- }
714
- catch {
715
- // ignore
716
- }
717
- }
718
- // A hand-written page that embeds an endpoint via `openapi:` frontmatter
719
- // gets the same method badge in the sidebar as a generated endpoint page.
720
- let httpMethod;
721
- if (frontmatter.openapi) {
722
- const op = this.apiRegistry.lookup(String(frontmatter.openapi));
723
- if (op)
724
- httpMethod = op.method.toUpperCase();
725
- }
726
- return {
727
- slug: fullSlug,
728
- title: frontmatter.title || "Untitled",
729
- description: frontmatter.description || "",
730
- date: frontmatter.date || null,
731
- category: frontmatter.category || "",
732
- path: file,
733
- categoryOrder: frontmatter.categoryOrder || 0,
734
- order: frontmatter.order || 0,
735
- section: sectionSlug,
736
- // Sidebar icons (Lucide names). Kept separate from `icon`, which is
737
- // reserved for the favicon/OG metadata. Only emitted when set so the
738
- // generated page literal stays lean.
739
- ...(frontmatter.navIcon ? { navIcon: String(frontmatter.navIcon) } : {}),
740
- ...(frontmatter.categoryIcon
741
- ? { categoryIcon: String(frontmatter.categoryIcon) }
742
- : {}),
743
- ...(httpMethod ? { httpMethod } : {}),
744
- lastModified,
745
- };
746
- }
747
- async buildAllPagesMeta() {
748
- const files = await this.getAllMDXFiles();
749
- const real = await Promise.all(files.map((file) => this.parseMDXFile(file)));
750
- if (this.apiRegistry.isEmpty)
751
- return real;
752
- // Inject synthetic OpenAPI endpoint pages here - the single funnel every
753
- // aggregate (nav, sitemap, llms) flows through - so they cannot be dropped
754
- // by the .mdx-only disk scan. Hand-written pages win on any slug collision.
755
- const realSlugs = new Set(real.map((page) => page.slug));
756
- const synthetic = this.apiRegistry.syntheticPages().filter((page) => {
757
- if (realSlugs.has(page.slug)) {
758
- console.log(chalk.yellow(`āš ļø API page ${page.slug} is shadowed by a hand-written page; skipping`));
759
- return false;
760
- }
761
- return true;
762
- });
763
- return [...real, ...synthetic];
764
- }
765
- /**
766
- * Writes the generated page(s) for a single MDX file: the doc page and, for a
767
- * section-index file, the section landing page. Deliberately does NOT run the
768
- * site-wide aggregations (pages index, layout, sitemap, llms, section
769
- * redirects) - the caller batches those so a bulk build runs them once at the
770
- * end instead of once per file (which is what made large builds O(n²)).
771
- */
772
- async writePageForFile(filePath) {
773
- const fullPath = path.join(this.watchDir, filePath);
774
- const content = await fs.readFile(fullPath, "utf8");
775
- const { data: frontmatter, content: mdxContent } = safeMatter(content, filePath);
776
- const { sectionSlug, pageSlug } = this.determineSectionForFile(filePath, frontmatter);
777
- const fullSlug = getFullSlug(pageSlug, sectionSlug);
778
- const isIndex = filePath === "index.mdx" || filePath === "./index.mdx";
779
- const isSectionIndex = this.sectionsConfig && pageSlug === "" && sectionSlug !== "";
780
- if (isIndex) {
781
- // The homepage is emitted by updatePagesIndex() in the aggregate pass, so
782
- // there is no per-file page to write here.
783
- console.log(chalk.blue("šŸ  Updating homepage with index.mdx content"));
784
- }
785
- else {
786
- const mdxFile = {
787
- path: filePath,
788
- content: mdxContent,
789
- frontmatter,
790
- slug: fullSlug,
791
- };
792
- // `openapi: <METHOD> <path>` (or an operationId) in frontmatter renders
793
- // that operation's playground inline with the author's prose. An unknown
794
- // reference is logged and the page still renders its prose (graceful).
795
- let apiOperation;
796
- if (frontmatter.openapi) {
797
- apiOperation = this.apiRegistry.lookup(String(frontmatter.openapi));
798
- if (!apiOperation) {
799
- console.error(chalk.red(`āŒ openapi frontmatter "${frontmatter.openapi}" in ${filePath} not found in any spec`));
800
- }
801
- }
802
- await this.generatePageFromMDX(mdxFile, apiOperation ? { apiOperation } : undefined);
803
- }
804
- if (isSectionIndex) {
805
- await this.updateSectionIndex(sectionSlug, frontmatter, mdxContent, filePath);
806
- }
807
- }
808
- /**
809
- * Regenerates every file that depends on the full set of pages (pages index,
810
- * root/site layout, sitemap, llms files, section redirects). Parses all MDX
811
- * exactly once and threads the result through each generator, so one refresh
812
- * is a single scan rather than one scan per generator.
813
- */
814
- async refreshSiteAggregates() {
815
- const pages = await this.buildAllPagesMeta();
816
- await this.updatePagesIndex();
817
- await this.updateRootLayout(pages);
818
- await this.updateSitemap(pages);
819
- await this.updateLlmsFiles(pages);
820
- await this.generateSectionIndexPages(pages);
821
- }
822
- async handleFileChange(action, filePath) {
823
- console.log(chalk.cyan(`šŸ“ File ${action}: ${filePath}`));
824
- try {
825
- await this.writePageForFile(filePath);
826
- await this.refreshSiteAggregates();
827
- console.log(chalk.green(`āœ… Generated page for: ${filePath}`));
828
- await this.maybeUpdateSections();
829
- }
830
- catch (error) {
831
- console.error(chalk.red(`āŒ Error processing ${filePath}:`), error);
832
- }
833
- }
834
- async handleFileDelete(filePath) {
835
- console.log(chalk.red(`šŸ—‘ļø File deleted: ${filePath}`));
836
- try {
837
- if (filePath === "index.mdx" || filePath === "./index.mdx") {
838
- console.log(chalk.blue("šŸ  Updating homepage - index.mdx deleted"));
839
- }
840
- else {
841
- // We don't have frontmatter for deleted files, so use directory-based matching
842
- const { sectionSlug, pageSlug } = this.determineSectionForFile(filePath, {});
843
- const fullSlug = getFullSlug(pageSlug, sectionSlug);
844
- const pagePath = path.join(this.outputDir, "app", "(site)", fullSlug);
845
- await fs.remove(pagePath);
846
- }
847
- await this.updatePagesIndex();
848
- await this.updateRootLayout();
849
- await this.updateSitemap();
850
- await this.updateLlmsFiles();
851
- console.log(chalk.green(`āœ… Removed page for: ${filePath}`));
852
- await this.maybeUpdateSections();
853
- }
854
- catch (error) {
855
- console.error(chalk.red(`āŒ Error removing page for ${filePath}:`), error);
856
- }
857
- }
858
- async processAllMDXFiles() {
859
- const files = await this.getAllMDXFiles();
860
- // Write each page first (the only genuinely per-file work), then run the
861
- // site-wide aggregations a single time. Doing the aggregations per file
862
- // re-scanned and re-parsed every MDX file on each iteration, which made a
863
- // full build O(n²); batching them makes it O(n). A single bad file is
864
- // logged and skipped so it never aborts the whole build.
865
- for (const file of files) {
866
- console.log(chalk.cyan(`šŸ“ Processing: ${file}`));
867
- try {
868
- await this.writePageForFile(file);
869
- }
870
- catch (error) {
871
- console.error(chalk.red(`āŒ Error processing ${file}:`), error);
872
- }
873
- }
874
- await this.refreshSiteAggregates();
875
- }
876
- async getAllMDXFiles() {
877
- const files = [];
878
- async function scanDir(dir, relativePath = "") {
879
- const entries = await fs.readdir(dir, { withFileTypes: true });
880
- for (const entry of entries) {
881
- const fullPath = path.join(dir, entry.name);
882
- const relPath = path.join(relativePath, entry.name);
883
- if (entry.isDirectory()) {
884
- await scanDir(fullPath, relPath);
885
- }
886
- else if (entry.name.endsWith(".mdx")) {
887
- files.push(relPath);
888
- }
889
- }
890
- }
891
- await scanDir(this.watchDir);
892
- return files;
893
- }
894
- async generateRootLayout() {
895
- const fontConfig = await this.loadFontConfig();
896
- const analyticsEnabled = this.analyticsConfig !== null;
897
- return rootLayoutTemplate(fontConfig, analyticsEnabled);
898
- }
899
- async generateSiteLayout(pages) {
900
- const resolvedPages = pages ?? (await this.buildAllPagesMeta());
901
- return siteLayoutTemplate(resolvedPages, this.sectionsConfig);
902
- }
903
- async generateSectionIndexPages(pages) {
904
- const nextSlugs = new Set();
905
- if (this.sectionsConfig && this.sectionsConfig.length > 0) {
906
- const resolvedPages = pages ?? (await this.buildAllPagesMeta());
907
- for (const section of this.sectionsConfig) {
908
- if (section.slug === "")
909
- continue;
910
- // Check if a page already exists at the section root
911
- const hasIndex = resolvedPages.some((p) => p.slug === section.slug);
912
- if (hasIndex)
913
- continue;
914
- // Find the first page in this section
915
- const sectionPages = resolvedPages
916
- .filter((p) => p.section === section.slug)
917
- .sort((a, b) => {
918
- if (a.categoryOrder !== b.categoryOrder)
919
- return a.categoryOrder - b.categoryOrder;
920
- return a.order - b.order;
921
- });
922
- if (sectionPages.length === 0)
923
- continue;
924
- const firstPage = sectionPages[0];
925
- const redirectContent = `import { redirect } from "next/navigation";
926
-
927
- export default function SectionIndex() {
928
- redirect("/${firstPage.slug}");
929
- }
930
- `;
931
- const pagePath = path.join(this.outputDir, "app", "(site)", section.slug, "page.tsx");
932
- await fs.ensureDir(path.dirname(pagePath));
933
- await fs.writeFile(pagePath, redirectContent, "utf8");
934
- nextSlugs.add(section.slug);
935
- console.log(chalk.blue(`šŸ”€ Generated section index redirect: /${section.slug} -> /${firstPage.slug}`));
936
- }
937
- }
938
- await this.cleanupStaleSectionIndexPages(nextSlugs);
939
- }
940
- /**
941
- * Removes section index redirects written earlier in this session whose
942
- * section has since disappeared (e.g. the API Reference section after the
943
- * `openapi` config is removed mid-watch). Only files that still contain the
944
- * generated redirect are deleted, so a hand-written page that has taken
945
- * over the slug is never touched. Fresh processes start clean anyway -
946
- * init() wipes app/ - so in-session tracking is enough.
947
- */
948
- async cleanupStaleSectionIndexPages(nextSlugs) {
949
- for (const stale of this.generatedSectionIndexSlugs) {
950
- if (nextSlugs.has(stale))
951
- continue;
952
- const pagePath = path.join(this.outputDir, "app", "(site)", stale, "page.tsx");
953
- try {
954
- if (!(await fs.pathExists(pagePath)))
955
- continue;
956
- const content = await fs.readFile(pagePath, "utf8");
957
- if (!content.includes("function SectionIndex()"))
958
- continue;
959
- await fs.remove(pagePath);
960
- await this.removeEmptyDirsUpTo(path.dirname(pagePath), path.join(this.outputDir, "app", "(site)"));
961
- console.log(chalk.blue(`🧹 Removed stale section index redirect: /${stale}`));
962
- }
963
- catch {
964
- // ignore
965
- }
966
- }
967
- this.generatedSectionIndexSlugs = nextSlugs;
968
- }
969
- /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
970
- async removeEmptyDirsUpTo(dir, stopDir) {
971
- const stop = path.resolve(stopDir);
972
- let current = path.resolve(dir);
973
- while (current !== stop && current.startsWith(stop + path.sep)) {
974
- try {
975
- const entries = await fs.readdir(current);
976
- if (entries.length > 0)
977
- return;
978
- await fs.remove(current);
979
- }
980
- catch {
981
- return;
982
- }
983
- current = path.dirname(current);
984
- }
985
- }
986
- async generatePageFromMDX(mdxFile, options) {
987
- const fm = mdxFile.frontmatter;
988
- const apiOperation = options?.apiOperation;
989
- // Pages containing <Update> blocks publish a subscribable changelog: an
990
- // RSS feed at {page-url}/rss.xml. Synthetic OpenAPI pages never contain
991
- // Update blocks, so skip the parse for them.
992
- const isSynthetic = mdxFile.path.startsWith("@openapi/");
993
- const updates = isSynthetic ? [] : parseUpdateBlocks(mdxFile.content);
994
- const hasFeed = updates.length > 0;
995
- const feedPath = `/${mdxFile.slug}/rss.xml`;
996
- const metadataBlock = generateMetadataBlock({
997
- title: fm.title,
998
- titleFallback: "Generated with Doccupine",
999
- name: fm.name,
1000
- titleOrder: "page-first",
1001
- description: fm.description,
1002
- icon: fm.icon,
1003
- image: fm.image,
1004
- canonicalPath: mdxFile.slug,
1005
- rssPath: hasFeed ? feedPath : undefined,
1006
- });
1007
- const jsonLd = generateJsonLdScript({
1008
- kind: "article",
1009
- canonicalPath: mdxFile.slug,
1010
- title: fm.title,
1011
- description: fm.description,
1012
- date: typeof fm.date === "string" ? fm.date : undefined,
1013
- updated: typeof fm.updated === "string"
1014
- ? fm.updated
1015
- : typeof fm.date === "string"
1016
- ? fm.date
1017
- : undefined,
1018
- image: fm.image,
1019
- });
1020
- // For an OpenAPI-backed page, embed the operation descriptor as a JS string
1021
- // literal parsed at load. Serializing to JSON then re-`JSON.parse`ing is
1022
- // total escaping for arbitrary JSON - unlike `escapeTemplateContent`, which
1023
- // only guards backticks/`${`/backslashes for the MDX prose literal.
1024
- const apiImport = apiOperation
1025
- ? `\nimport { ApiPlayground } from "@/components/layout/ApiPlayground";`
1026
- : "";
1027
- // The descriptor JSON always exceeds the 80-col print width, so emit the
1028
- // call pre-wrapped in the exact shape Prettier produces (argument on its own
1029
- // line with a trailing comma, single-quoted so the JSON's own double quotes
1030
- // need no escaping). Keeps generated endpoint pages Prettier-stable without
1031
- // running a formatter at build time.
1032
- const apiConst = apiOperation
1033
- ? (() => {
1034
- const arg = toJsStringLiteral(JSON.stringify(apiOperation));
1035
- const inline = `const operation = JSON.parse(${arg});`;
1036
- const decl = inline.length <= 80
1037
- ? inline
1038
- : `const operation = JSON.parse(\n ${arg},\n);`;
1039
- return `\n${decl}\n`;
1040
- })()
1041
- : "";
1042
- // The playground renders as a child of <Docs> so it sits inside the docs
1043
- // content column (a sibling would escape the layout and overlap the nav).
1044
- // Synthetic endpoint pages pass no `sourcePath`: it only namespaces Mermaid
1045
- // diagrams (which endpoint docs never contain), and its long `@openapi/...`
1046
- // value would push the opening tag past 80 cols and make Prettier rewrap it.
1047
- const sourcePathLiteral = JSON.stringify(mdxFile.path);
1048
- // `rss: true` frontmatter opts the page into an RSS button in the action
1049
- // bar (only when a feed actually exists). The playground branch keeps its
1050
- // fixed JSX shape - a feed on an inline-playground page stays reachable
1051
- // via autodiscovery. The buttoned form usually exceeds the 80-col print
1052
- // width, so pre-wrap it in the shape Prettier produces (attributes on
1053
- // their own lines) relative to its 6-space insertion indent.
1054
- const showRssButton = hasFeed && fm.rss === true && !apiOperation;
1055
- const docsAttrs = [
1056
- `content={content}`,
1057
- `sourcePath={${sourcePathLiteral}}`,
1058
- ...(showRssButton ? [`rssHref={${JSON.stringify(feedPath)}}`] : []),
1059
- ];
1060
- const inlineDocs = `<Docs ${docsAttrs.join(" ")} />`;
1061
- const docsElement = apiOperation
1062
- ? `<Docs content={content}>
1063
- <ApiPlayground operation={operation} />
1064
- </Docs>`
1065
- : inlineDocs.length + 6 <= 80
1066
- ? inlineDocs
1067
- : `<Docs\n${docsAttrs.map((attr) => ` ${attr}`).join("\n")}\n />`;
1068
- const pageContent = `import { Metadata } from "next";
1069
- import { Docs } from "@/components/Docs";
1070
- import { config } from "@/utils/config";${apiImport}
1071
-
1072
- const content = \`${escapeTemplateContent(mdxFile.content)}\`;
1073
- ${apiConst}
1074
- ${metadataBlock}
1075
-
1076
- // Doc pages have no per-request data: theme resolves client-side via the
1077
- // "dark" class on <html> (set before paint by the theme-init blocking
1078
- // script). Static rendering lets every response come from the edge cache.
1079
- export const dynamic = "force-static";
1080
- export const revalidate = false;
1081
-
1082
- export default function Page() {
1083
- ${jsonLd.declarations}
1084
-
1085
- return (
1086
- <>
1087
- ${jsonLd.element}
1088
- ${docsElement}
1089
- </>
1090
- );
1091
- }
1092
- `;
1093
- const pagePath = path.join(this.outputDir, "app", "(site)", mdxFile.slug, "page.tsx");
1094
- await fs.ensureDir(path.dirname(pagePath));
1095
- await fs.writeFile(pagePath, pageContent, "utf8");
1096
- // The feed route lives inside the page's directory, so a deleted page
1097
- // takes its feed along (handleFileDelete removes the whole dir) and the
1098
- // else-branch prunes the route when a regenerated page no longer has
1099
- // Update blocks. Cross-run staleness is covered by the app/ wipe in
1100
- // createNextJSStructure.
1101
- if (!isSynthetic) {
1102
- const rssDir = path.join(path.dirname(pagePath), "rss.xml");
1103
- if (hasFeed) {
1104
- await fs.ensureDir(rssDir);
1105
- await fs.writeFile(path.join(rssDir, "route.ts"), rssRouteTemplate({
1106
- pagePath: mdxFile.slug,
1107
- title: typeof fm.title === "string" ? fm.title : null,
1108
- description: typeof fm.description === "string" ? fm.description : null,
1109
- items: updates.map((update) => ({
1110
- title: update.label,
1111
- anchor: update.anchor,
1112
- description: update.description,
1113
- })),
1114
- }), "utf8");
1115
- }
1116
- else {
1117
- await fs.remove(rssDir);
1118
- }
1119
- }
1120
- }
1121
- /** Parses the configured OpenAPI spec(s) into the shared registry. */
1122
- async loadOpenApiRegistry() {
1123
- if (this.openApiSpecs.length === 0)
1124
- return;
1125
- await this.apiRegistry.load(this.openApiSpecs, this.rootDir, this.apiBaseSlug);
1126
- if (!this.apiRegistry.isEmpty) {
1127
- console.log(chalk.blue(`šŸ“˜ Loaded ${this.apiRegistry.all.length} API endpoint(s) from ${this.openApiSpecs.length} spec(s)`));
1128
- }
1129
- }
1130
- /**
1131
- * Generates one page per OpenAPI operation, (re)writes the request-execution
1132
- * allowlist consumed by the playground proxy + component, and removes endpoint
1133
- * pages that no longer exist in the spec. Safe to call when there are no specs
1134
- * - it still emits an empty allowlist and prunes any previously generated
1135
- * pages (e.g. after the `openapi` config is removed).
1136
- */
1137
- async writeApiPages() {
1138
- const nextSlugs = new Set();
1139
- for (const op of this.apiRegistry.all) {
1140
- const methodUpper = op.method.toUpperCase();
1141
- const mdxFile = {
1142
- path: `@openapi/${op.specName}/${op.method}${op.path}`,
1143
- content: buildEndpointDoc(op),
1144
- frontmatter: {
1145
- title: op.summary ?? `${methodUpper} ${op.path}`,
1146
- description: op.summary ?? "",
1147
- },
1148
- slug: op.slug,
1149
- };
1150
- try {
1151
- await this.generatePageFromMDX(mdxFile, { apiOperation: op });
1152
- nextSlugs.add(op.slug);
1153
- }
1154
- catch (error) {
1155
- console.error(chalk.red(`āŒ Error generating API page ${op.slug}:`), error);
1156
- }
1157
- }
1158
- await this.writeApiAllowlist();
1159
- await this.cleanupStaleApiPages(nextSlugs);
1160
- if (nextSlugs.size > 0) {
1161
- console.log(chalk.green(`🧩 Generated ${nextSlugs.size} API reference page(s)`));
1162
- }
1163
- }
1164
- /** Writes the request-execution allowlist (overwrites the shipped stub). */
1165
- async writeApiAllowlist() {
1166
- const target = path.join(this.outputDir, "services", "openapi", "playground-allowlist.json");
1167
- await fs.ensureDir(path.dirname(target));
1168
- await fs.writeFile(target, `${JSON.stringify(this.apiRegistry.allowlist(), null, 2)}\n`, "utf8");
1169
- }
1170
- apiManifestPath() {
1171
- return path.join(this.outputDir, ".doccupine-api-manifest.json");
1172
- }
1173
- async readApiManifest() {
1174
- try {
1175
- const manifestPath = this.apiManifestPath();
1176
- if (await fs.pathExists(manifestPath)) {
1177
- const raw = await fs.readFile(manifestPath, "utf8");
1178
- const parsed = JSON.parse(raw);
1179
- if (Array.isArray(parsed.pageSlugs)) {
1180
- return new Set(parsed.pageSlugs.filter((entry) => typeof entry === "string"));
1181
- }
1182
- }
1183
- }
1184
- catch {
1185
- // ignore corrupted manifest
1186
- }
1187
- return new Set();
1188
- }
1189
- async writeApiManifest(slugs) {
1190
- const payload = { pageSlugs: Array.from(slugs).sort() };
1191
- await fs.writeFile(this.apiManifestPath(), `${JSON.stringify(payload, null, 2)}\n`, "utf8");
1192
- }
1193
- /** Removes endpoint page directories that are no longer in the spec. */
1194
- async cleanupStaleApiPages(nextSlugs) {
1195
- const previous = new Set([
1196
- ...this.generatedApiPageSlugs,
1197
- ...(await this.readApiManifest()),
1198
- ]);
1199
- for (const stale of previous) {
1200
- if (nextSlugs.has(stale))
1201
- continue;
1202
- try {
1203
- const dir = path.join(this.outputDir, "app", "(site)", stale);
1204
- if (await fs.pathExists(dir)) {
1205
- await fs.remove(dir);
1206
- await this.removeEmptyDirsUpTo(path.dirname(dir), path.join(this.outputDir, "app", "(site)"));
1207
- }
1208
- }
1209
- catch {
1210
- // ignore
1211
- }
1212
- }
1213
- this.generatedApiPageSlugs = nextSlugs;
1214
- await this.writeApiManifest(nextSlugs);
1215
- }
1216
- /**
1217
- * (Re)points the spec-file watcher at the currently configured spec paths.
1218
- * Called at startup and whenever doccupine.json changes the `openapi` set,
1219
- * so specs added mid-session are watched without a restart.
1220
- */
1221
- async syncOpenApiSpecWatcher() {
1222
- if (this.openApiWatcher) {
1223
- await this.openApiWatcher.close();
1224
- this.openApiWatcher = null;
1225
- }
1226
- if (this.openApiSpecs.length === 0)
1227
- return;
1228
- const specPaths = this.openApiSpecs.map((spec) => path.resolve(this.rootDir, spec.file));
1229
- this.openApiWatcher = chokidar.watch(specPaths, {
1230
- persistent: true,
1231
- ignoreInitial: true,
1232
- });
1233
- this.openApiWatcher
1234
- .on("add", () => this.handleOpenApiChange())
1235
- .on("change", () => this.handleOpenApiChange())
1236
- .on("unlink", () => this.handleOpenApiChange())
1237
- .on("error", (error) => {
1238
- console.error(chalk.red("āŒ OpenAPI watcher error:"), error);
1239
- });
1240
- }
1241
- /**
1242
- * Reparses the spec(s) and rewrites everything derived from them: the
1243
- * endpoint pages and allowlist, the sections (the "API Reference" section
1244
- * appears and disappears with the registry), and the site aggregates.
1245
- */
1246
- async rebuildApiReference() {
1247
- await this.apiRegistry.load(this.openApiSpecs, this.rootDir, this.apiBaseSlug);
1248
- this.sectionsConfig = await this.resolveSections();
1249
- await this.writeApiPages();
1250
- await this.refreshSiteAggregates();
1251
- }
1252
- /** Reparses the spec(s) and regenerates the API reference on a watch event. */
1253
- async handleOpenApiChange() {
1254
- console.log(chalk.cyan("šŸ“˜ OpenAPI spec changed - regenerating API reference"));
1255
- try {
1256
- await this.rebuildApiReference();
1257
- console.log(chalk.green("āœ… API reference updated"));
1258
- }
1259
- catch (error) {
1260
- console.error(chalk.red("āŒ Error updating API reference:"), error);
1261
- }
1262
- }
1263
- /**
1264
- * Applies `openapi` edits in doccupine.json without a restart: reloads the
1265
- * registry, regenerates or prunes the endpoint pages and allowlist,
1266
- * refreshes nav/sitemap/llms, and re-points the spec-file watcher. Other
1267
- * fields (watchDir, outputDir, port) cannot be hot-applied, so a change
1268
- * there only logs a restart hint. Invalid or missing JSON (e.g. a
1269
- * half-written editor save) keeps the current configuration.
1270
- */
1271
- async handleDoccupineConfigChange() {
1272
- const configPath = path.join(this.rootDir, this.doccupineConfigFile);
1273
- let config;
1274
- try {
1275
- config = JSON.parse(await fs.readFile(configPath, "utf8"));
1276
- }
1277
- catch {
1278
- console.warn(chalk.yellow("āš ļø doccupine.json is missing or invalid - keeping the current configuration"));
1279
- return;
1280
- }
1281
- if ((config.watchDir &&
1282
- path.resolve(this.rootDir, config.watchDir) !== this.watchDir) ||
1283
- (config.outputDir &&
1284
- path.resolve(this.rootDir, config.outputDir) !== this.outputDir)) {
1285
- console.log(chalk.yellow("āš ļø watchDir/outputDir changes in doccupine.json need a restart to apply"));
1286
- }
1287
- const nextSpecs = normalizeOpenApiConfig(config.openapi);
1288
- if (JSON.stringify(nextSpecs) === JSON.stringify(this.openApiSpecs)) {
1289
- return;
1290
- }
1291
- console.log(chalk.cyan("šŸ“˜ OpenAPI configuration changed - updating API reference"));
1292
- this.openApiSpecs = nextSpecs;
1293
- try {
1294
- await this.syncOpenApiSpecWatcher();
1295
- await this.rebuildApiReference();
1296
- console.log(chalk.green("āœ… API reference updated"));
1297
- }
1298
- catch (error) {
1299
- console.error(chalk.red("āŒ Error updating API reference:"), error);
1300
- }
1301
- }
1302
- async updatePagesIndex() {
1303
- const files = await this.getAllMDXFiles();
1304
- let indexMDX = null;
1305
- for (const file of files) {
1306
- if (file === "index.mdx" || file === "./index.mdx") {
1307
- const fullPath = path.join(this.watchDir, file);
1308
- const content = await fs.readFile(fullPath, "utf8");
1309
- const { data: frontmatter, content: mdxContent } = safeMatter(content, file);
1310
- indexMDX = {
1311
- content: mdxContent,
1312
- title: frontmatter.title || "Welcome",
1313
- description: frontmatter.description || "",
1314
- icon: frontmatter.icon,
1315
- image: frontmatter.image,
1316
- name: frontmatter.name,
1317
- date: typeof frontmatter.date === "string" ? frontmatter.date : undefined,
1318
- updated: typeof frontmatter.updated === "string"
1319
- ? frontmatter.updated
1320
- : undefined,
1321
- openapi: typeof frontmatter.openapi === "string"
1322
- ? frontmatter.openapi
1323
- : undefined,
1324
- rss: frontmatter.rss === true,
1325
- };
1326
- break;
1327
- }
1328
- }
1329
- // The homepage publishes the same subscribable changelog as any other
1330
- // page (see generatePageFromMDX): <Update> blocks feed the site-root
1331
- // /rss.xml, and `rss: true` frontmatter opts into the RSS button.
1332
- const updates = indexMDX ? parseUpdateBlocks(indexMDX.content) : [];
1333
- const hasFeed = updates.length > 0;
1334
- const feedPath = "/rss.xml";
1335
- const metadataBlock = indexMDX
1336
- ? generateMetadataBlock({
1337
- title: indexMDX.title,
1338
- titleFallback: "Welcome",
1339
- name: indexMDX.name,
1340
- titleOrder: "name-first",
1341
- description: indexMDX.description || undefined,
1342
- icon: indexMDX.icon,
1343
- image: indexMDX.image,
1344
- canonicalPath: "",
1345
- rssPath: hasFeed ? feedPath : undefined,
1346
- })
1347
- : generateRuntimeOnlyMetadataBlock();
1348
- const homeJsonLd = generateJsonLdScript({
1349
- kind: "homepage",
1350
- canonicalPath: "",
1351
- title: indexMDX?.title,
1352
- description: indexMDX?.description || undefined,
1353
- date: indexMDX?.date,
1354
- updated: indexMDX?.updated ?? indexMDX?.date,
1355
- image: indexMDX?.image,
1356
- });
1357
- // The homepage supports the same `openapi: <METHOD> <path>` frontmatter as
1358
- // any other page: look the operation up and embed its playground inline.
1359
- let apiOperation;
1360
- if (indexMDX?.openapi) {
1361
- apiOperation = this.apiRegistry.lookup(indexMDX.openapi);
1362
- if (!apiOperation) {
1363
- console.error(chalk.red(`āŒ openapi frontmatter "${indexMDX.openapi}" in index.mdx not found in any spec`));
1364
- }
1365
- }
1366
- const apiImport = apiOperation
1367
- ? `\nimport { ApiPlayground } from "@/components/layout/ApiPlayground";`
1368
- : "";
1369
- const apiConst = apiOperation
1370
- ? `\nconst operation = JSON.parse(${JSON.stringify(JSON.stringify(apiOperation))});\n`
1371
- : "";
1372
- // Same gating as generatePageFromMDX: the playground branch keeps its
1373
- // fixed JSX shape, so a feed on a playground homepage stays reachable via
1374
- // autodiscovery. The buttoned inline form stays within the 80-col print
1375
- // width at its 6-space insertion indent, so it is Prettier-stable as is.
1376
- const showRssButton = hasFeed && indexMDX?.rss === true && !apiOperation;
1377
- const docsElement = apiOperation
1378
- ? `<Docs content={content} sourcePath="index.mdx">
1379
- <ApiPlayground operation={operation} />
1380
- </Docs>`
1381
- : showRssButton
1382
- ? `<Docs content={content} sourcePath="index.mdx" rssHref={"/rss.xml"} />`
1383
- : `<Docs content={content} sourcePath="index.mdx" />`;
1384
- const indexContent = `import { Metadata } from "next";
1385
- import { Docs } from "@/components/Docs";
1386
- import { config } from "@/utils/config";${apiImport}
1387
-
1388
- ${indexMDX ? `const content = \`${escapeTemplateContent(indexMDX.content)}\`;` : `const content = null;`}
1389
- ${apiConst}
1390
- ${metadataBlock}
1391
-
1392
- export const dynamic = "force-static";
1393
- export const revalidate = false;
1394
-
1395
- export default function Home() {
1396
- ${homeJsonLd.declarations}
1397
-
1398
- return (
1399
- <>
1400
- ${homeJsonLd.element}
1401
- ${docsElement}
1402
- </>
1403
- );
1404
- }
1405
- `;
1406
- const homePath = path.join(this.outputDir, "app", "(site)", "page.tsx");
1407
- await fs.ensureDir(path.dirname(homePath));
1408
- await fs.writeFile(homePath, indexContent, "utf8");
1409
- // Same lifecycle as the per-page feeds in generatePageFromMDX: write the
1410
- // root feed route while the homepage has Update blocks, prune it when
1411
- // they go away or index.mdx is deleted (this runs on every aggregate
1412
- // refresh, including the delete path).
1413
- const rssDir = path.join(this.outputDir, "app", "(site)", "rss.xml");
1414
- if (hasFeed && indexMDX) {
1415
- await fs.ensureDir(rssDir);
1416
- await fs.writeFile(path.join(rssDir, "route.ts"), rssRouteTemplate({
1417
- pagePath: "",
1418
- title: indexMDX.title,
1419
- description: indexMDX.description || null,
1420
- items: updates.map((update) => ({
1421
- title: update.label,
1422
- anchor: update.anchor,
1423
- description: update.description,
1424
- })),
1425
- }), "utf8");
1426
- }
1427
- else {
1428
- await fs.remove(rssDir);
1429
- }
1430
- }
1431
- async updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath) {
1432
- // This overwrites the page generatePageFromMDX just wrote for the same
1433
- // slug (section landings compose their metadata name-first), so the RSS
1434
- // state must be re-derived here or the overwrite silently drops the
1435
- // button and autodiscovery - the feed route survives either way since it
1436
- // lives in a sibling rss.xml/ dir.
1437
- const updates = parseUpdateBlocks(mdxContent);
1438
- const hasFeed = updates.length > 0;
1439
- const feedPath = `/${sectionSlug}/rss.xml`;
1440
- const showRssButton = hasFeed && frontmatter.rss === true;
1441
- const metadataBlock = generateMetadataBlock({
1442
- title: frontmatter.title,
1443
- titleFallback: "Section",
1444
- name: frontmatter.name,
1445
- titleOrder: "name-first",
1446
- description: frontmatter.description || undefined,
1447
- icon: frontmatter.icon,
1448
- image: frontmatter.image,
1449
- canonicalPath: sectionSlug,
1450
- rssPath: hasFeed ? feedPath : undefined,
1451
- });
1452
- const sectionJsonLd = generateJsonLdScript({
1453
- kind: "article",
1454
- canonicalPath: sectionSlug,
1455
- title: frontmatter.title,
1456
- description: frontmatter.description,
1457
- date: typeof frontmatter.date === "string" ? frontmatter.date : undefined,
1458
- updated: typeof frontmatter.updated === "string"
1459
- ? frontmatter.updated
1460
- : typeof frontmatter.date === "string"
1461
- ? frontmatter.date
1462
- : undefined,
1463
- image: frontmatter.image,
1464
- });
1465
- // Same Prettier pre-wrap contract as generatePageFromMDX: the buttoned
1466
- // form usually pushes the line past the 80-col print width, so emit it
1467
- // with attributes on their own lines relative to the 6-space indent.
1468
- const docsAttrs = [
1469
- `content={content}`,
1470
- `sourcePath={${JSON.stringify(sourcePath ?? `${sectionSlug}/index.mdx`)}}`,
1471
- ...(showRssButton ? [`rssHref={${JSON.stringify(feedPath)}}`] : []),
1472
- ];
1473
- const inlineDocs = `<Docs ${docsAttrs.join(" ")} />`;
1474
- const docsElement = inlineDocs.length + 6 <= 80
1475
- ? inlineDocs
1476
- : `<Docs\n${docsAttrs.map((attr) => ` ${attr}`).join("\n")}\n />`;
1477
- const indexContent = `import { Metadata } from "next";
1478
- import { Docs } from "@/components/Docs";
1479
- import { config } from "@/utils/config";
1480
-
1481
- const content = \`${escapeTemplateContent(mdxContent)}\`;
1482
-
1483
- ${metadataBlock}
1484
-
1485
- export const dynamic = "force-static";
1486
- export const revalidate = false;
1487
-
1488
- export default function Page() {
1489
- ${sectionJsonLd.declarations}
1490
-
1491
- return (
1492
- <>
1493
- ${sectionJsonLd.element}
1494
- ${docsElement}
1495
- </>
1496
- );
1497
- }
1498
- `;
1499
- const pagePath = path.join(this.outputDir, "app", "(site)", sectionSlug, "page.tsx");
1500
- await fs.ensureDir(path.dirname(pagePath));
1501
- await fs.writeFile(pagePath, indexContent, "utf8");
1502
- }
1503
- async updateRootLayout(pages) {
1504
- await fs.writeFile(path.join(this.outputDir, "app", "layout.tsx"), await this.generateRootLayout(), "utf8");
1505
- const siteLayoutPath = path.join(this.outputDir, "app", "(site)", "layout.tsx");
1506
- await fs.ensureDir(path.dirname(siteLayoutPath));
1507
- await fs.writeFile(siteLayoutPath, await this.generateSiteLayout(pages), "utf8");
1508
- }
1509
- async loadSiteUrl() {
1510
- const configPath = path.join(this.rootDir, "config.json");
1511
- try {
1512
- if (await fs.pathExists(configPath)) {
1513
- const content = await fs.readFile(configPath, "utf8");
1514
- const parsed = JSON.parse(content);
1515
- if (typeof parsed.url === "string" && parsed.url.trim() !== "") {
1516
- return parsed.url.trim().replace(/\/$/, "");
1517
- }
1518
- }
1519
- }
1520
- catch (error) {
1521
- console.warn(chalk.yellow("āš ļø Error reading config.json"), error);
1522
- }
1523
- return null;
1524
- }
1525
- buildSitemapEntries(pages) {
1526
- const sectionSlugs = new Set((this.sectionsConfig || [])
1527
- .map((s) => s.slug)
1528
- .filter((s) => typeof s === "string" && s !== ""));
1529
- const entries = pages.map((page) => {
1530
- let priority = 0.5;
1531
- if (page.slug === "") {
1532
- priority = 1.0;
1533
- }
1534
- else if (sectionSlugs.has(page.slug)) {
1535
- priority = 0.8;
1536
- }
1537
- return {
1538
- slug: page.slug,
1539
- lastModified: page.lastModified,
1540
- changeFrequency: "weekly",
1541
- priority,
1542
- };
1543
- });
1544
- if (!entries.some((entry) => entry.slug === "")) {
1545
- entries.unshift({
1546
- slug: "",
1547
- changeFrequency: "weekly",
1548
- priority: 1.0,
1549
- });
1550
- }
1551
- return entries;
1552
- }
1553
- async updateSitemap(pages) {
1554
- const sitemapPath = path.join(this.outputDir, "app", "sitemap.ts");
1555
- const siteUrl = await this.loadSiteUrl();
1556
- if (!siteUrl) {
1557
- if (await fs.pathExists(sitemapPath)) {
1558
- await fs.remove(sitemapPath);
1559
- console.log(chalk.yellow("šŸ—‘ļø Removed sitemap.ts (no site URL configured)"));
1560
- }
1561
- return;
1562
- }
1563
- const resolvedPages = pages ?? (await this.buildAllPagesMeta());
1564
- const entries = this.buildSitemapEntries(resolvedPages);
1565
- await fs.writeFile(sitemapPath, sitemapTemplate(entries), "utf8");
1566
- console.log(chalk.green(`šŸ—ŗļø Generated sitemap.ts with ${entries.length} page(s) using ${siteUrl}`));
1567
- }
1568
- async updateRobots() {
1569
- const siteUrl = await this.loadSiteUrl();
1570
- await fs.writeFile(path.join(this.outputDir, "app", "robots.ts"), robotsTemplate(siteUrl !== null), "utf8");
1571
- console.log(chalk.green(siteUrl
1572
- ? `šŸ¤– Regenerated robots.ts with sitemap link`
1573
- : `šŸ¤– Regenerated robots.ts (no sitemap link)`));
1574
- }
1575
- async loadSiteMetadata() {
1576
- const configPath = path.join(this.rootDir, "config.json");
1577
- let url = null;
1578
- let name = "Documentation";
1579
- let description = "";
1580
- try {
1581
- if (await fs.pathExists(configPath)) {
1582
- const content = await fs.readFile(configPath, "utf8");
1583
- const parsed = JSON.parse(content);
1584
- if (typeof parsed.url === "string" && parsed.url.trim() !== "") {
1585
- url = parsed.url.trim().replace(/\/$/, "");
1586
- }
1587
- if (typeof parsed.name === "string" && parsed.name.trim() !== "") {
1588
- name = parsed.name.trim();
1589
- }
1590
- else if (typeof parsed.title === "string" &&
1591
- parsed.title.trim() !== "") {
1592
- name = parsed.title.trim();
1593
- }
1594
- if (typeof parsed.description === "string" &&
1595
- parsed.description.trim() !== "") {
1596
- description = parsed.description.trim();
1597
- }
1598
- }
1599
- }
1600
- catch (error) {
1601
- console.warn(chalk.yellow("āš ļø Error reading config.json for llms metadata"), error);
1602
- }
1603
- return { url, name, description };
1604
- }
1605
- async readPageWithBody(page) {
1606
- // Synthetic OpenAPI pages have no backing .mdx file; their markdown body
1607
- // comes from the registry instead of disk.
1608
- if (!page.path.endsWith(".mdx")) {
1609
- return { ...page, body: this.apiRegistry.bodyForSlug(page.slug) ?? "" };
1610
- }
1611
- const fullPath = path.join(this.watchDir, page.path);
1612
- const raw = await fs.readFile(fullPath, "utf8");
1613
- const { content: body } = safeMatter(raw, page.path);
1614
- return { ...page, body };
1615
- }
1616
- llmsManifestPath() {
1617
- return path.join(this.outputDir, ".doccupine-llms-manifest.json");
1618
- }
1619
- async readLlmsManifest() {
1620
- const manifestPath = this.llmsManifestPath();
1621
- try {
1622
- if (await fs.pathExists(manifestPath)) {
1623
- const raw = await fs.readFile(manifestPath, "utf8");
1624
- const parsed = JSON.parse(raw);
1625
- if (Array.isArray(parsed.pageFiles)) {
1626
- return new Set(parsed.pageFiles.filter((entry) => typeof entry === "string"));
1627
- }
1628
- }
1629
- }
1630
- catch {
1631
- // ignore corrupted manifest
1632
- }
1633
- return new Set();
1634
- }
1635
- async writeLlmsManifest(pageFiles) {
1636
- const manifestPath = this.llmsManifestPath();
1637
- const payload = { pageFiles: Array.from(pageFiles).sort() };
1638
- const json = JSON.stringify(payload, null, 2) + "\n";
1639
- await fs.writeFile(manifestPath, json, "utf8");
1640
- }
1641
- async updateLlmsFiles(pages) {
1642
- const publicDir = path.join(this.outputDir, "public");
1643
- await fs.ensureDir(publicDir);
1644
- const { url: baseUrl, name, description } = await this.loadSiteMetadata();
1645
- const resolvedPages = pages ?? (await this.buildAllPagesMeta());
1646
- const pagesWithBodies = await Promise.all(resolvedPages.map((page) => this.readPageWithBody(page)));
1647
- const indexContent = llmsIndexTemplate({
1648
- siteName: name,
1649
- siteDescription: description,
1650
- baseUrl,
1651
- pages: resolvedPages,
1652
- sectionsConfig: this.sectionsConfig,
1653
- });
1654
- const fullContent = llmsFullTemplate({
1655
- siteName: name,
1656
- siteDescription: description,
1657
- baseUrl,
1658
- pages: pagesWithBodies,
1659
- sectionsConfig: this.sectionsConfig,
1660
- });
1661
- await fs.writeFile(path.join(publicDir, "llms.txt"), indexContent, "utf8");
1662
- await fs.writeFile(path.join(publicDir, "llms-full.txt"), fullContent, "utf8");
1663
- const skillContent = skillMdTemplate({
1664
- siteName: name,
1665
- siteDescription: description,
1666
- baseUrl,
1667
- pages: resolvedPages,
1668
- sectionsConfig: this.sectionsConfig,
1669
- });
1670
- await fs.writeFile(path.join(publicDir, "skill.md"), skillContent, "utf8");
1671
- // MCP discovery manifest. Needs an absolute URL, so it only exists when
1672
- // config.json declares the site url; it is pruned if the url is removed.
1673
- const mcpJsonPath = path.join(publicDir, ".well-known", "mcp.json");
1674
- if (baseUrl) {
1675
- const mcpJson = JSON.stringify({
1676
- mcpServers: {
1677
- [siteDocsSlug(name)]: {
1678
- url: `${baseUrl}/api/mcp`,
1679
- transport: "streamable-http",
1680
- },
1681
- },
1682
- }, null, 2) + "\n";
1683
- await fs.ensureDir(path.dirname(mcpJsonPath));
1684
- await fs.writeFile(mcpJsonPath, mcpJson, "utf8");
1685
- }
1686
- else if (await fs.pathExists(mcpJsonPath)) {
1687
- await fs.remove(mcpJsonPath);
1688
- }
1689
- const nextRelativePaths = new Set();
1690
- await Promise.all(pagesWithBodies.map(async (page) => {
1691
- const relPath = page.slug === "" ? "index.md" : `${page.slug}.md`;
1692
- const targetPath = path.join(publicDir, relPath);
1693
- await fs.ensureDir(path.dirname(targetPath));
1694
- await fs.writeFile(targetPath, llmsPageTemplate(page, baseUrl), "utf8");
1695
- nextRelativePaths.add(relPath);
1696
- }));
1697
- const previousRelativePaths = new Set([
1698
- ...this.generatedLlmsPagePaths,
1699
- ...(await this.readLlmsManifest()),
1700
- ]);
1701
- for (const stale of previousRelativePaths) {
1702
- if (!nextRelativePaths.has(stale)) {
1703
- try {
1704
- const stalePath = path.join(publicDir, stale);
1705
- if (await fs.pathExists(stalePath)) {
1706
- await fs.remove(stalePath);
1707
- }
1708
- }
1709
- catch {
1710
- // ignore
1711
- }
1712
- }
1713
- }
1714
- this.generatedLlmsPagePaths = nextRelativePaths;
1715
- await this.writeLlmsManifest(nextRelativePaths);
1716
- console.log(chalk.green(`šŸ¤– Generated llms.txt and llms-full.txt with ${resolvedPages.length} page(s)${baseUrl ? ` using ${baseUrl}` : " (relative URLs)"}`));
1717
- }
1718
- async stop() {
1719
- if (this.watcher) {
1720
- await this.watcher.close();
1721
- console.log(chalk.yellow("šŸ‘‹ Stopped watching for MDX changes"));
1722
- }
1723
- if (this.configWatcher) {
1724
- await this.configWatcher.close();
1725
- console.log(chalk.yellow("šŸ‘‹ Stopped watching for config changes"));
1726
- }
1727
- if (this.fontWatcher) {
1728
- await this.fontWatcher.close();
1729
- console.log(chalk.yellow("šŸ‘‹ Stopped watching for font config changes"));
1730
- }
1731
- if (this.analyticsWatcher) {
1732
- await this.analyticsWatcher.close();
1733
- console.log(chalk.yellow("šŸ‘‹ Stopped watching for analytics config changes"));
1734
- }
1735
- if (this.openApiWatcher) {
1736
- await this.openApiWatcher.close();
1737
- console.log(chalk.yellow("šŸ‘‹ Stopped watching for OpenAPI spec changes"));
1738
- }
1739
- if (this.doccupineConfigWatcher) {
1740
- await this.doccupineConfigWatcher.close();
1741
- console.log(chalk.yellow("šŸ‘‹ Stopped watching for doccupine.json changes"));
1742
- }
1743
- if (this.publicWatcher) {
1744
- await this.publicWatcher.close();
1745
- console.log(chalk.yellow("šŸ‘‹ Stopped watching for public directory changes"));
1746
- }
1747
- if (this.rootDirWatcher) {
1748
- await this.rootDirWatcher.close();
1749
- }
1750
- }
1751
- }
1752
- program
1753
- .name("doccupine")
1754
- .description("Watch MDX files and generate Next.js documentation pages automatically")
1755
- .version(version);
1756
- program
1757
- .command("watch", { isDefault: true })
1758
- .description("Watch a directory for MDX changes and generate Next.js app")
1759
- .option("--port <port>", "Port for Next.js dev server", "3000")
1760
- .option("--verbose", "Show verbose output")
1761
- .option("--reset", "Reset configuration and prompt for new directories")
1762
- .option("--package-manager <name>", "Package manager for the generated app: pnpm or npm (default: auto-detect)")
1763
- .action(async (options) => {
1764
- const configManager = new ConfigManager();
1765
- const config = await configManager.getConfig({
1766
- reset: options.reset,
1767
- port: options.port,
1768
- });
1769
- const generator = new MDXToNextJSGenerator(config.watchDir, config.outputDir, normalizeOpenApiConfig(config.openapi));
1770
- // Config paths are project-relative; child processes get an absolute cwd.
1771
- const outputDir = path.resolve(process.cwd(), config.outputDir);
1772
- await generator.init();
1773
- let devServer = null;
1774
- console.log(chalk.blue("šŸ“¦ Installing dependencies..."));
1775
- const { spawn } = await import("child_process");
1776
- // Prefer pnpm (the generated app ships a pnpm workspace) and fall back to
1777
- // npm. A --package-manager flag or a "packageManager" field in
1778
- // doccupine.json overrides detection; the flag wins.
1779
- const packageManager = resolvePackageManager(options.packageManager ?? config.packageManager);
1780
- console.log(chalk.blue(`šŸ“¦ Using ${packageManager.name}...`));
1781
- const install = spawn(packageManager.bin, ["install"], {
1782
- cwd: outputDir,
1783
- stdio: "inherit",
1784
- });
1785
- await new Promise((resolve, reject) => {
1786
- install.on("close", (code) => {
1787
- if (code === 0) {
1788
- console.log(chalk.green("āœ… Dependencies installed"));
1789
- resolve(void 0);
1790
- }
1791
- else {
1792
- reject(new Error(`${packageManager.name} install failed with code ${code}`));
1793
- }
1794
- });
1795
- install.on("error", reject);
1796
- });
1797
- const port = await findAvailablePort(parseInt(config.port, 10));
1798
- if (port !== parseInt(config.port, 10)) {
1799
- console.log(chalk.yellow(`āš ļø Port ${config.port} is in use, using port ${port} instead`));
1800
- }
1801
- console.log(chalk.blue(`šŸš€ Starting Next.js dev server on port ${port}...`));
1802
- const portStr = String(port);
1803
- const devArgs = packageManager.name === "npm"
1804
- ? ["run", "dev", "--", "--port", portStr]
1805
- : ["run", "dev", "--port", portStr];
1806
- devServer = spawn(packageManager.bin, devArgs, {
1807
- cwd: outputDir,
1808
- stdio: ["ignore", "pipe", "pipe"],
1809
- });
1810
- devServer.stdout?.on("data", (data) => {
1811
- const output = data.toString();
1812
- if (output.includes("Ready") || output.includes("started")) {
1813
- console.log(chalk.green(`🌐 Next.js ready at http://localhost:${port}`));
1814
- }
1815
- if (options.verbose) {
1816
- process.stdout.write(chalk.gray("[Next.js] ") + output);
1817
- }
1818
- else if (output.includes("compiled") ||
1819
- output.includes("error") ||
1820
- output.includes("Ready")) {
1821
- process.stdout.write(chalk.gray("[Next.js] ") + output);
1822
- }
1823
- });
1824
- devServer.stderr?.on("data", (data) => {
1825
- const output = data.toString();
1826
- if (options.verbose ||
1827
- output.includes("Error") ||
1828
- output.includes("error")) {
1829
- process.stderr.write(chalk.red("[Next.js] ") + output);
1830
- }
1831
- });
1832
- devServer.on("error", (error) => {
1833
- console.error(chalk.red("āŒ Error starting dev server:"), error);
1834
- });
1835
- devServer.on("close", (code) => {
1836
- if (code && code !== 0) {
1837
- console.error(chalk.red(`āŒ Next.js dev server exited with code ${code}`));
1838
- }
1839
- });
1840
- await generator.startWatching();
1841
- process.on("SIGINT", async () => {
1842
- console.log(chalk.yellow("\nšŸ›‘ Shutting down..."));
1843
- await generator.stop();
1844
- if (devServer) {
1845
- devServer.kill();
1846
- }
1847
- process.exit(0);
1848
- });
1849
- console.log(chalk.green("šŸŽ‰ Generator is running! Press Ctrl+C to stop."));
1850
- console.log(chalk.cyan(`šŸ“ Edit your MDX files in: ${config.watchDir}`));
1851
- });
1852
- program
1853
- .command("build")
1854
- .description("One-time build of Next.js app from MDX files")
1855
- .option("--reset", "Reset configuration and prompt for new directories")
1856
- .action(async (options) => {
1857
- const configManager = new ConfigManager();
1858
- const config = await configManager.getConfig({
1859
- reset: options.reset,
1860
- });
1861
- const generator = new MDXToNextJSGenerator(config.watchDir, config.outputDir, normalizeOpenApiConfig(config.openapi));
1862
- await generator.init();
1863
- console.log(chalk.green("šŸŽ‰ Build complete!"));
1864
- });
1865
- program
1866
- .command("config")
1867
- .description("Show or reset configuration")
1868
- .option("--show", "Show current configuration")
1869
- .option("--reset", "Reset configuration")
1870
- .action(async (options) => {
1871
- const configManager = new ConfigManager();
1872
- if (options.show) {
1873
- const config = await configManager.loadConfig();
1874
- if (config) {
1875
- console.log(chalk.blue("šŸ“„ Current configuration:"));
1876
- console.log(chalk.white("Watch Directory:"), chalk.cyan(path.relative(process.cwd(), config.watchDir)));
1877
- console.log(chalk.white("Output Directory:"), chalk.cyan(path.relative(process.cwd(), config.outputDir)));
1878
- console.log(chalk.white("Port:"), chalk.cyan(config.port || "3000"));
1879
- }
1880
- else {
1881
- console.log(chalk.yellow("āš ļø No configuration file found"));
1882
- }
1883
- }
1884
- else if (options.reset) {
1885
- await configManager.getConfig({ reset: true });
1886
- console.log(chalk.green("āœ… Configuration reset"));
1887
- }
1888
- else {
1889
- console.log(chalk.blue("Use --show to display configuration or --reset to reset it"));
1890
- }
1891
- });
1892
7
  /**
1893
8
  * True when this file is what node was asked to run, rather than a module some
1894
- * other process imported. The test suite imports this file for its exported
1895
- * helpers; without this guard, that import parses argv, falls through to the
1896
- * default `watch` command, and prompts for config / starts file watchers.
1897
- *
1898
- * Compares realpaths because npm installs the bin as a symlink
1899
- * (`node_modules/.bin/doccupine` -> `dist/index.js`), so `process.argv[1]` and
1900
- * `import.meta.url` can name the same file by different paths.
9
+ * other process imported. Compares realpaths because npm installs the bin as a
10
+ * symlink (`node_modules/.bin/doccupine` -> `dist/index.js`).
1901
11
  */
1902
12
  export function isProcessEntrypoint(entry = process.argv[1], self = __filename) {
1903
13
  if (!entry)
@@ -1913,5 +23,6 @@ export function isProcessEntrypoint(entry = process.argv[1], self = __filename)
1913
23
  }
1914
24
  }
1915
25
  if (isProcessEntrypoint()) {
1916
- program.parse();
26
+ const { runCli } = await import("./cli.js");
27
+ await runCli();
1917
28
  }