doccupine 0.0.142 → 0.0.144
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.
- package/README.md +1 -1
- package/dist/cli.d.ts +6 -0
- package/dist/cli.js +130 -22
- package/dist/generator/api-reference-generator.d.ts +20 -0
- package/dist/generator/api-reference-generator.js +95 -0
- package/dist/generator/app-scaffolder.d.ts +19 -0
- package/dist/generator/app-scaffolder.js +54 -0
- package/dist/generator/generated-route-manager.d.ts +17 -0
- package/dist/generator/generated-route-manager.js +91 -0
- package/dist/generator/page-catalog.d.ts +17 -0
- package/dist/generator/page-catalog.js +68 -0
- package/dist/generator/page-renderer.d.ts +31 -0
- package/dist/generator/page-renderer.js +248 -0
- package/dist/generator/project-config-repository.d.ts +25 -0
- package/dist/generator/project-config-repository.js +133 -0
- package/dist/generator/public-asset-manager.d.ts +20 -0
- package/dist/generator/public-asset-manager.js +225 -0
- package/dist/generator/section-resolver.d.ts +13 -0
- package/dist/generator/section-resolver.js +150 -0
- package/dist/generator/secure-source-fs.d.ts +27 -0
- package/dist/generator/secure-source-fs.js +361 -0
- package/dist/generator/site-artifacts.d.ts +22 -0
- package/dist/generator/site-artifacts.js +159 -0
- package/dist/generator/watch-coordinator.d.ts +57 -0
- package/dist/generator/watch-coordinator.js +438 -0
- package/dist/lib/generated-artifacts.d.ts +3 -0
- package/dist/lib/generated-artifacts.js +27 -1
- package/dist/lib/layout.d.ts +1 -17
- package/dist/lib/layout.js +5 -4
- package/dist/lib/project-config.d.ts +3 -0
- package/dist/lib/project-config.js +110 -0
- package/dist/lib/structures.js +2 -0
- package/dist/lib/types.d.ts +14 -1
- package/dist/mdx-to-nextjs-generator.d.ts +7 -25
- package/dist/mdx-to-nextjs-generator.js +126 -1574
- package/dist/templates/app/api/rag/route.d.ts +1 -1
- package/dist/templates/app/api/rag/route.js +2 -1
- package/dist/templates/components/Chat.d.ts +1 -1
- package/dist/templates/components/Chat.js +2 -1
- package/dist/templates/components/MDXComponents.d.ts +1 -1
- package/dist/templates/components/MDXComponents.js +1 -1
- package/dist/templates/components/layout/Accordion.d.ts +1 -1
- package/dist/templates/components/layout/Accordion.js +2 -3
- package/dist/templates/components/layout/Space.d.ts +1 -0
- package/dist/templates/components/layout/Space.js +70 -0
- package/dist/templates/mdx/space.mdx.d.ts +1 -1
- package/dist/templates/mdx/space.mdx.js +27 -27
- package/dist/templates/next.config.js +2 -2
- package/dist/templates/package.js +2 -2
- package/dist/templates/proxy.js +1 -1
- package/dist/templates/services/mcp/server.d.ts +1 -1
- package/dist/templates/services/mcp/server.js +2 -12
- package/package.json +2 -2
|
@@ -1,64 +1,29 @@
|
|
|
1
|
-
import chokidar from "chokidar";
|
|
2
1
|
import fs from "fs-extra";
|
|
3
|
-
import { constants } from "node:fs";
|
|
4
|
-
import { open } from "node:fs/promises";
|
|
5
2
|
import path from "path";
|
|
6
3
|
import chalk from "chalk";
|
|
7
|
-
import { appStructure, obsoleteFiles, startingDocsStructure, } from "./lib/structures.js";
|
|
8
4
|
import { rootLayoutTemplate, siteLayoutTemplate } from "./lib/layout.js";
|
|
9
5
|
import { normalizeOpenApiConfig, validateConfig, } from "./lib/config-manager.js";
|
|
10
6
|
import { GeneratedArtifacts } from "./lib/generated-artifacts.js";
|
|
11
|
-
import { claimOutputDirectory,
|
|
12
|
-
import { OpenApiRegistry, DEFAULT_API_BASE_SLUG
|
|
13
|
-
import {
|
|
14
|
-
import { generateMetadataBlock, generateRuntimeOnlyMetadataBlock, generateJsonLdScript, } from "./lib/metadata.js";
|
|
15
|
-
import { parseUpdateBlocks } from "./lib/rss.js";
|
|
7
|
+
import { claimOutputDirectory, resolveOutputPath, } from "./lib/output-safety.js";
|
|
8
|
+
import { OpenApiRegistry, DEFAULT_API_BASE_SLUG } from "./lib/openapi.js";
|
|
9
|
+
import { getFullSlug, safeMatter, writeFileAtomic } from "./lib/utils.js";
|
|
16
10
|
import { nextConfigTemplate } from "./templates/next.config.js";
|
|
17
|
-
import { pnpmWorkspaceTemplate } from "./templates/pnpmWorkspace.js";
|
|
18
11
|
import { proxyTemplate } from "./templates/proxy.js";
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
".well-known/mcp.json",
|
|
31
|
-
]);
|
|
32
|
-
function normalizePublicArtifactPath(relativePath) {
|
|
33
|
-
return relativePath.replace(/\\/g, "/").toLowerCase();
|
|
34
|
-
}
|
|
35
|
-
function isPublicAggregate(relativePath) {
|
|
36
|
-
return PUBLIC_AGGREGATE_PATHS.has(normalizePublicArtifactPath(relativePath));
|
|
37
|
-
}
|
|
38
|
-
function isManagedPublicArtifact(relativePath) {
|
|
39
|
-
const normalized = normalizePublicArtifactPath(relativePath);
|
|
40
|
-
return PUBLIC_AGGREGATE_PATHS.has(normalized) || normalized.endsWith(".md");
|
|
41
|
-
}
|
|
42
|
-
function errorCode(error) {
|
|
43
|
-
return error && typeof error === "object" && "code" in error
|
|
44
|
-
? String(error.code)
|
|
45
|
-
: undefined;
|
|
46
|
-
}
|
|
47
|
-
function sameFileIdentity(left, right) {
|
|
48
|
-
return left.dev === right.dev && left.ino === right.ino;
|
|
49
|
-
}
|
|
12
|
+
import { SecureSourceFs } from "./generator/secure-source-fs.js";
|
|
13
|
+
import { AppScaffolder } from "./generator/app-scaffolder.js";
|
|
14
|
+
import { ApiReferenceGenerator } from "./generator/api-reference-generator.js";
|
|
15
|
+
import { GeneratedRouteManager } from "./generator/generated-route-manager.js";
|
|
16
|
+
import { ProjectConfigRepository } from "./generator/project-config-repository.js";
|
|
17
|
+
import { PublicAssetManager } from "./generator/public-asset-manager.js";
|
|
18
|
+
import { WatchCoordinator } from "./generator/watch-coordinator.js";
|
|
19
|
+
import { addApiReferenceSection, determineSectionRoute, discoverSections, } from "./generator/section-resolver.js";
|
|
20
|
+
import { renderHomepage, renderMdxPage, renderSectionPage, } from "./generator/page-renderer.js";
|
|
21
|
+
import { buildRealPagesMeta as buildRealPageCatalog, mergePages as mergePageCatalog, parseMdxPageMeta, } from "./generator/page-catalog.js";
|
|
22
|
+
import { loadSiteMetadata, loadSiteUrl as loadSiteUrlArtifact, writeLlmsFiles, writeRobots, writeSitemap, } from "./generator/site-artifacts.js";
|
|
50
23
|
export class MDXToNextJSGenerator {
|
|
51
24
|
watchDir;
|
|
52
25
|
outputDir;
|
|
53
26
|
rootDir;
|
|
54
|
-
watcher = null;
|
|
55
|
-
configWatcher = null;
|
|
56
|
-
fontWatcher = null;
|
|
57
|
-
publicWatcher = null;
|
|
58
|
-
rootDirWatcher = null;
|
|
59
|
-
analyticsWatcher = null;
|
|
60
|
-
openApiWatcher = null;
|
|
61
|
-
doccupineConfigWatcher = null;
|
|
62
27
|
doccupineConfigFile = "doccupine.json";
|
|
63
28
|
configFiles = [
|
|
64
29
|
"theme.json",
|
|
@@ -78,192 +43,61 @@ export class MDXToNextJSGenerator {
|
|
|
78
43
|
apiBaseSlug = DEFAULT_API_BASE_SLUG;
|
|
79
44
|
apiRegistry = new OpenApiRegistry();
|
|
80
45
|
artifacts;
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
46
|
+
sourceFs;
|
|
47
|
+
appScaffolder;
|
|
48
|
+
apiReferenceGenerator;
|
|
49
|
+
generatedRouteManager;
|
|
50
|
+
projectConfigRepository;
|
|
51
|
+
publicAssetManager;
|
|
52
|
+
watchCoordinator;
|
|
85
53
|
constructor(watchDir, outputDir, openApiSpecs = [], rootDir = process.cwd()) {
|
|
86
54
|
this.watchDir = path.resolve(watchDir);
|
|
87
55
|
this.outputDir = path.resolve(outputDir);
|
|
88
56
|
this.rootDir = path.resolve(rootDir);
|
|
89
57
|
this.openApiSpecs = openApiSpecs;
|
|
90
58
|
this.artifacts = new GeneratedArtifacts(this.outputDir);
|
|
59
|
+
this.sourceFs = new SecureSourceFs(this.watchDir, this.rootDir);
|
|
60
|
+
this.appScaffolder = new AppScaffolder(this.outputDir);
|
|
61
|
+
this.apiReferenceGenerator = new ApiReferenceGenerator(this.outputDir, this.artifacts);
|
|
62
|
+
this.generatedRouteManager = new GeneratedRouteManager(this.outputDir, this.artifacts);
|
|
63
|
+
this.projectConfigRepository = new ProjectConfigRepository(this.rootDir, this.outputDir, this.sourceFs, this.configFiles, this.fontConfigFile, this.analyticsConfigFile);
|
|
64
|
+
this.publicAssetManager = new PublicAssetManager(this.rootDir, this.outputDir, this.artifacts, this.sourceFs);
|
|
65
|
+
this.watchCoordinator = new WatchCoordinator({
|
|
66
|
+
watchDir: this.watchDir,
|
|
67
|
+
rootDir: this.rootDir,
|
|
68
|
+
configFiles: this.configFiles,
|
|
69
|
+
fontConfigFile: this.fontConfigFile,
|
|
70
|
+
analyticsConfigFile: this.analyticsConfigFile,
|
|
71
|
+
doccupineConfigFile: this.doccupineConfigFile,
|
|
72
|
+
sourceFs: this.sourceFs,
|
|
73
|
+
getOpenApiSpecs: () => this.openApiSpecs,
|
|
74
|
+
callbacks: {
|
|
75
|
+
syncOpenApiSpecWatcher: () => this.syncOpenApiSpecWatcher(),
|
|
76
|
+
handleFileChange: (action, filePath) => this.handleFileChange(action, filePath),
|
|
77
|
+
handleFileDelete: (filePath) => this.handleFileDelete(filePath),
|
|
78
|
+
handleConfigFileChange: (filePath) => this.handleConfigFileChange(filePath),
|
|
79
|
+
handleConfigFileDelete: (filePath) => this.handleConfigFileDelete(filePath),
|
|
80
|
+
handleFontConfigChange: () => this.handleFontConfigChange(),
|
|
81
|
+
handleFontConfigDelete: () => this.handleFontConfigDelete(),
|
|
82
|
+
handleAnalyticsConfigChange: () => this.handleAnalyticsConfigChange(),
|
|
83
|
+
handleAnalyticsConfigDelete: () => this.handleAnalyticsConfigDelete(),
|
|
84
|
+
handleDoccupineConfigChange: () => this.handleDoccupineConfigChange(),
|
|
85
|
+
handleOpenApiChange: () => this.handleOpenApiChange(),
|
|
86
|
+
copyPublicFiles: () => this.copyPublicFiles(),
|
|
87
|
+
handlePublicFileChange: (filePath) => this.handlePublicFileChange(filePath),
|
|
88
|
+
handlePublicFileDelete: (filePath) => this.handlePublicFileDelete(filePath),
|
|
89
|
+
processAllMDXFiles: () => this.processAllMDXFiles(),
|
|
90
|
+
},
|
|
91
|
+
});
|
|
91
92
|
}
|
|
92
93
|
outputPath(...segments) {
|
|
93
94
|
return resolveOutputPath(this.outputDir, ...segments);
|
|
94
95
|
}
|
|
95
|
-
publicOutputFilePath(relativePath) {
|
|
96
|
-
const parent = path.dirname(relativePath);
|
|
97
|
-
const outputParent = parent === "."
|
|
98
|
-
? this.outputPath("public")
|
|
99
|
-
: this.outputPath("public", parent);
|
|
100
|
-
return resolveWithin(outputParent, path.basename(relativePath));
|
|
101
|
-
}
|
|
102
|
-
sourcePathError(label, sourcePath, detail) {
|
|
103
|
-
return new Error(`Refusing to use ${label} at ${sourcePath}: ${detail}. Replace it with a real file or directory inside the source root.`);
|
|
104
|
-
}
|
|
105
|
-
async realSourceRoot(root, label, rejectRootSymlink) {
|
|
106
|
-
let rootStat;
|
|
107
|
-
try {
|
|
108
|
-
rootStat = await fs.lstat(root);
|
|
109
|
-
}
|
|
110
|
-
catch (error) {
|
|
111
|
-
if (errorCode(error) === "ENOENT") {
|
|
112
|
-
throw this.sourcePathError(label, root, "the source root does not exist");
|
|
113
|
-
}
|
|
114
|
-
throw error;
|
|
115
|
-
}
|
|
116
|
-
if (rootStat.isSymbolicLink() && rejectRootSymlink) {
|
|
117
|
-
throw this.sourcePathError(label, root, "the source root is a symbolic link");
|
|
118
|
-
}
|
|
119
|
-
const realRoot = await fs.realpath(root);
|
|
120
|
-
if (!(await fs.stat(realRoot)).isDirectory()) {
|
|
121
|
-
throw this.sourcePathError(label, root, "the source root is not a directory");
|
|
122
|
-
}
|
|
123
|
-
return realRoot;
|
|
124
|
-
}
|
|
125
|
-
async readSafeSourceFile(root, sourcePath, label, rejectRootSymlink) {
|
|
126
|
-
const resolvedRoot = path.resolve(root);
|
|
127
|
-
const resolvedSource = path.resolve(sourcePath);
|
|
128
|
-
if (!isPathInside(resolvedRoot, resolvedSource)) {
|
|
129
|
-
throw this.sourcePathError(label, resolvedSource, `the path is outside ${resolvedRoot}`);
|
|
130
|
-
}
|
|
131
|
-
const realRoot = await this.realSourceRoot(resolvedRoot, label, rejectRootSymlink);
|
|
132
|
-
const relativePath = path.relative(resolvedRoot, resolvedSource);
|
|
133
|
-
const components = relativePath.split(path.sep).filter(Boolean);
|
|
134
|
-
let currentPath = resolvedRoot;
|
|
135
|
-
for (const [index, component] of components.entries()) {
|
|
136
|
-
currentPath = path.join(currentPath, component);
|
|
137
|
-
let stat;
|
|
138
|
-
try {
|
|
139
|
-
stat = await fs.lstat(currentPath);
|
|
140
|
-
}
|
|
141
|
-
catch (error) {
|
|
142
|
-
if (errorCode(error) === "ENOENT") {
|
|
143
|
-
throw this.sourcePathError(label, currentPath, "the path does not exist");
|
|
144
|
-
}
|
|
145
|
-
throw error;
|
|
146
|
-
}
|
|
147
|
-
if (stat.isSymbolicLink()) {
|
|
148
|
-
throw this.sourcePathError(label, currentPath, "the path is a symbolic link");
|
|
149
|
-
}
|
|
150
|
-
if (index < components.length - 1 && !stat.isDirectory()) {
|
|
151
|
-
throw this.sourcePathError(label, currentPath, "a path component is not a directory");
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
const sourceStat = await fs.lstat(resolvedSource);
|
|
155
|
-
if (!sourceStat.isFile()) {
|
|
156
|
-
throw this.sourcePathError(label, resolvedSource, "expected a regular file");
|
|
157
|
-
}
|
|
158
|
-
const realSource = await fs.realpath(resolvedSource);
|
|
159
|
-
if (!isPathInside(realRoot, realSource)) {
|
|
160
|
-
throw this.sourcePathError(label, resolvedSource, `the real path ${realSource} is outside ${realRoot}`);
|
|
161
|
-
}
|
|
162
|
-
const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
|
|
163
|
-
let handle;
|
|
164
|
-
try {
|
|
165
|
-
handle = await open(resolvedSource, constants.O_RDONLY | noFollow);
|
|
166
|
-
}
|
|
167
|
-
catch (error) {
|
|
168
|
-
if (errorCode(error) === "ELOOP") {
|
|
169
|
-
throw this.sourcePathError(label, resolvedSource, "the final path became a symbolic link while it was being opened");
|
|
170
|
-
}
|
|
171
|
-
throw error;
|
|
172
|
-
}
|
|
173
|
-
try {
|
|
174
|
-
const openedStat = await handle.stat();
|
|
175
|
-
if (!openedStat.isFile()) {
|
|
176
|
-
throw this.sourcePathError(label, resolvedSource, "the opened source is not a regular file");
|
|
177
|
-
}
|
|
178
|
-
let currentStat;
|
|
179
|
-
let currentRealSource;
|
|
180
|
-
let currentRealStat;
|
|
181
|
-
try {
|
|
182
|
-
currentStat = await fs.lstat(resolvedSource);
|
|
183
|
-
currentRealSource = await fs.realpath(resolvedSource);
|
|
184
|
-
currentRealStat = await fs.lstat(currentRealSource);
|
|
185
|
-
}
|
|
186
|
-
catch {
|
|
187
|
-
throw this.sourcePathError(label, resolvedSource, "the path changed while it was being opened");
|
|
188
|
-
}
|
|
189
|
-
if (!isPathInside(realRoot, currentRealSource)) {
|
|
190
|
-
throw this.sourcePathError(label, resolvedSource, `the real path ${currentRealSource} is outside ${realRoot}`);
|
|
191
|
-
}
|
|
192
|
-
if (currentStat.isSymbolicLink() ||
|
|
193
|
-
!currentStat.isFile() ||
|
|
194
|
-
!currentRealStat.isFile() ||
|
|
195
|
-
!sameFileIdentity(sourceStat, openedStat) ||
|
|
196
|
-
!sameFileIdentity(openedStat, currentStat) ||
|
|
197
|
-
!sameFileIdentity(openedStat, currentRealStat)) {
|
|
198
|
-
throw this.sourcePathError(label, resolvedSource, "the source identity changed while it was being opened");
|
|
199
|
-
}
|
|
200
|
-
return { data: await handle.readFile(), stat: openedStat };
|
|
201
|
-
}
|
|
202
|
-
finally {
|
|
203
|
-
await handle.close();
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
96
|
async readMdxSourceFile(filePath) {
|
|
207
|
-
|
|
208
|
-
throw this.sourcePathError("documentation source", filePath, "expected an .mdx file");
|
|
209
|
-
}
|
|
210
|
-
const { data, stat } = await this.readSafeSourceFile(this.watchDir, path.resolve(this.watchDir, filePath), "documentation source", false);
|
|
211
|
-
return { content: data.toString("utf8"), stat };
|
|
97
|
+
return this.sourceFs.readMdxSourceFile(filePath);
|
|
212
98
|
}
|
|
213
99
|
async ensureSafeStarterPath(relativePath) {
|
|
214
|
-
|
|
215
|
-
const targetPath = path.resolve(resolvedRoot, relativePath);
|
|
216
|
-
if (!isPathInside(resolvedRoot, targetPath)) {
|
|
217
|
-
throw this.sourcePathError("documentation source", targetPath, `the starter path is outside ${resolvedRoot}`);
|
|
218
|
-
}
|
|
219
|
-
const realRoot = await this.realSourceRoot(resolvedRoot, "documentation source", false);
|
|
220
|
-
const parentRelativePath = path.relative(resolvedRoot, path.dirname(targetPath));
|
|
221
|
-
let currentPath = resolvedRoot;
|
|
222
|
-
for (const component of parentRelativePath
|
|
223
|
-
.split(path.sep)
|
|
224
|
-
.filter(Boolean)) {
|
|
225
|
-
currentPath = path.join(currentPath, component);
|
|
226
|
-
try {
|
|
227
|
-
await fs.mkdir(currentPath);
|
|
228
|
-
}
|
|
229
|
-
catch (error) {
|
|
230
|
-
if (errorCode(error) !== "EEXIST")
|
|
231
|
-
throw error;
|
|
232
|
-
}
|
|
233
|
-
const stat = await fs.lstat(currentPath);
|
|
234
|
-
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
235
|
-
throw this.sourcePathError("documentation source", currentPath, "a starter directory component is not a real directory");
|
|
236
|
-
}
|
|
237
|
-
const realPath = await fs.realpath(currentPath);
|
|
238
|
-
if (!isPathInside(realRoot, realPath)) {
|
|
239
|
-
throw this.sourcePathError("documentation source", currentPath, `the real path ${realPath} is outside ${realRoot}`);
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
try {
|
|
243
|
-
const stat = await fs.lstat(targetPath);
|
|
244
|
-
const detail = stat.isSymbolicLink()
|
|
245
|
-
? "the starter file is a symbolic link"
|
|
246
|
-
: "the starter file appeared after the empty-source check";
|
|
247
|
-
throw this.sourcePathError("documentation source", targetPath, detail);
|
|
248
|
-
}
|
|
249
|
-
catch (error) {
|
|
250
|
-
if (errorCode(error) !== "ENOENT")
|
|
251
|
-
throw error;
|
|
252
|
-
}
|
|
253
|
-
return targetPath;
|
|
254
|
-
}
|
|
255
|
-
async copyRegularPublicFile(publicDir, sourcePath, destPath) {
|
|
256
|
-
const { data } = await this.readSafeSourceFile(publicDir, sourcePath, "public source", true);
|
|
257
|
-
await writeFileAtomic(destPath, data);
|
|
258
|
-
}
|
|
259
|
-
async copyRootSourceFile(sourcePath, destPath, label) {
|
|
260
|
-
const { data } = await this.readSafeSourceFile(this.rootDir, sourcePath, label, false);
|
|
261
|
-
await writeFileAtomic(destPath, data);
|
|
262
|
-
}
|
|
263
|
-
enqueueMutation(label, task) {
|
|
264
|
-
this.mutationQueue = this.mutationQueue.then(task).catch((error) => {
|
|
265
|
-
console.error(chalk.red(`❌ ${label}:`), error);
|
|
266
|
-
});
|
|
100
|
+
return this.sourceFs.ensureSafeStarterPath(relativePath);
|
|
267
101
|
}
|
|
268
102
|
async init() {
|
|
269
103
|
console.log(chalk.blue("🚀 Initializing MDX to Next.js generator..."));
|
|
@@ -298,229 +132,53 @@ export class MDXToNextJSGenerator {
|
|
|
298
132
|
// registry.
|
|
299
133
|
await this.writeApiPages();
|
|
300
134
|
await this.processAllMDXFiles();
|
|
135
|
+
await this.watchCoordinator.establishSourceSnapshot();
|
|
301
136
|
console.log(chalk.green("✅ Initial setup complete!"));
|
|
302
137
|
console.log(chalk.cyan("💡 To start the Next.js dev server:"));
|
|
303
138
|
console.log(chalk.white(` cd ${path.relative(process.cwd(), this.outputDir)}`));
|
|
304
139
|
console.log(chalk.white(" install dependencies, then run the dev script"));
|
|
305
140
|
}
|
|
306
141
|
async createNextJSStructure() {
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
await fs.remove(this.outputPath("app"));
|
|
314
|
-
// Drop files that earlier CLI versions generated but no longer exist in
|
|
315
|
-
// the template set, so upgraded projects don't keep stale copies.
|
|
316
|
-
await Promise.all(obsoleteFiles.map((file) => fs.remove(this.outputPath(file))));
|
|
317
|
-
const structure = {
|
|
318
|
-
...appStructure,
|
|
319
|
-
"next.config.ts": nextConfigTemplate(this.analyticsConfig),
|
|
320
|
-
"pnpm-workspace.yaml": pnpmWorkspaceTemplate,
|
|
321
|
-
"proxy.ts": proxyTemplate(this.analyticsConfig),
|
|
322
|
-
"analytics.json": `{}\n`,
|
|
323
|
-
"config.json": `{}\n`,
|
|
324
|
-
"links.json": `[]\n`,
|
|
325
|
-
"navigation.json": `[]\n`,
|
|
326
|
-
"sections.json": `[]\n`,
|
|
327
|
-
"theme.json": `{}\n`,
|
|
328
|
-
"app/robots.ts": robotsTemplate,
|
|
329
|
-
"app/layout.tsx": this.generateRootLayout(),
|
|
330
|
-
"app/(site)/layout.tsx": this.generateSiteLayout(),
|
|
331
|
-
};
|
|
332
|
-
for (const [filePath, content] of Object.entries(structure)) {
|
|
333
|
-
const fullPath = this.outputPath(filePath);
|
|
334
|
-
await fs.ensureDir(path.dirname(fullPath));
|
|
335
|
-
await writeFileAtomic(fullPath, String(await content));
|
|
336
|
-
}
|
|
337
|
-
await this.updateSitemap();
|
|
338
|
-
await this.updateLlmsFiles();
|
|
142
|
+
return this.appScaffolder.createNextJsStructure(this.analyticsConfig, {
|
|
143
|
+
generateRootLayout: () => this.generateRootLayout(),
|
|
144
|
+
generateSiteLayout: () => this.generateSiteLayout(),
|
|
145
|
+
updateSitemap: () => this.updateSitemap(),
|
|
146
|
+
updateLlmsFiles: () => this.updateLlmsFiles(),
|
|
147
|
+
});
|
|
339
148
|
}
|
|
340
149
|
async createStartingDocs() {
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
for (const [filePath, content] of Object.entries(startingDocsStructure)) {
|
|
346
|
-
const fullPath = await this.ensureSafeStarterPath(filePath);
|
|
347
|
-
await writeFileAtomic(fullPath, String(content));
|
|
348
|
-
}
|
|
150
|
+
return this.appScaffolder.createStartingDocs({
|
|
151
|
+
getAllMdxFiles: () => this.getAllMDXFiles(),
|
|
152
|
+
ensureSafeStarterPath: (filePath) => this.ensureSafeStarterPath(filePath),
|
|
153
|
+
});
|
|
349
154
|
}
|
|
350
155
|
async copyCustomConfigFiles() {
|
|
351
|
-
|
|
352
|
-
for (const configFile of this.configFiles) {
|
|
353
|
-
const sourcePath = path.join(this.rootDir, configFile);
|
|
354
|
-
const destPath = this.outputPath(configFile);
|
|
355
|
-
console.log(chalk.gray(` Checking ${configFile}...`));
|
|
356
|
-
if (await fs.pathExists(sourcePath)) {
|
|
357
|
-
await this.copyRootSourceFile(sourcePath, destPath, "config source");
|
|
358
|
-
console.log(chalk.green(` ✓ Copied ${configFile} to Next.js app`));
|
|
359
|
-
}
|
|
360
|
-
else {
|
|
361
|
-
console.log(chalk.gray(` ✗ ${configFile} not found, skipping`));
|
|
362
|
-
}
|
|
363
|
-
}
|
|
156
|
+
return this.projectConfigRepository.copyCustomConfigFiles();
|
|
364
157
|
}
|
|
365
158
|
async copyFontConfig() {
|
|
366
|
-
|
|
367
|
-
const sourcePath = path.join(this.rootDir, this.fontConfigFile);
|
|
368
|
-
const destPath = this.outputPath(this.fontConfigFile);
|
|
369
|
-
if (await fs.pathExists(sourcePath)) {
|
|
370
|
-
await this.copyRootSourceFile(sourcePath, destPath, "font source");
|
|
371
|
-
console.log(chalk.green(` ✓ Copied ${this.fontConfigFile} to Next.js app`));
|
|
372
|
-
}
|
|
373
|
-
else {
|
|
374
|
-
console.log(chalk.gray(` ✗ ${this.fontConfigFile} not found, skipping`));
|
|
375
|
-
}
|
|
159
|
+
return this.projectConfigRepository.copyFontConfig();
|
|
376
160
|
}
|
|
377
161
|
async loadFontConfig() {
|
|
378
|
-
|
|
379
|
-
try {
|
|
380
|
-
if (await fs.pathExists(fontPath)) {
|
|
381
|
-
const fontContent = await fs.readFile(fontPath, "utf8");
|
|
382
|
-
return JSON.parse(fontContent);
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
catch (error) {
|
|
386
|
-
console.warn(chalk.yellow(`⚠️ Error reading ${this.fontConfigFile}`), error);
|
|
387
|
-
}
|
|
388
|
-
return null;
|
|
162
|
+
return this.projectConfigRepository.loadFontConfig();
|
|
389
163
|
}
|
|
390
164
|
async loadAnalyticsConfig() {
|
|
391
|
-
|
|
392
|
-
try {
|
|
393
|
-
if (await fs.pathExists(analyticsPath)) {
|
|
394
|
-
const content = await fs.readFile(analyticsPath, "utf8");
|
|
395
|
-
const parsed = JSON.parse(content);
|
|
396
|
-
if (parsed?.provider === "posthog" && parsed.posthog?.key) {
|
|
397
|
-
return parsed;
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
catch (error) {
|
|
402
|
-
console.warn(chalk.yellow(`⚠️ Error reading ${this.analyticsConfigFile}`), error);
|
|
403
|
-
}
|
|
404
|
-
return null;
|
|
165
|
+
return this.projectConfigRepository.loadAnalyticsConfig();
|
|
405
166
|
}
|
|
406
167
|
async copyAnalyticsConfig() {
|
|
407
|
-
|
|
408
|
-
const sourcePath = path.join(this.rootDir, this.analyticsConfigFile);
|
|
409
|
-
const destPath = this.outputPath(this.analyticsConfigFile);
|
|
410
|
-
if (await fs.pathExists(sourcePath)) {
|
|
411
|
-
await this.copyRootSourceFile(sourcePath, destPath, "analytics source");
|
|
412
|
-
console.log(chalk.green(` ✓ Copied ${this.analyticsConfigFile} to Next.js app`));
|
|
413
|
-
}
|
|
414
|
-
else {
|
|
415
|
-
console.log(chalk.gray(` ✗ ${this.analyticsConfigFile} not found, skipping`));
|
|
416
|
-
}
|
|
168
|
+
return this.projectConfigRepository.copyAnalyticsConfig(() => this.loadAnalyticsConfig());
|
|
417
169
|
}
|
|
418
170
|
async loadSectionsConfig() {
|
|
419
|
-
|
|
420
|
-
try {
|
|
421
|
-
if (await fs.pathExists(sectionsPath)) {
|
|
422
|
-
const content = await fs.readFile(sectionsPath, "utf8");
|
|
423
|
-
const parsed = JSON.parse(content);
|
|
424
|
-
if (Array.isArray(parsed) && parsed.length > 0) {
|
|
425
|
-
const seenLabels = new Set();
|
|
426
|
-
const seenSlugs = new Set();
|
|
427
|
-
return parsed.map((entry, index) => {
|
|
428
|
-
if (!entry || typeof entry !== "object") {
|
|
429
|
-
throw new Error(`sections.json entry ${index + 1} must be an object`);
|
|
430
|
-
}
|
|
431
|
-
const candidate = entry;
|
|
432
|
-
const label = typeof candidate.label === "string" ? candidate.label.trim() : "";
|
|
433
|
-
const slug = typeof candidate.slug === "string" ? candidate.slug.trim() : "";
|
|
434
|
-
if (!label) {
|
|
435
|
-
throw new Error(`sections.json entry ${index + 1} needs a non-empty label`);
|
|
436
|
-
}
|
|
437
|
-
if (slug !== "" &&
|
|
438
|
-
(slug !== slugifySegment(slug) ||
|
|
439
|
-
slug.includes("/") ||
|
|
440
|
-
slug === "." ||
|
|
441
|
-
slug === "..")) {
|
|
442
|
-
throw new Error(`Unsafe section slug "${slug}"; use a lowercase URL segment such as "${slugifySegment(slug)}"`);
|
|
443
|
-
}
|
|
444
|
-
if (seenLabels.has(label) || seenSlugs.has(slug)) {
|
|
445
|
-
throw new Error(`Duplicate section label or slug at entry ${index + 1}`);
|
|
446
|
-
}
|
|
447
|
-
seenLabels.add(label);
|
|
448
|
-
seenSlugs.add(slug);
|
|
449
|
-
let directory;
|
|
450
|
-
if (candidate.directory !== undefined) {
|
|
451
|
-
if (typeof candidate.directory !== "string") {
|
|
452
|
-
throw new Error(`sections.json directory at entry ${index + 1} must be a string`);
|
|
453
|
-
}
|
|
454
|
-
directory = candidate.directory
|
|
455
|
-
.replace(/\\/g, "/")
|
|
456
|
-
.replace(/^\/+|\/+$/g, "");
|
|
457
|
-
const parts = directory.split("/");
|
|
458
|
-
if (!directory ||
|
|
459
|
-
parts.some((part) => part === "." ||
|
|
460
|
-
part === ".." ||
|
|
461
|
-
part !== slugifySegment(part))) {
|
|
462
|
-
throw new Error(`Unsafe section directory "${candidate.directory}"`);
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
return { label, slug, ...(directory ? { directory } : {}) };
|
|
466
|
-
});
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
catch (error) {
|
|
471
|
-
console.warn(chalk.yellow("⚠️ Error reading sections.json"), error);
|
|
472
|
-
}
|
|
473
|
-
return null;
|
|
171
|
+
return this.projectConfigRepository.loadSectionsConfig();
|
|
474
172
|
}
|
|
475
173
|
async discoverSectionsFromFrontmatter() {
|
|
476
174
|
const files = await this.getAllMDXFiles();
|
|
477
|
-
const
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
const { data: frontmatter } = safeMatter(content, file);
|
|
483
|
-
if (typeof frontmatter.section === "string" &&
|
|
484
|
-
frontmatter.section.trim()) {
|
|
485
|
-
const label = frontmatter.section.trim();
|
|
486
|
-
const order = typeof frontmatter.sectionOrder === "number"
|
|
487
|
-
? frontmatter.sectionOrder
|
|
488
|
-
: 0;
|
|
489
|
-
const existing = sectionMap.get(label);
|
|
490
|
-
if (!existing || order < existing.order) {
|
|
491
|
-
sectionMap.set(label, { label, order });
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
else {
|
|
495
|
-
hasUnsectionedPages = true;
|
|
496
|
-
}
|
|
497
|
-
if ((file === "index.mdx" || file === "./index.mdx") &&
|
|
498
|
-
typeof frontmatter.sectionLabel === "string" &&
|
|
499
|
-
frontmatter.sectionLabel.trim()) {
|
|
500
|
-
defaultSectionLabel = frontmatter.sectionLabel.trim();
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
if (sectionMap.size === 0)
|
|
504
|
-
return null;
|
|
505
|
-
const sorted = [...sectionMap.values()].sort((a, b) => a.order - b.order);
|
|
506
|
-
const sections = [];
|
|
507
|
-
// Implicit root entry for pages without a section field
|
|
508
|
-
if (hasUnsectionedPages) {
|
|
509
|
-
sections.push({ label: defaultSectionLabel, slug: "" });
|
|
510
|
-
}
|
|
511
|
-
const usedSlugs = new Set(sections.map((section) => section.slug));
|
|
512
|
-
for (const s of sorted) {
|
|
513
|
-
const slug = slugifySegment(s.label);
|
|
514
|
-
if (usedSlugs.has(slug)) {
|
|
515
|
-
throw new Error(`Section labels resolve to the same slug "${slug}". Rename one section or define sections.json explicitly.`);
|
|
516
|
-
}
|
|
517
|
-
usedSlugs.add(slug);
|
|
518
|
-
sections.push({
|
|
519
|
-
label: s.label,
|
|
520
|
-
slug,
|
|
521
|
-
});
|
|
175
|
+
const documents = [];
|
|
176
|
+
for (const filePath of files) {
|
|
177
|
+
const { content } = await this.readMdxSourceFile(filePath);
|
|
178
|
+
const { data: frontmatter } = safeMatter(content, filePath);
|
|
179
|
+
documents.push({ filePath, frontmatter });
|
|
522
180
|
}
|
|
523
|
-
return
|
|
181
|
+
return discoverSections(documents);
|
|
524
182
|
}
|
|
525
183
|
async resolveSections() {
|
|
526
184
|
const fromFile = await this.loadSectionsConfig();
|
|
@@ -534,18 +192,7 @@ export class MDXToNextJSGenerator {
|
|
|
534
192
|
* for the existing pages so both appear in the section switcher.
|
|
535
193
|
*/
|
|
536
194
|
withApiReferenceSection(sections) {
|
|
537
|
-
|
|
538
|
-
return sections;
|
|
539
|
-
const apiSection = {
|
|
540
|
-
label: "API Reference",
|
|
541
|
-
slug: this.apiBaseSlug,
|
|
542
|
-
};
|
|
543
|
-
if (!sections || sections.length === 0) {
|
|
544
|
-
return [{ label: "Documentation", slug: "" }, apiSection];
|
|
545
|
-
}
|
|
546
|
-
if (sections.some((s) => s.slug === this.apiBaseSlug))
|
|
547
|
-
return sections;
|
|
548
|
-
return [...sections, apiSection];
|
|
195
|
+
return addApiReferenceSection(sections, !this.apiRegistry.isEmpty, this.apiBaseSlug);
|
|
549
196
|
}
|
|
550
197
|
async reloadSections() {
|
|
551
198
|
console.log(chalk.cyan("📑 Sections configuration changed"));
|
|
@@ -578,65 +225,13 @@ export class MDXToNextJSGenerator {
|
|
|
578
225
|
}
|
|
579
226
|
}
|
|
580
227
|
determineSectionForFile(filePath, frontmatter) {
|
|
581
|
-
|
|
582
|
-
return { sectionSlug: "", pageSlug: generateSlug(filePath) };
|
|
583
|
-
}
|
|
584
|
-
const normalizedPath = filePath.replace(/\\/g, "/");
|
|
585
|
-
const firstDir = normalizedPath.includes("/")
|
|
586
|
-
? normalizedPath.split("/")[0]
|
|
587
|
-
: "";
|
|
588
|
-
// Explicit directory matching (entries with a directory field)
|
|
589
|
-
for (const section of this.sectionsConfig) {
|
|
590
|
-
if (!section.directory)
|
|
591
|
-
continue;
|
|
592
|
-
const dirPrefix = section.directory + "/";
|
|
593
|
-
if (normalizedPath.startsWith(dirPrefix)) {
|
|
594
|
-
return {
|
|
595
|
-
sectionSlug: section.slug,
|
|
596
|
-
pageSlug: generateSlug(normalizedPath.slice(dirPrefix.length)),
|
|
597
|
-
};
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
// Directory matches section slug (auto-detect)
|
|
601
|
-
if (firstDir) {
|
|
602
|
-
const match = this.sectionsConfig.find((s) => s.slug === firstDir);
|
|
603
|
-
if (match) {
|
|
604
|
-
const pathForSlug = normalizedPath.slice(firstDir.length + 1);
|
|
605
|
-
return {
|
|
606
|
-
sectionSlug: match.slug,
|
|
607
|
-
pageSlug: generateSlug(pathForSlug),
|
|
608
|
-
};
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
// Frontmatter section field
|
|
612
|
-
if (frontmatter.section) {
|
|
613
|
-
const label = frontmatter.section;
|
|
614
|
-
const match = this.sectionsConfig.find((s) => s.label === label);
|
|
615
|
-
if (match) {
|
|
616
|
-
// Strip the directory if it matches the section slug
|
|
617
|
-
let pathForSlug = filePath;
|
|
618
|
-
if (firstDir && firstDir === match.slug) {
|
|
619
|
-
pathForSlug = normalizedPath.slice(firstDir.length + 1);
|
|
620
|
-
}
|
|
621
|
-
return {
|
|
622
|
-
sectionSlug: match.slug,
|
|
623
|
-
pageSlug: generateSlug(pathForSlug),
|
|
624
|
-
};
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
|
-
// No section match - page stays at root
|
|
628
|
-
return {
|
|
629
|
-
sectionSlug: "",
|
|
630
|
-
pageSlug: generateSlug(filePath),
|
|
631
|
-
};
|
|
228
|
+
return determineSectionRoute(filePath, frontmatter, this.sectionsConfig);
|
|
632
229
|
}
|
|
633
230
|
async handleConfigFileChange(filePath) {
|
|
634
231
|
const fileName = path.basename(filePath);
|
|
635
232
|
if (this.configFiles.includes(fileName)) {
|
|
636
|
-
const sourcePath = path.join(this.rootDir, fileName);
|
|
637
|
-
const destPath = this.outputPath(fileName);
|
|
638
233
|
try {
|
|
639
|
-
await this.
|
|
234
|
+
await this.projectConfigRepository.copyConfigFile(fileName);
|
|
640
235
|
console.log(chalk.green(`📋 Updated ${fileName} in Next.js app`));
|
|
641
236
|
if (fileName === "sections.json") {
|
|
642
237
|
await this.reloadSections();
|
|
@@ -655,14 +250,8 @@ export class MDXToNextJSGenerator {
|
|
|
655
250
|
async handleConfigFileDelete(filePath) {
|
|
656
251
|
const fileName = path.basename(filePath);
|
|
657
252
|
if (this.configFiles.includes(fileName)) {
|
|
658
|
-
const destPath = this.outputPath(fileName);
|
|
659
253
|
try {
|
|
660
|
-
|
|
661
|
-
"links.json",
|
|
662
|
-
"navigation.json",
|
|
663
|
-
"sections.json",
|
|
664
|
-
]);
|
|
665
|
-
await writeFileAtomic(destPath, arrayDefaults.has(fileName) ? `[]\n` : `{}\n`);
|
|
254
|
+
await this.projectConfigRepository.resetConfigFile(fileName);
|
|
666
255
|
console.log(chalk.yellow(`🗑️ Reset ${fileName} to its generated default`));
|
|
667
256
|
if (fileName === "sections.json") {
|
|
668
257
|
await this.reloadSections();
|
|
@@ -680,10 +269,8 @@ export class MDXToNextJSGenerator {
|
|
|
680
269
|
}
|
|
681
270
|
async handleFontConfigChange() {
|
|
682
271
|
console.log(chalk.cyan(`🔤 Font configuration changed`));
|
|
683
|
-
const sourcePath = path.join(this.rootDir, this.fontConfigFile);
|
|
684
|
-
const destPath = this.outputPath(this.fontConfigFile);
|
|
685
272
|
try {
|
|
686
|
-
await this.
|
|
273
|
+
await this.projectConfigRepository.copyFontConfigFile();
|
|
687
274
|
console.log(chalk.green(`📋 Updated ${this.fontConfigFile} in Next.js app`));
|
|
688
275
|
await this.updateRootLayout();
|
|
689
276
|
console.log(chalk.green(`✅ Layout updated with new font configuration`));
|
|
@@ -694,10 +281,8 @@ export class MDXToNextJSGenerator {
|
|
|
694
281
|
}
|
|
695
282
|
async handleFontConfigDelete() {
|
|
696
283
|
console.log(chalk.red(`🗑️ Font configuration deleted`));
|
|
697
|
-
const destPath = this.outputPath(this.fontConfigFile);
|
|
698
284
|
try {
|
|
699
|
-
if (await
|
|
700
|
-
await fs.remove(destPath);
|
|
285
|
+
if (await this.projectConfigRepository.removeFontConfig()) {
|
|
701
286
|
console.log(chalk.yellow(`🗑️ Removed ${this.fontConfigFile} from Next.js app`));
|
|
702
287
|
await this.updateRootLayout();
|
|
703
288
|
console.log(chalk.green(`✅ Layout updated without font configuration`));
|
|
@@ -709,12 +294,10 @@ export class MDXToNextJSGenerator {
|
|
|
709
294
|
}
|
|
710
295
|
async handleAnalyticsConfigChange() {
|
|
711
296
|
console.log(chalk.cyan(`📊 Analytics configuration changed`));
|
|
712
|
-
const sourcePath = path.join(this.rootDir, this.analyticsConfigFile);
|
|
713
|
-
const destPath = this.outputPath(this.analyticsConfigFile);
|
|
714
297
|
try {
|
|
715
|
-
await this.copyRootSourceFile(sourcePath, destPath, "analytics source");
|
|
716
|
-
console.log(chalk.green(`📋 Updated ${this.analyticsConfigFile} in Next.js app`));
|
|
717
298
|
this.analyticsConfig = await this.loadAnalyticsConfig();
|
|
299
|
+
await this.projectConfigRepository.writeAnalyticsConfig(this.analyticsConfig);
|
|
300
|
+
console.log(chalk.green(`📋 Updated ${this.analyticsConfigFile} in Next.js app`));
|
|
718
301
|
// Regenerate dynamic templates that depend on analytics config
|
|
719
302
|
await writeFileAtomic(this.outputPath("next.config.ts"), nextConfigTemplate(this.analyticsConfig));
|
|
720
303
|
await writeFileAtomic(this.outputPath("proxy.ts"), proxyTemplate(this.analyticsConfig));
|
|
@@ -730,10 +313,9 @@ export class MDXToNextJSGenerator {
|
|
|
730
313
|
}
|
|
731
314
|
async handleAnalyticsConfigDelete() {
|
|
732
315
|
console.log(chalk.red(`🗑️ Analytics configuration deleted`));
|
|
733
|
-
const destPath = this.outputPath(this.analyticsConfigFile);
|
|
734
316
|
try {
|
|
735
317
|
// Write empty analytics.json so runtime imports don't break
|
|
736
|
-
await
|
|
318
|
+
await this.projectConfigRepository.resetAnalyticsConfig();
|
|
737
319
|
this.analyticsConfig = null;
|
|
738
320
|
// Regenerate dynamic templates without analytics
|
|
739
321
|
await writeFileAtomic(this.outputPath("next.config.ts"), nextConfigTemplate(null));
|
|
@@ -746,357 +328,33 @@ export class MDXToNextJSGenerator {
|
|
|
746
328
|
}
|
|
747
329
|
}
|
|
748
330
|
async copyPublicFiles() {
|
|
749
|
-
|
|
750
|
-
console.log(chalk.blue(`🔍 Checking for public directory...`));
|
|
751
|
-
let publicStat;
|
|
752
|
-
try {
|
|
753
|
-
publicStat = await fs.lstat(publicDir);
|
|
754
|
-
}
|
|
755
|
-
catch (error) {
|
|
756
|
-
if (errorCode(error) !== "ENOENT")
|
|
757
|
-
throw error;
|
|
758
|
-
console.log(chalk.gray(` ✗ public directory not found, skipping`));
|
|
759
|
-
return;
|
|
760
|
-
}
|
|
761
|
-
if (publicStat.isSymbolicLink() || !publicStat.isDirectory()) {
|
|
762
|
-
throw this.sourcePathError("public source", publicDir, "the public source root must be a real directory");
|
|
763
|
-
}
|
|
764
|
-
const realPublicDir = await this.realSourceRoot(publicDir, "public source", true);
|
|
765
|
-
const files = [];
|
|
766
|
-
const scanDir = async (directory, relativePath = "") => {
|
|
767
|
-
const entries = await fs.readdir(directory, { withFileTypes: true });
|
|
768
|
-
for (const entry of entries) {
|
|
769
|
-
const sourcePath = path.join(directory, entry.name);
|
|
770
|
-
const entryRelativePath = path.join(relativePath, entry.name);
|
|
771
|
-
const stat = await fs.lstat(sourcePath);
|
|
772
|
-
if (stat.isSymbolicLink()) {
|
|
773
|
-
throw this.sourcePathError("public source", sourcePath, "the path is a symbolic link");
|
|
774
|
-
}
|
|
775
|
-
const realPath = await fs.realpath(sourcePath);
|
|
776
|
-
if (!isPathInside(realPublicDir, realPath)) {
|
|
777
|
-
throw this.sourcePathError("public source", sourcePath, `the real path ${realPath} is outside ${realPublicDir}`);
|
|
778
|
-
}
|
|
779
|
-
if (stat.isDirectory()) {
|
|
780
|
-
await scanDir(sourcePath, entryRelativePath);
|
|
781
|
-
}
|
|
782
|
-
else if (stat.isFile()) {
|
|
783
|
-
files.push(entryRelativePath);
|
|
784
|
-
}
|
|
785
|
-
else {
|
|
786
|
-
throw this.sourcePathError("public source", sourcePath, "expected a regular file or directory");
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
};
|
|
790
|
-
await scanDir(publicDir);
|
|
791
|
-
for (const relativePath of files) {
|
|
792
|
-
await this.copyRegularPublicFile(publicDir, path.join(publicDir, relativePath), this.publicOutputFilePath(relativePath));
|
|
793
|
-
}
|
|
794
|
-
console.log(chalk.green(` ✓ Copied public directory to Next.js app`));
|
|
331
|
+
return this.publicAssetManager.copyPublicFiles();
|
|
795
332
|
}
|
|
796
333
|
async handlePublicFileChange(filePath) {
|
|
797
|
-
|
|
798
|
-
const relativePath = path.relative(publicDir, filePath);
|
|
799
|
-
const destRelativePath = isPublicAggregate(relativePath)
|
|
800
|
-
? normalizePublicArtifactPath(relativePath)
|
|
801
|
-
: relativePath;
|
|
802
|
-
const destPath = this.publicOutputFilePath(destRelativePath);
|
|
803
|
-
try {
|
|
804
|
-
await this.copyRegularPublicFile(publicDir, filePath, destPath);
|
|
805
|
-
console.log(chalk.green(`📋 Updated public/${relativePath} in Next.js app`));
|
|
806
|
-
if (isManagedPublicArtifact(relativePath)) {
|
|
807
|
-
await this.updateLlmsFiles();
|
|
808
|
-
}
|
|
809
|
-
}
|
|
810
|
-
catch (error) {
|
|
811
|
-
console.error(chalk.red(`❌ Error copying public/${relativePath}:`), error);
|
|
812
|
-
throw error;
|
|
813
|
-
}
|
|
334
|
+
return this.publicAssetManager.handlePublicFileChange(filePath, () => this.updateLlmsFiles());
|
|
814
335
|
}
|
|
815
336
|
async handlePublicFileDelete(filePath) {
|
|
816
|
-
|
|
817
|
-
const relativePath = path.relative(publicDir, filePath);
|
|
818
|
-
const destRelativePath = isPublicAggregate(relativePath)
|
|
819
|
-
? normalizePublicArtifactPath(relativePath)
|
|
820
|
-
: relativePath;
|
|
821
|
-
const destPath = this.outputPath("public", destRelativePath);
|
|
822
|
-
try {
|
|
823
|
-
// A rapid replace can queue an unlink after the replacement already
|
|
824
|
-
// exists. Copy the current source instead of deleting its fresh mirror.
|
|
825
|
-
if (await fs.pathExists(filePath)) {
|
|
826
|
-
await this.handlePublicFileChange(filePath);
|
|
827
|
-
return;
|
|
828
|
-
}
|
|
829
|
-
if (await fs.pathExists(destPath)) {
|
|
830
|
-
await fs.remove(destPath);
|
|
831
|
-
console.log(chalk.yellow(`🗑️ Removed public/${relativePath} from Next.js app`));
|
|
832
|
-
}
|
|
833
|
-
if (isManagedPublicArtifact(relativePath)) {
|
|
834
|
-
await this.updateLlmsFiles();
|
|
835
|
-
}
|
|
836
|
-
}
|
|
837
|
-
catch (error) {
|
|
838
|
-
console.error(chalk.red(`❌ Error removing public/${relativePath}:`), error);
|
|
839
|
-
}
|
|
337
|
+
return this.publicAssetManager.handlePublicFileDelete(filePath, () => this.handlePublicFileChange(filePath), () => this.updateLlmsFiles());
|
|
840
338
|
}
|
|
841
339
|
async startWatching() {
|
|
842
|
-
|
|
843
|
-
this.watcher = chokidar.watch(this.watchDir, {
|
|
844
|
-
persistent: true,
|
|
845
|
-
ignoreInitial: true,
|
|
846
|
-
followSymlinks: false,
|
|
847
|
-
ignored: (filePath, stats) => {
|
|
848
|
-
const isFile = stats?.isFile() ?? path.extname(filePath) !== "";
|
|
849
|
-
const fileName = path.basename(filePath);
|
|
850
|
-
if (this.configFiles.includes(fileName)) {
|
|
851
|
-
return true;
|
|
852
|
-
}
|
|
853
|
-
if (isFile && !filePath.endsWith(".mdx")) {
|
|
854
|
-
return true;
|
|
855
|
-
}
|
|
856
|
-
return false;
|
|
857
|
-
},
|
|
858
|
-
});
|
|
859
|
-
this.watcher
|
|
860
|
-
.on("add", (filePath) => {
|
|
861
|
-
const relativePath = path.relative(this.watchDir, filePath);
|
|
862
|
-
this.enqueueMutation("Error processing added MDX file", () => this.handleFileChange("added", relativePath));
|
|
863
|
-
})
|
|
864
|
-
.on("change", (filePath) => {
|
|
865
|
-
const relativePath = path.relative(this.watchDir, filePath);
|
|
866
|
-
this.enqueueMutation("Error processing changed MDX file", () => this.handleFileChange("changed", relativePath));
|
|
867
|
-
})
|
|
868
|
-
.on("unlink", (filePath) => {
|
|
869
|
-
const relativePath = path.relative(this.watchDir, filePath);
|
|
870
|
-
this.enqueueMutation("Error processing deleted MDX file", () => this.handleFileDelete(relativePath));
|
|
871
|
-
})
|
|
872
|
-
.on("ready", () => {
|
|
873
|
-
console.log(chalk.green("📁 Initial scan complete. Ready for changes..."));
|
|
874
|
-
})
|
|
875
|
-
.on("error", (error) => {
|
|
876
|
-
console.error(chalk.red("❌ Watcher error:"), error);
|
|
877
|
-
});
|
|
878
|
-
const configPaths = this.configFiles.map((f) => path.join(this.rootDir, f));
|
|
879
|
-
this.configWatcher = chokidar.watch(configPaths, {
|
|
880
|
-
persistent: true,
|
|
881
|
-
ignoreInitial: true,
|
|
882
|
-
});
|
|
883
|
-
this.configWatcher
|
|
884
|
-
.on("add", (filePath) => {
|
|
885
|
-
console.log(chalk.cyan(`📝 Config file added: ${path.basename(filePath)}`));
|
|
886
|
-
this.enqueueMutation("Error applying config file", () => this.handleConfigFileChange(filePath));
|
|
887
|
-
})
|
|
888
|
-
.on("change", (filePath) => {
|
|
889
|
-
console.log(chalk.cyan(`📝 Config file changed: ${path.basename(filePath)}`));
|
|
890
|
-
this.enqueueMutation("Error applying config file", () => this.handleConfigFileChange(filePath));
|
|
891
|
-
})
|
|
892
|
-
.on("unlink", (filePath) => {
|
|
893
|
-
console.log(chalk.red(`🗑️ Config file deleted: ${path.basename(filePath)}`));
|
|
894
|
-
this.enqueueMutation("Error deleting config file", () => this.handleConfigFileDelete(filePath));
|
|
895
|
-
})
|
|
896
|
-
.on("error", (error) => {
|
|
897
|
-
console.error(chalk.red("❌ Config watcher error:"), error);
|
|
898
|
-
});
|
|
899
|
-
const fontPath = path.join(this.rootDir, this.fontConfigFile);
|
|
900
|
-
this.fontWatcher = chokidar.watch(fontPath, {
|
|
901
|
-
persistent: true,
|
|
902
|
-
ignoreInitial: true,
|
|
903
|
-
});
|
|
904
|
-
this.fontWatcher
|
|
905
|
-
.on("add", () => {
|
|
906
|
-
console.log(chalk.cyan(`🔤 Font configuration added`));
|
|
907
|
-
this.enqueueMutation("Error applying font configuration", () => this.handleFontConfigChange());
|
|
908
|
-
})
|
|
909
|
-
.on("change", () => {
|
|
910
|
-
this.enqueueMutation("Error applying font configuration", () => this.handleFontConfigChange());
|
|
911
|
-
})
|
|
912
|
-
.on("unlink", () => {
|
|
913
|
-
this.enqueueMutation("Error deleting font configuration", () => this.handleFontConfigDelete());
|
|
914
|
-
})
|
|
915
|
-
.on("error", (error) => {
|
|
916
|
-
console.error(chalk.red("❌ Font watcher error:"), error);
|
|
917
|
-
});
|
|
918
|
-
const analyticsPath = path.join(this.rootDir, this.analyticsConfigFile);
|
|
919
|
-
this.analyticsWatcher = chokidar.watch(analyticsPath, {
|
|
920
|
-
persistent: true,
|
|
921
|
-
ignoreInitial: true,
|
|
922
|
-
});
|
|
923
|
-
this.analyticsWatcher
|
|
924
|
-
.on("add", () => {
|
|
925
|
-
console.log(chalk.cyan(`📊 Analytics configuration added`));
|
|
926
|
-
this.enqueueMutation("Error applying analytics configuration", () => this.handleAnalyticsConfigChange());
|
|
927
|
-
})
|
|
928
|
-
.on("change", () => {
|
|
929
|
-
this.enqueueMutation("Error applying analytics configuration", () => this.handleAnalyticsConfigChange());
|
|
930
|
-
})
|
|
931
|
-
.on("unlink", () => {
|
|
932
|
-
this.enqueueMutation("Error deleting analytics configuration", () => this.handleAnalyticsConfigDelete());
|
|
933
|
-
})
|
|
934
|
-
.on("error", (error) => {
|
|
935
|
-
console.error(chalk.red("❌ Analytics watcher error:"), error);
|
|
936
|
-
});
|
|
937
|
-
await this.syncOpenApiSpecWatcher();
|
|
938
|
-
const doccupineConfigPath = path.join(this.rootDir, this.doccupineConfigFile);
|
|
939
|
-
this.doccupineConfigWatcher = chokidar.watch(doccupineConfigPath, {
|
|
940
|
-
persistent: true,
|
|
941
|
-
ignoreInitial: true,
|
|
942
|
-
});
|
|
943
|
-
this.doccupineConfigWatcher
|
|
944
|
-
.on("add", () => this.enqueueMutation("Error applying doccupine.json", () => this.handleDoccupineConfigChange()))
|
|
945
|
-
.on("change", () => this.enqueueMutation("Error applying doccupine.json", () => this.handleDoccupineConfigChange()))
|
|
946
|
-
.on("error", (error) => {
|
|
947
|
-
console.error(chalk.red("❌ doccupine.json watcher error:"), error);
|
|
948
|
-
});
|
|
949
|
-
const publicDir = path.join(this.rootDir, "public");
|
|
950
|
-
if (await fs.pathExists(publicDir)) {
|
|
951
|
-
this.setupPublicWatcher();
|
|
952
|
-
}
|
|
953
|
-
// Watch rootDir for public directory creation
|
|
954
|
-
this.rootDirWatcher = chokidar.watch(this.rootDir, {
|
|
955
|
-
persistent: true,
|
|
956
|
-
ignoreInitial: true,
|
|
957
|
-
depth: 0,
|
|
958
|
-
});
|
|
959
|
-
this.rootDirWatcher
|
|
960
|
-
.on("addDir", (dirPath) => {
|
|
961
|
-
if (path.basename(dirPath) === "public" &&
|
|
962
|
-
path.dirname(dirPath) === this.rootDir &&
|
|
963
|
-
!this.publicWatcher) {
|
|
964
|
-
this.enqueueMutation("Error initializing public directory", async () => {
|
|
965
|
-
console.log(chalk.cyan("📁 Public directory created"));
|
|
966
|
-
await this.copyPublicFiles();
|
|
967
|
-
this.setupPublicWatcher();
|
|
968
|
-
});
|
|
969
|
-
}
|
|
970
|
-
})
|
|
971
|
-
.on("error", (error) => {
|
|
972
|
-
console.error(chalk.red("❌ Root dir watcher error:"), error);
|
|
973
|
-
});
|
|
974
|
-
}
|
|
975
|
-
setupPublicWatcher() {
|
|
976
|
-
if (this.publicWatcher) {
|
|
977
|
-
return;
|
|
978
|
-
}
|
|
979
|
-
const publicDir = path.join(this.rootDir, "public");
|
|
980
|
-
this.publicWatcher = chokidar.watch(publicDir, {
|
|
981
|
-
persistent: true,
|
|
982
|
-
ignoreInitial: true,
|
|
983
|
-
followSymlinks: false,
|
|
984
|
-
});
|
|
985
|
-
this.publicWatcher
|
|
986
|
-
.on("add", (filePath) => {
|
|
987
|
-
console.log(chalk.cyan(`📁 Public file added: ${path.relative(publicDir, filePath)}`));
|
|
988
|
-
this.enqueueMutation("Error copying public file", () => this.handlePublicFileChange(filePath));
|
|
989
|
-
})
|
|
990
|
-
.on("change", (filePath) => {
|
|
991
|
-
console.log(chalk.cyan(`📁 Public file changed: ${path.relative(publicDir, filePath)}`));
|
|
992
|
-
this.enqueueMutation("Error copying public file", () => this.handlePublicFileChange(filePath));
|
|
993
|
-
})
|
|
994
|
-
.on("unlink", (filePath) => {
|
|
995
|
-
console.log(chalk.red(`🗑️ Public file deleted: ${path.relative(publicDir, filePath)}`));
|
|
996
|
-
this.enqueueMutation("Error deleting public file", () => this.handlePublicFileDelete(filePath));
|
|
997
|
-
})
|
|
998
|
-
.on("error", (error) => {
|
|
999
|
-
console.error(chalk.red("❌ Public watcher error:"), error);
|
|
1000
|
-
});
|
|
340
|
+
return this.watchCoordinator.startWatching();
|
|
1001
341
|
}
|
|
1002
342
|
async parseMDXFile(file) {
|
|
1003
|
-
|
|
1004
|
-
const { data: frontmatter } = safeMatter(content, file);
|
|
1005
|
-
const { sectionSlug, pageSlug } = this.determineSectionForFile(file, frontmatter);
|
|
1006
|
-
const fullSlug = getFullSlug(pageSlug, sectionSlug);
|
|
1007
|
-
let lastModified;
|
|
1008
|
-
const authoredLastModified = frontmatter.updated ?? frontmatter.date;
|
|
1009
|
-
if (authoredLastModified) {
|
|
1010
|
-
const parsed = new Date(authoredLastModified);
|
|
1011
|
-
if (!Number.isNaN(parsed.getTime())) {
|
|
1012
|
-
lastModified = parsed.toISOString();
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
if (!lastModified) {
|
|
1016
|
-
lastModified = stat.mtime.toISOString();
|
|
1017
|
-
}
|
|
1018
|
-
// A hand-written page that embeds an endpoint via `openapi:` frontmatter
|
|
1019
|
-
// gets the same method badge in the sidebar as a generated endpoint page.
|
|
1020
|
-
let httpMethod;
|
|
1021
|
-
if (frontmatter.openapi) {
|
|
1022
|
-
const op = this.apiRegistry.lookup(String(frontmatter.openapi));
|
|
1023
|
-
if (op)
|
|
1024
|
-
httpMethod = op.method.toUpperCase();
|
|
1025
|
-
}
|
|
1026
|
-
return {
|
|
1027
|
-
slug: fullSlug,
|
|
1028
|
-
title: frontmatter.title || "Untitled",
|
|
1029
|
-
description: frontmatter.description || "",
|
|
1030
|
-
date: frontmatter.date || null,
|
|
1031
|
-
category: frontmatter.category || "",
|
|
1032
|
-
path: file,
|
|
1033
|
-
categoryOrder: frontmatter.categoryOrder || 0,
|
|
1034
|
-
order: frontmatter.order || 0,
|
|
1035
|
-
section: sectionSlug,
|
|
1036
|
-
// Sidebar icons (Lucide names). Kept separate from `icon`, which is
|
|
1037
|
-
// reserved for the favicon/OG metadata. Only emitted when set so the
|
|
1038
|
-
// generated page literal stays lean.
|
|
1039
|
-
...(frontmatter.navIcon ? { navIcon: String(frontmatter.navIcon) } : {}),
|
|
1040
|
-
...(frontmatter.categoryIcon
|
|
1041
|
-
? { categoryIcon: String(frontmatter.categoryIcon) }
|
|
1042
|
-
: {}),
|
|
1043
|
-
...(httpMethod ? { httpMethod } : {}),
|
|
1044
|
-
lastModified,
|
|
1045
|
-
};
|
|
343
|
+
return parseMdxPageMeta(file, (filePath) => this.readMdxSourceFile(filePath), (filePath, frontmatter) => this.determineSectionForFile(filePath, frontmatter), (reference) => this.apiRegistry.lookup(reference)?.method);
|
|
1046
344
|
}
|
|
1047
345
|
async buildRealPagesMeta() {
|
|
1048
346
|
const files = await this.getAllMDXFiles();
|
|
1049
|
-
|
|
1050
|
-
const bySlug = new Map();
|
|
1051
|
-
for (const page of real) {
|
|
1052
|
-
const existing = bySlug.get(page.slug);
|
|
1053
|
-
if (existing) {
|
|
1054
|
-
throw new Error(`Route collision at "/${page.slug}": both "${existing}" and "${page.path}" generate the same page.`);
|
|
1055
|
-
}
|
|
1056
|
-
bySlug.set(page.slug, page.path);
|
|
1057
|
-
}
|
|
1058
|
-
return real;
|
|
347
|
+
return buildRealPageCatalog(files, (file) => this.parseMDXFile(file));
|
|
1059
348
|
}
|
|
1060
349
|
async buildAllPagesMeta() {
|
|
1061
350
|
const real = await this.buildRealPagesMeta();
|
|
1062
|
-
|
|
1063
|
-
return real;
|
|
1064
|
-
// Inject synthetic OpenAPI endpoint pages here - the single funnel every
|
|
1065
|
-
// aggregate (nav, sitemap, llms) flows through - so they cannot be dropped
|
|
1066
|
-
// by the .mdx-only disk scan. Hand-written pages win on any slug collision.
|
|
1067
|
-
const realSlugs = new Set(real.map((page) => page.slug));
|
|
1068
|
-
const synthetic = this.apiRegistry.syntheticPages().filter((page) => {
|
|
1069
|
-
if (realSlugs.has(page.slug)) {
|
|
1070
|
-
console.log(chalk.yellow(`⚠️ API page ${page.slug} is shadowed by a hand-written page; skipping`));
|
|
1071
|
-
return false;
|
|
1072
|
-
}
|
|
1073
|
-
return true;
|
|
1074
|
-
});
|
|
1075
|
-
return [...real, ...synthetic];
|
|
351
|
+
return mergePageCatalog(real, this.apiRegistry.isEmpty ? [] : this.apiRegistry.syntheticPages());
|
|
1076
352
|
}
|
|
1077
353
|
async removeOwnedRoute(slug) {
|
|
1078
|
-
|
|
1079
|
-
return;
|
|
1080
|
-
const siteDir = this.outputPath("app", "(site)");
|
|
1081
|
-
const routeDir = resolveOutputPath(siteDir, slug);
|
|
1082
|
-
await Promise.all([
|
|
1083
|
-
fs.remove(resolveOutputPath(siteDir, slug, "page.tsx")),
|
|
1084
|
-
fs.remove(resolveOutputPath(siteDir, slug, "rss.xml")),
|
|
1085
|
-
]);
|
|
1086
|
-
await this.removeEmptyDirsUpTo(routeDir, siteDir);
|
|
354
|
+
return this.generatedRouteManager.removeOwnedRoute(slug);
|
|
1087
355
|
}
|
|
1088
356
|
async removeStaleMdxRoutes(realPages) {
|
|
1089
|
-
|
|
1090
|
-
.filter((page) => page.slug !== "")
|
|
1091
|
-
.map((page) => [page.path.replace(/\\/g, "/"), page.slug]));
|
|
1092
|
-
const nextSlugs = new Set(nextBySource.values());
|
|
1093
|
-
for (const previous of this.artifacts.routesFor("mdx")) {
|
|
1094
|
-
if (nextBySource.get(previous.source) === previous.slug)
|
|
1095
|
-
continue;
|
|
1096
|
-
if (nextSlugs.has(previous.slug))
|
|
1097
|
-
continue;
|
|
1098
|
-
await this.removeOwnedRoute(previous.slug);
|
|
1099
|
-
}
|
|
357
|
+
return this.generatedRouteManager.removeStaleMdxRoutes(realPages, (slug) => this.removeOwnedRoute(slug));
|
|
1100
358
|
}
|
|
1101
359
|
/**
|
|
1102
360
|
* Writes the generated page(s) for a single MDX file: the doc page and, for a
|
|
@@ -1161,16 +419,13 @@ export class MDXToNextJSGenerator {
|
|
|
1161
419
|
// Validate the complete route set before writing this page so a collision
|
|
1162
420
|
// cannot transiently overwrite another route during watch mode.
|
|
1163
421
|
const normalizedSource = filePath.replace(/\\/g, "/");
|
|
1164
|
-
const previousSlug = this.
|
|
422
|
+
const previousSlug = this.generatedRouteManager.routeForMdxSource(normalizedSource);
|
|
1165
423
|
const realPages = await this.buildRealPagesMeta();
|
|
1166
424
|
const currentPage = realPages.find((page) => page.path.replace(/\\/g, "/") === normalizedSource);
|
|
1167
425
|
if (previousSlug && previousSlug !== currentPage?.slug)
|
|
1168
426
|
await this.removeStaleMdxRoutes(realPages);
|
|
1169
427
|
await this.writePageForFile(filePath);
|
|
1170
|
-
this.
|
|
1171
|
-
.filter((page) => page.slug !== "")
|
|
1172
|
-
.map((page) => ({ source: page.path, slug: page.slug })));
|
|
1173
|
-
await this.artifacts.save();
|
|
428
|
+
await this.generatedRouteManager.replaceMdxRoutes(realPages);
|
|
1174
429
|
if (!this.apiRegistry.isEmpty)
|
|
1175
430
|
await this.writeApiPages();
|
|
1176
431
|
const pages = await this.buildAllPagesMeta();
|
|
@@ -1190,11 +445,10 @@ export class MDXToNextJSGenerator {
|
|
|
1190
445
|
}
|
|
1191
446
|
else {
|
|
1192
447
|
const normalizedSource = filePath.replace(/\\/g, "/");
|
|
1193
|
-
const ownedSlug = this.
|
|
448
|
+
const ownedSlug = this.generatedRouteManager.routeForMdxSource(normalizedSource);
|
|
1194
449
|
if (ownedSlug)
|
|
1195
450
|
await this.removeOwnedRoute(ownedSlug);
|
|
1196
|
-
this.
|
|
1197
|
-
await this.artifacts.save();
|
|
451
|
+
await this.generatedRouteManager.removeMdxRoute(normalizedSource);
|
|
1198
452
|
}
|
|
1199
453
|
if (!this.apiRegistry.isEmpty)
|
|
1200
454
|
await this.writeApiPages();
|
|
@@ -1225,53 +479,12 @@ export class MDXToNextJSGenerator {
|
|
|
1225
479
|
console.error(chalk.red(`❌ Error processing ${file}:`), error);
|
|
1226
480
|
}
|
|
1227
481
|
}
|
|
1228
|
-
this.
|
|
1229
|
-
.filter((page) => page.slug !== "")
|
|
1230
|
-
.map((page) => ({ source: page.path, slug: page.slug })));
|
|
1231
|
-
await this.artifacts.save();
|
|
482
|
+
await this.generatedRouteManager.replaceMdxRoutes(realPages);
|
|
1232
483
|
const pages = await this.buildAllPagesMeta();
|
|
1233
484
|
await this.refreshSiteAggregates(pages);
|
|
1234
485
|
}
|
|
1235
486
|
async getAllMDXFiles() {
|
|
1236
|
-
|
|
1237
|
-
const realWatchDir = await this.realSourceRoot(this.watchDir, "documentation source", false);
|
|
1238
|
-
const scanDir = async (dir, relativePath = "") => {
|
|
1239
|
-
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
1240
|
-
for (const entry of entries) {
|
|
1241
|
-
const fullPath = path.join(dir, entry.name);
|
|
1242
|
-
const relPath = path.join(relativePath, entry.name);
|
|
1243
|
-
const stat = await fs.lstat(fullPath);
|
|
1244
|
-
if (stat.isSymbolicLink()) {
|
|
1245
|
-
let linksToDirectory = false;
|
|
1246
|
-
try {
|
|
1247
|
-
linksToDirectory = (await fs.stat(fullPath)).isDirectory();
|
|
1248
|
-
}
|
|
1249
|
-
catch (error) {
|
|
1250
|
-
if (errorCode(error) !== "ENOENT")
|
|
1251
|
-
throw error;
|
|
1252
|
-
}
|
|
1253
|
-
if (entry.name.endsWith(".mdx") || linksToDirectory) {
|
|
1254
|
-
throw this.sourcePathError("documentation source", fullPath, "the path is a symbolic link");
|
|
1255
|
-
}
|
|
1256
|
-
continue;
|
|
1257
|
-
}
|
|
1258
|
-
const realPath = await fs.realpath(fullPath);
|
|
1259
|
-
if (!isPathInside(realWatchDir, realPath)) {
|
|
1260
|
-
throw this.sourcePathError("documentation source", fullPath, `the real path ${realPath} is outside ${realWatchDir}`);
|
|
1261
|
-
}
|
|
1262
|
-
if (stat.isDirectory()) {
|
|
1263
|
-
await scanDir(fullPath, relPath);
|
|
1264
|
-
}
|
|
1265
|
-
else if (stat.isFile() && entry.name.endsWith(".mdx")) {
|
|
1266
|
-
files.push(relPath);
|
|
1267
|
-
}
|
|
1268
|
-
else if (!stat.isFile() && entry.name.endsWith(".mdx")) {
|
|
1269
|
-
throw this.sourcePathError("documentation source", fullPath, "expected a regular .mdx file");
|
|
1270
|
-
}
|
|
1271
|
-
}
|
|
1272
|
-
};
|
|
1273
|
-
await scanDir(this.watchDir);
|
|
1274
|
-
return files;
|
|
487
|
+
return this.sourceFs.getAllMdxFiles();
|
|
1275
488
|
}
|
|
1276
489
|
async generateRootLayout() {
|
|
1277
490
|
const fontConfig = await this.loadFontConfig();
|
|
@@ -1328,172 +541,27 @@ export default function SectionIndex() {
|
|
|
1328
541
|
* init() wipes app/ - so in-session tracking is enough.
|
|
1329
542
|
*/
|
|
1330
543
|
async cleanupStaleSectionIndexPages(nextSlugs) {
|
|
1331
|
-
|
|
1332
|
-
if (nextSlugs.has(stale))
|
|
1333
|
-
continue;
|
|
1334
|
-
const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", stale, "page.tsx");
|
|
1335
|
-
try {
|
|
1336
|
-
if (!(await fs.pathExists(pagePath)))
|
|
1337
|
-
continue;
|
|
1338
|
-
const content = await fs.readFile(pagePath, "utf8");
|
|
1339
|
-
if (!content.includes("function SectionIndex()"))
|
|
1340
|
-
continue;
|
|
1341
|
-
await fs.remove(pagePath);
|
|
1342
|
-
await this.removeEmptyDirsUpTo(path.dirname(pagePath), this.outputPath("app", "(site)"));
|
|
1343
|
-
console.log(chalk.blue(`🧹 Removed stale section index redirect: /${stale}`));
|
|
1344
|
-
}
|
|
1345
|
-
catch {
|
|
1346
|
-
// ignore
|
|
1347
|
-
}
|
|
1348
|
-
}
|
|
1349
|
-
this.generatedSectionIndexSlugs = nextSlugs;
|
|
544
|
+
return this.generatedRouteManager.cleanupStaleSectionIndexPages(nextSlugs, (dir, stopDir) => this.removeEmptyDirsUpTo(dir, stopDir));
|
|
1350
545
|
}
|
|
1351
546
|
/** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
|
|
1352
547
|
async removeEmptyDirsUpTo(dir, stopDir) {
|
|
1353
|
-
|
|
1354
|
-
let current = path.resolve(dir);
|
|
1355
|
-
while (current !== stop && current.startsWith(stop + path.sep)) {
|
|
1356
|
-
try {
|
|
1357
|
-
const entries = await fs.readdir(current);
|
|
1358
|
-
if (entries.length > 0)
|
|
1359
|
-
return;
|
|
1360
|
-
await fs.remove(current);
|
|
1361
|
-
}
|
|
1362
|
-
catch {
|
|
1363
|
-
return;
|
|
1364
|
-
}
|
|
1365
|
-
current = path.dirname(current);
|
|
1366
|
-
}
|
|
548
|
+
return this.generatedRouteManager.removeEmptyDirsUpTo(dir, stopDir);
|
|
1367
549
|
}
|
|
1368
550
|
async generatePageFromMDX(mdxFile, options) {
|
|
1369
|
-
const
|
|
1370
|
-
const apiOperation = options?.apiOperation;
|
|
1371
|
-
// Pages containing <Update> blocks publish a subscribable changelog: an
|
|
1372
|
-
// RSS feed at {page-url}/rss.xml. Synthetic OpenAPI pages never contain
|
|
1373
|
-
// Update blocks, so skip the parse for them.
|
|
1374
|
-
const isSynthetic = mdxFile.path.startsWith("@openapi/");
|
|
1375
|
-
const updates = isSynthetic ? [] : parseUpdateBlocks(mdxFile.content);
|
|
1376
|
-
const hasFeed = updates.length > 0;
|
|
1377
|
-
const feedPath = `/${mdxFile.slug}/rss.xml`;
|
|
1378
|
-
const metadataBlock = generateMetadataBlock({
|
|
1379
|
-
title: fm.title,
|
|
1380
|
-
titleFallback: "Generated with Doccupine",
|
|
1381
|
-
name: fm.name,
|
|
1382
|
-
titleOrder: "page-first",
|
|
1383
|
-
description: fm.description,
|
|
1384
|
-
icon: fm.icon,
|
|
1385
|
-
image: fm.image,
|
|
1386
|
-
canonicalPath: mdxFile.slug,
|
|
1387
|
-
rssPath: hasFeed ? feedPath : undefined,
|
|
1388
|
-
});
|
|
1389
|
-
const jsonLd = generateJsonLdScript({
|
|
1390
|
-
kind: "article",
|
|
1391
|
-
canonicalPath: mdxFile.slug,
|
|
1392
|
-
title: fm.title,
|
|
1393
|
-
description: fm.description,
|
|
1394
|
-
date: typeof fm.date === "string" ? fm.date : undefined,
|
|
1395
|
-
updated: typeof fm.updated === "string"
|
|
1396
|
-
? fm.updated
|
|
1397
|
-
: typeof fm.date === "string"
|
|
1398
|
-
? fm.date
|
|
1399
|
-
: undefined,
|
|
1400
|
-
image: fm.image,
|
|
1401
|
-
});
|
|
1402
|
-
// For an OpenAPI-backed page, embed the operation descriptor as a JS string
|
|
1403
|
-
// literal parsed at load. Serializing to JSON then re-`JSON.parse`ing is
|
|
1404
|
-
// total escaping for arbitrary JSON - unlike `escapeTemplateContent`, which
|
|
1405
|
-
// only guards backticks/`${`/backslashes for the MDX prose literal.
|
|
1406
|
-
const apiImport = apiOperation
|
|
1407
|
-
? `\nimport { ApiPlayground } from "@/components/layout/ApiPlayground";`
|
|
1408
|
-
: "";
|
|
1409
|
-
// The descriptor JSON always exceeds the 80-col print width, so emit the
|
|
1410
|
-
// call pre-wrapped in the exact shape Prettier produces (argument on its own
|
|
1411
|
-
// line with a trailing comma, single-quoted so the JSON's own double quotes
|
|
1412
|
-
// need no escaping). Keeps generated endpoint pages Prettier-stable without
|
|
1413
|
-
// running a formatter at build time.
|
|
1414
|
-
const apiConst = apiOperation
|
|
1415
|
-
? (() => {
|
|
1416
|
-
const arg = toJsStringLiteral(JSON.stringify(apiOperation));
|
|
1417
|
-
const inline = `const operation = JSON.parse(${arg});`;
|
|
1418
|
-
const decl = inline.length <= 80
|
|
1419
|
-
? inline
|
|
1420
|
-
: `const operation = JSON.parse(\n ${arg},\n);`;
|
|
1421
|
-
return `\n${decl}\n`;
|
|
1422
|
-
})()
|
|
1423
|
-
: "";
|
|
1424
|
-
// The playground renders as a child of <Docs> so it sits inside the docs
|
|
1425
|
-
// content column (a sibling would escape the layout and overlap the nav).
|
|
1426
|
-
// Synthetic endpoint pages pass no `sourcePath`: it only namespaces Mermaid
|
|
1427
|
-
// diagrams (which endpoint docs never contain), and its long `@openapi/...`
|
|
1428
|
-
// value would push the opening tag past 80 cols and make Prettier rewrap it.
|
|
1429
|
-
const sourcePathLiteral = JSON.stringify(mdxFile.path);
|
|
1430
|
-
// `rss: true` frontmatter opts the page into an RSS button in the action
|
|
1431
|
-
// bar (only when a feed actually exists). The playground branch keeps its
|
|
1432
|
-
// fixed JSX shape - a feed on an inline-playground page stays reachable
|
|
1433
|
-
// via autodiscovery. The buttoned form usually exceeds the 80-col print
|
|
1434
|
-
// width, so pre-wrap it in the shape Prettier produces (attributes on
|
|
1435
|
-
// their own lines) relative to its 6-space insertion indent.
|
|
1436
|
-
const showRssButton = hasFeed && fm.rss === true && !apiOperation;
|
|
1437
|
-
const docsAttrs = [
|
|
1438
|
-
`content={content}`,
|
|
1439
|
-
`sourcePath={${sourcePathLiteral}}`,
|
|
1440
|
-
...(showRssButton ? [`rssHref={${JSON.stringify(feedPath)}}`] : []),
|
|
1441
|
-
];
|
|
1442
|
-
const inlineDocs = `<Docs ${docsAttrs.join(" ")} />`;
|
|
1443
|
-
const docsElement = apiOperation
|
|
1444
|
-
? `<Docs content={content}>
|
|
1445
|
-
<ApiPlayground operation={operation} />
|
|
1446
|
-
</Docs>`
|
|
1447
|
-
: inlineDocs.length + 6 <= 80
|
|
1448
|
-
? inlineDocs
|
|
1449
|
-
: `<Docs\n${docsAttrs.map((attr) => ` ${attr}`).join("\n")}\n />`;
|
|
1450
|
-
const pageContent = `import { Metadata } from "next";
|
|
1451
|
-
import { Docs } from "@/components/Docs";
|
|
1452
|
-
import { config } from "@/utils/config";${apiImport}
|
|
1453
|
-
|
|
1454
|
-
const content = \`${escapeTemplateContent(mdxFile.content)}\`;
|
|
1455
|
-
${apiConst}
|
|
1456
|
-
${metadataBlock}
|
|
1457
|
-
|
|
1458
|
-
// Doc pages have no per-request data: theme resolves client-side via the
|
|
1459
|
-
// "dark" class on <html> (set before paint by the theme-init blocking
|
|
1460
|
-
// script). Static rendering lets every response come from the edge cache.
|
|
1461
|
-
export const dynamic = "force-static";
|
|
1462
|
-
export const revalidate = false;
|
|
1463
|
-
|
|
1464
|
-
export default function Page() {
|
|
1465
|
-
${jsonLd.declarations}
|
|
1466
|
-
|
|
1467
|
-
return (
|
|
1468
|
-
<>
|
|
1469
|
-
${jsonLd.element}
|
|
1470
|
-
${docsElement}
|
|
1471
|
-
</>
|
|
1472
|
-
);
|
|
1473
|
-
}
|
|
1474
|
-
`;
|
|
551
|
+
const rendered = renderMdxPage(mdxFile, options);
|
|
1475
552
|
const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", mdxFile.slug, "page.tsx");
|
|
1476
553
|
await fs.ensureDir(path.dirname(pagePath));
|
|
1477
|
-
await writeFileAtomic(pagePath, pageContent);
|
|
554
|
+
await writeFileAtomic(pagePath, rendered.pageContent);
|
|
1478
555
|
// The feed route lives inside the page's directory, so a deleted page
|
|
1479
556
|
// takes its feed along (handleFileDelete removes the whole dir) and the
|
|
1480
557
|
// else-branch prunes the route when a regenerated page no longer has
|
|
1481
558
|
// Update blocks. Cross-run staleness is covered by the app/ wipe in
|
|
1482
559
|
// createNextJSStructure.
|
|
1483
|
-
if (
|
|
560
|
+
if (rendered.rssRoute.action !== "preserve") {
|
|
1484
561
|
const rssDir = resolveOutputPath(path.dirname(pagePath), "rss.xml");
|
|
1485
|
-
if (
|
|
562
|
+
if (rendered.rssRoute.action === "write") {
|
|
1486
563
|
await fs.ensureDir(rssDir);
|
|
1487
|
-
await writeFileAtomic(resolveOutputPath(path.dirname(pagePath), "rss.xml", "route.ts"),
|
|
1488
|
-
pagePath: mdxFile.slug,
|
|
1489
|
-
title: typeof fm.title === "string" ? fm.title : null,
|
|
1490
|
-
description: typeof fm.description === "string" ? fm.description : null,
|
|
1491
|
-
items: updates.map((update) => ({
|
|
1492
|
-
title: update.label,
|
|
1493
|
-
anchor: update.anchor,
|
|
1494
|
-
description: update.description,
|
|
1495
|
-
})),
|
|
1496
|
-
}));
|
|
564
|
+
await writeFileAtomic(resolveOutputPath(path.dirname(pagePath), "rss.xml", "route.ts"), rendered.rssRoute.content);
|
|
1497
565
|
}
|
|
1498
566
|
else {
|
|
1499
567
|
await fs.remove(rssDir);
|
|
@@ -1517,82 +585,16 @@ export default function Page() {
|
|
|
1517
585
|
* pages (e.g. after the `openapi` config is removed).
|
|
1518
586
|
*/
|
|
1519
587
|
async writeApiPages() {
|
|
1520
|
-
const
|
|
1521
|
-
|
|
1522
|
-
const indexPage = this.apiRegistry
|
|
1523
|
-
.syntheticPages()
|
|
1524
|
-
.find((page) => page.slug === this.apiBaseSlug);
|
|
1525
|
-
if (indexPage && !realSlugs.has(indexPage.slug)) {
|
|
1526
|
-
try {
|
|
1527
|
-
await this.generatePageFromMDX({
|
|
1528
|
-
path: indexPage.path,
|
|
1529
|
-
content: this.apiRegistry.bodyForSlug(indexPage.slug) ?? "",
|
|
1530
|
-
frontmatter: {
|
|
1531
|
-
title: indexPage.title,
|
|
1532
|
-
description: indexPage.description,
|
|
1533
|
-
},
|
|
1534
|
-
slug: indexPage.slug,
|
|
1535
|
-
});
|
|
1536
|
-
nextRoutes.set(`@openapi/${indexPage.slug}`, indexPage.slug);
|
|
1537
|
-
}
|
|
1538
|
-
catch (error) {
|
|
1539
|
-
console.error(chalk.red(`❌ Error generating API index ${indexPage.slug}:`), error);
|
|
1540
|
-
}
|
|
1541
|
-
}
|
|
1542
|
-
for (const op of this.apiRegistry.all) {
|
|
1543
|
-
const methodUpper = op.method.toUpperCase();
|
|
1544
|
-
const mdxFile = {
|
|
1545
|
-
path: `@openapi/${op.specName}/${op.method}${op.path}`,
|
|
1546
|
-
content: buildEndpointDoc(op),
|
|
1547
|
-
frontmatter: {
|
|
1548
|
-
title: op.summary ?? `${methodUpper} ${op.path}`,
|
|
1549
|
-
description: op.summary ?? "",
|
|
1550
|
-
},
|
|
1551
|
-
slug: op.slug,
|
|
1552
|
-
};
|
|
1553
|
-
if (realSlugs.has(op.slug)) {
|
|
1554
|
-
console.log(chalk.yellow(`⚠️ API page ${op.slug} is shadowed by a hand-written page; skipping`));
|
|
1555
|
-
continue;
|
|
1556
|
-
}
|
|
1557
|
-
try {
|
|
1558
|
-
await this.generatePageFromMDX(mdxFile, { apiOperation: op });
|
|
1559
|
-
nextRoutes.set(`@openapi/${op.slug}`, op.slug);
|
|
1560
|
-
}
|
|
1561
|
-
catch (error) {
|
|
1562
|
-
console.error(chalk.red(`❌ Error generating API page ${op.slug}:`), error);
|
|
1563
|
-
}
|
|
1564
|
-
}
|
|
1565
|
-
await this.writeApiAllowlist();
|
|
1566
|
-
await this.cleanupStaleApiPages(nextRoutes, realSlugs);
|
|
1567
|
-
if (this.apiRegistry.all.length > 0) {
|
|
1568
|
-
console.log(chalk.green(`🧩 Generated ${nextRoutes.size} API reference page(s)`));
|
|
1569
|
-
}
|
|
588
|
+
const realPages = await this.buildRealPagesMeta();
|
|
589
|
+
return this.apiReferenceGenerator.writePages(this.apiRegistry, this.apiBaseSlug, realPages, (mdxFile, options) => this.generatePageFromMDX(mdxFile, options), () => this.writeApiAllowlist(), (nextRoutes, realSlugs) => this.cleanupStaleApiPages(nextRoutes, realSlugs));
|
|
1570
590
|
}
|
|
1571
591
|
/** Writes the request-execution allowlist (overwrites the shipped stub). */
|
|
1572
592
|
async writeApiAllowlist() {
|
|
1573
|
-
|
|
1574
|
-
await fs.ensureDir(path.dirname(target));
|
|
1575
|
-
await writeFileAtomic(target, `${JSON.stringify(this.apiRegistry.allowlist(), null, 2)}\n`);
|
|
593
|
+
return this.apiReferenceGenerator.writeAllowlist(this.apiRegistry);
|
|
1576
594
|
}
|
|
1577
595
|
/** Removes endpoint page directories that are no longer in the spec. */
|
|
1578
596
|
async cleanupStaleApiPages(nextRoutes, realSlugs) {
|
|
1579
|
-
|
|
1580
|
-
for (const previous of this.artifacts.routesFor("openapi")) {
|
|
1581
|
-
if (nextRoutes.has(previous.source) || nextSlugs.has(previous.slug))
|
|
1582
|
-
continue;
|
|
1583
|
-
// A hand-written page may have taken ownership of this route since the
|
|
1584
|
-
// previous OpenAPI pass. Never remove an output now claimed by MDX.
|
|
1585
|
-
if (realSlugs.has(previous.slug))
|
|
1586
|
-
continue;
|
|
1587
|
-
try {
|
|
1588
|
-
await this.removeOwnedRoute(previous.slug);
|
|
1589
|
-
}
|
|
1590
|
-
catch {
|
|
1591
|
-
// ignore
|
|
1592
|
-
}
|
|
1593
|
-
}
|
|
1594
|
-
this.artifacts.replaceRoutes("openapi", [...nextRoutes].map(([source, slug]) => ({ source, slug })));
|
|
1595
|
-
await this.artifacts.save();
|
|
597
|
+
return this.apiReferenceGenerator.cleanupStalePages(nextRoutes, realSlugs, (slug) => this.removeOwnedRoute(slug));
|
|
1596
598
|
}
|
|
1597
599
|
/**
|
|
1598
600
|
* (Re)points the spec-file watcher at the currently configured spec paths.
|
|
@@ -1600,24 +602,7 @@ export default function Page() {
|
|
|
1600
602
|
* so specs added mid-session are watched without a restart.
|
|
1601
603
|
*/
|
|
1602
604
|
async syncOpenApiSpecWatcher() {
|
|
1603
|
-
|
|
1604
|
-
await this.openApiWatcher.close();
|
|
1605
|
-
this.openApiWatcher = null;
|
|
1606
|
-
}
|
|
1607
|
-
if (this.openApiSpecs.length === 0)
|
|
1608
|
-
return;
|
|
1609
|
-
const specPaths = this.openApiSpecs.map((spec) => path.resolve(this.rootDir, spec.file));
|
|
1610
|
-
this.openApiWatcher = chokidar.watch(specPaths, {
|
|
1611
|
-
persistent: true,
|
|
1612
|
-
ignoreInitial: true,
|
|
1613
|
-
});
|
|
1614
|
-
this.openApiWatcher
|
|
1615
|
-
.on("add", () => this.enqueueMutation("Error rebuilding API reference", () => this.handleOpenApiChange()))
|
|
1616
|
-
.on("change", () => this.enqueueMutation("Error rebuilding API reference", () => this.handleOpenApiChange()))
|
|
1617
|
-
.on("unlink", () => this.enqueueMutation("Error rebuilding API reference", () => this.handleOpenApiChange()))
|
|
1618
|
-
.on("error", (error) => {
|
|
1619
|
-
console.error(chalk.red("❌ OpenAPI watcher error:"), error);
|
|
1620
|
-
});
|
|
605
|
+
return this.watchCoordinator.syncOpenApiSpecWatcher(this.openApiSpecs);
|
|
1621
606
|
}
|
|
1622
607
|
/**
|
|
1623
608
|
* Reparses the spec(s) and rewrites everything derived from them: the
|
|
@@ -1740,34 +725,6 @@ export default function Page() {
|
|
|
1740
725
|
break;
|
|
1741
726
|
}
|
|
1742
727
|
}
|
|
1743
|
-
// The homepage publishes the same subscribable changelog as any other
|
|
1744
|
-
// page (see generatePageFromMDX): <Update> blocks feed the site-root
|
|
1745
|
-
// /rss.xml, and `rss: true` frontmatter opts into the RSS button.
|
|
1746
|
-
const updates = indexMDX ? parseUpdateBlocks(indexMDX.content) : [];
|
|
1747
|
-
const hasFeed = updates.length > 0;
|
|
1748
|
-
const feedPath = "/rss.xml";
|
|
1749
|
-
const metadataBlock = indexMDX
|
|
1750
|
-
? generateMetadataBlock({
|
|
1751
|
-
title: indexMDX.title,
|
|
1752
|
-
titleFallback: "Welcome",
|
|
1753
|
-
name: indexMDX.name,
|
|
1754
|
-
titleOrder: "name-first",
|
|
1755
|
-
description: indexMDX.description || undefined,
|
|
1756
|
-
icon: indexMDX.icon,
|
|
1757
|
-
image: indexMDX.image,
|
|
1758
|
-
canonicalPath: "",
|
|
1759
|
-
rssPath: hasFeed ? feedPath : undefined,
|
|
1760
|
-
})
|
|
1761
|
-
: generateRuntimeOnlyMetadataBlock();
|
|
1762
|
-
const homeJsonLd = generateJsonLdScript({
|
|
1763
|
-
kind: "homepage",
|
|
1764
|
-
canonicalPath: "",
|
|
1765
|
-
title: indexMDX?.title,
|
|
1766
|
-
description: indexMDX?.description || undefined,
|
|
1767
|
-
date: indexMDX?.date,
|
|
1768
|
-
updated: indexMDX?.updated ?? indexMDX?.date,
|
|
1769
|
-
image: indexMDX?.image,
|
|
1770
|
-
});
|
|
1771
728
|
// The homepage supports the same `openapi: <METHOD> <path>` frontmatter as
|
|
1772
729
|
// any other page: look the operation up and embed its playground inline.
|
|
1773
730
|
let apiOperation;
|
|
@@ -1777,142 +734,28 @@ export default function Page() {
|
|
|
1777
734
|
console.error(chalk.red(`❌ openapi frontmatter "${indexMDX.openapi}" in index.mdx not found in any spec`));
|
|
1778
735
|
}
|
|
1779
736
|
}
|
|
1780
|
-
const
|
|
1781
|
-
? `\nimport { ApiPlayground } from "@/components/layout/ApiPlayground";`
|
|
1782
|
-
: "";
|
|
1783
|
-
const apiConst = apiOperation
|
|
1784
|
-
? `\nconst operation = JSON.parse(${JSON.stringify(JSON.stringify(apiOperation))});\n`
|
|
1785
|
-
: "";
|
|
1786
|
-
// Same gating as generatePageFromMDX: the playground branch keeps its
|
|
1787
|
-
// fixed JSX shape, so a feed on a playground homepage stays reachable via
|
|
1788
|
-
// autodiscovery. The buttoned inline form stays within the 80-col print
|
|
1789
|
-
// width at its 6-space insertion indent, so it is Prettier-stable as is.
|
|
1790
|
-
const showRssButton = hasFeed && indexMDX?.rss === true && !apiOperation;
|
|
1791
|
-
const docsElement = apiOperation
|
|
1792
|
-
? `<Docs content={content} sourcePath="index.mdx">
|
|
1793
|
-
<ApiPlayground operation={operation} />
|
|
1794
|
-
</Docs>`
|
|
1795
|
-
: showRssButton
|
|
1796
|
-
? `<Docs content={content} sourcePath="index.mdx" rssHref={"/rss.xml"} />`
|
|
1797
|
-
: `<Docs content={content} sourcePath="index.mdx" />`;
|
|
1798
|
-
const indexContent = `import { Metadata } from "next";
|
|
1799
|
-
import { Docs } from "@/components/Docs";
|
|
1800
|
-
import { config } from "@/utils/config";${apiImport}
|
|
1801
|
-
|
|
1802
|
-
${indexMDX ? `const content = \`${escapeTemplateContent(indexMDX.content)}\`;` : `const content = null;`}
|
|
1803
|
-
${apiConst}
|
|
1804
|
-
${metadataBlock}
|
|
1805
|
-
|
|
1806
|
-
export const dynamic = "force-static";
|
|
1807
|
-
export const revalidate = false;
|
|
1808
|
-
|
|
1809
|
-
export default function Home() {
|
|
1810
|
-
${homeJsonLd.declarations}
|
|
1811
|
-
|
|
1812
|
-
return (
|
|
1813
|
-
<>
|
|
1814
|
-
${homeJsonLd.element}
|
|
1815
|
-
${docsElement}
|
|
1816
|
-
</>
|
|
1817
|
-
);
|
|
1818
|
-
}
|
|
1819
|
-
`;
|
|
737
|
+
const rendered = renderHomepage(indexMDX, apiOperation);
|
|
1820
738
|
const homePath = this.outputPath("app", "(site)", "page.tsx");
|
|
1821
739
|
await fs.ensureDir(path.dirname(homePath));
|
|
1822
|
-
await writeFileAtomic(homePath,
|
|
740
|
+
await writeFileAtomic(homePath, rendered.pageContent);
|
|
1823
741
|
// Same lifecycle as the per-page feeds in generatePageFromMDX: write the
|
|
1824
742
|
// root feed route while the homepage has Update blocks, prune it when
|
|
1825
743
|
// they go away or index.mdx is deleted (this runs on every aggregate
|
|
1826
744
|
// refresh, including the delete path).
|
|
1827
745
|
const rssDir = this.outputPath("app", "(site)", "rss.xml");
|
|
1828
|
-
if (
|
|
746
|
+
if (rendered.rssRoute.action === "write") {
|
|
1829
747
|
await fs.ensureDir(rssDir);
|
|
1830
|
-
await writeFileAtomic(this.outputPath("app", "(site)", "rss.xml", "route.ts"),
|
|
1831
|
-
pagePath: "",
|
|
1832
|
-
title: indexMDX.title,
|
|
1833
|
-
description: indexMDX.description || null,
|
|
1834
|
-
items: updates.map((update) => ({
|
|
1835
|
-
title: update.label,
|
|
1836
|
-
anchor: update.anchor,
|
|
1837
|
-
description: update.description,
|
|
1838
|
-
})),
|
|
1839
|
-
}));
|
|
748
|
+
await writeFileAtomic(this.outputPath("app", "(site)", "rss.xml", "route.ts"), rendered.rssRoute.content);
|
|
1840
749
|
}
|
|
1841
750
|
else {
|
|
1842
751
|
await fs.remove(rssDir);
|
|
1843
752
|
}
|
|
1844
753
|
}
|
|
1845
754
|
async updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath) {
|
|
1846
|
-
|
|
1847
|
-
// slug (section landings compose their metadata name-first), so the RSS
|
|
1848
|
-
// state must be re-derived here or the overwrite silently drops the
|
|
1849
|
-
// button and autodiscovery - the feed route survives either way since it
|
|
1850
|
-
// lives in a sibling rss.xml/ dir.
|
|
1851
|
-
const updates = parseUpdateBlocks(mdxContent);
|
|
1852
|
-
const hasFeed = updates.length > 0;
|
|
1853
|
-
const feedPath = `/${sectionSlug}/rss.xml`;
|
|
1854
|
-
const showRssButton = hasFeed && frontmatter.rss === true;
|
|
1855
|
-
const metadataBlock = generateMetadataBlock({
|
|
1856
|
-
title: frontmatter.title,
|
|
1857
|
-
titleFallback: "Section",
|
|
1858
|
-
name: frontmatter.name,
|
|
1859
|
-
titleOrder: "name-first",
|
|
1860
|
-
description: frontmatter.description || undefined,
|
|
1861
|
-
icon: frontmatter.icon,
|
|
1862
|
-
image: frontmatter.image,
|
|
1863
|
-
canonicalPath: sectionSlug,
|
|
1864
|
-
rssPath: hasFeed ? feedPath : undefined,
|
|
1865
|
-
});
|
|
1866
|
-
const sectionJsonLd = generateJsonLdScript({
|
|
1867
|
-
kind: "article",
|
|
1868
|
-
canonicalPath: sectionSlug,
|
|
1869
|
-
title: frontmatter.title,
|
|
1870
|
-
description: frontmatter.description,
|
|
1871
|
-
date: typeof frontmatter.date === "string" ? frontmatter.date : undefined,
|
|
1872
|
-
updated: typeof frontmatter.updated === "string"
|
|
1873
|
-
? frontmatter.updated
|
|
1874
|
-
: typeof frontmatter.date === "string"
|
|
1875
|
-
? frontmatter.date
|
|
1876
|
-
: undefined,
|
|
1877
|
-
image: frontmatter.image,
|
|
1878
|
-
});
|
|
1879
|
-
// Same Prettier pre-wrap contract as generatePageFromMDX: the buttoned
|
|
1880
|
-
// form usually pushes the line past the 80-col print width, so emit it
|
|
1881
|
-
// with attributes on their own lines relative to the 6-space indent.
|
|
1882
|
-
const docsAttrs = [
|
|
1883
|
-
`content={content}`,
|
|
1884
|
-
`sourcePath={${JSON.stringify(sourcePath ?? `${sectionSlug}/index.mdx`)}}`,
|
|
1885
|
-
...(showRssButton ? [`rssHref={${JSON.stringify(feedPath)}}`] : []),
|
|
1886
|
-
];
|
|
1887
|
-
const inlineDocs = `<Docs ${docsAttrs.join(" ")} />`;
|
|
1888
|
-
const docsElement = inlineDocs.length + 6 <= 80
|
|
1889
|
-
? inlineDocs
|
|
1890
|
-
: `<Docs\n${docsAttrs.map((attr) => ` ${attr}`).join("\n")}\n />`;
|
|
1891
|
-
const indexContent = `import { Metadata } from "next";
|
|
1892
|
-
import { Docs } from "@/components/Docs";
|
|
1893
|
-
import { config } from "@/utils/config";
|
|
1894
|
-
|
|
1895
|
-
const content = \`${escapeTemplateContent(mdxContent)}\`;
|
|
1896
|
-
|
|
1897
|
-
${metadataBlock}
|
|
1898
|
-
|
|
1899
|
-
export const dynamic = "force-static";
|
|
1900
|
-
export const revalidate = false;
|
|
1901
|
-
|
|
1902
|
-
export default function Page() {
|
|
1903
|
-
${sectionJsonLd.declarations}
|
|
1904
|
-
|
|
1905
|
-
return (
|
|
1906
|
-
<>
|
|
1907
|
-
${sectionJsonLd.element}
|
|
1908
|
-
${docsElement}
|
|
1909
|
-
</>
|
|
1910
|
-
);
|
|
1911
|
-
}
|
|
1912
|
-
`;
|
|
755
|
+
const rendered = renderSectionPage(sectionSlug, frontmatter, mdxContent, sourcePath);
|
|
1913
756
|
const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", sectionSlug, "page.tsx");
|
|
1914
757
|
await fs.ensureDir(path.dirname(pagePath));
|
|
1915
|
-
await writeFileAtomic(pagePath,
|
|
758
|
+
await writeFileAtomic(pagePath, rendered.pageContent);
|
|
1916
759
|
}
|
|
1917
760
|
async updateRootLayout(pages) {
|
|
1918
761
|
await writeFileAtomic(this.outputPath("app", "layout.tsx"), await this.generateRootLayout());
|
|
@@ -1921,309 +764,18 @@ export default function Page() {
|
|
|
1921
764
|
await writeFileAtomic(siteLayoutPath, await this.generateSiteLayout(pages));
|
|
1922
765
|
}
|
|
1923
766
|
async loadSiteUrl() {
|
|
1924
|
-
|
|
1925
|
-
if (fromEnv)
|
|
1926
|
-
return fromEnv.replace(/\/$/, "");
|
|
1927
|
-
const configPath = path.join(this.rootDir, "config.json");
|
|
1928
|
-
try {
|
|
1929
|
-
if (await fs.pathExists(configPath)) {
|
|
1930
|
-
const content = await fs.readFile(configPath, "utf8");
|
|
1931
|
-
const parsed = JSON.parse(content);
|
|
1932
|
-
if (typeof parsed.url === "string" && parsed.url.trim() !== "") {
|
|
1933
|
-
return parsed.url.trim().replace(/\/$/, "");
|
|
1934
|
-
}
|
|
1935
|
-
}
|
|
1936
|
-
}
|
|
1937
|
-
catch (error) {
|
|
1938
|
-
console.warn(chalk.yellow("⚠️ Error reading config.json"), error);
|
|
1939
|
-
}
|
|
1940
|
-
return null;
|
|
1941
|
-
}
|
|
1942
|
-
buildSitemapEntries(pages) {
|
|
1943
|
-
const sectionSlugs = new Set((this.sectionsConfig || [])
|
|
1944
|
-
.map((s) => s.slug)
|
|
1945
|
-
.filter((s) => typeof s === "string" && s !== ""));
|
|
1946
|
-
const entries = pages.map((page) => {
|
|
1947
|
-
let priority = 0.5;
|
|
1948
|
-
if (page.slug === "") {
|
|
1949
|
-
priority = 1.0;
|
|
1950
|
-
}
|
|
1951
|
-
else if (sectionSlugs.has(page.slug)) {
|
|
1952
|
-
priority = 0.8;
|
|
1953
|
-
}
|
|
1954
|
-
return {
|
|
1955
|
-
slug: page.slug,
|
|
1956
|
-
lastModified: page.lastModified,
|
|
1957
|
-
changeFrequency: "weekly",
|
|
1958
|
-
priority,
|
|
1959
|
-
};
|
|
1960
|
-
});
|
|
1961
|
-
if (!entries.some((entry) => entry.slug === "")) {
|
|
1962
|
-
entries.unshift({
|
|
1963
|
-
slug: "",
|
|
1964
|
-
changeFrequency: "weekly",
|
|
1965
|
-
priority: 1.0,
|
|
1966
|
-
});
|
|
1967
|
-
}
|
|
1968
|
-
return entries;
|
|
767
|
+
return loadSiteUrlArtifact(this.rootDir);
|
|
1969
768
|
}
|
|
1970
769
|
async updateSitemap(pages) {
|
|
1971
|
-
|
|
1972
|
-
const siteUrl = await this.loadSiteUrl();
|
|
1973
|
-
const resolvedPages = pages ?? (await this.buildAllPagesMeta());
|
|
1974
|
-
const entries = this.buildSitemapEntries(resolvedPages);
|
|
1975
|
-
await writeFileAtomic(sitemapPath, sitemapTemplate(entries));
|
|
1976
|
-
console.log(chalk.green(`🗺️ Generated sitemap.ts with ${entries.length} page(s)${siteUrl ? ` using ${siteUrl}` : " (waiting for a deployment URL)"}`));
|
|
770
|
+
return writeSitemap(this.outputDir, this.sectionsConfig, async () => pages ?? (await this.buildAllPagesMeta()), () => this.loadSiteUrl());
|
|
1977
771
|
}
|
|
1978
772
|
async updateRobots() {
|
|
1979
|
-
|
|
1980
|
-
await writeFileAtomic(this.outputPath("app", "robots.ts"), robotsTemplate);
|
|
1981
|
-
console.log(chalk.green(siteUrl
|
|
1982
|
-
? `🤖 Regenerated robots.ts with sitemap link`
|
|
1983
|
-
: `🤖 Regenerated robots.ts (no sitemap link)`));
|
|
1984
|
-
}
|
|
1985
|
-
async loadSiteMetadata() {
|
|
1986
|
-
const configPath = path.join(this.rootDir, "config.json");
|
|
1987
|
-
let url = null;
|
|
1988
|
-
let name = "Documentation";
|
|
1989
|
-
let description = "";
|
|
1990
|
-
try {
|
|
1991
|
-
const fromEnv = process.env.NEXT_PUBLIC_SITE_URL?.trim();
|
|
1992
|
-
if (fromEnv)
|
|
1993
|
-
url = fromEnv.replace(/\/$/, "");
|
|
1994
|
-
if (await fs.pathExists(configPath)) {
|
|
1995
|
-
const content = await fs.readFile(configPath, "utf8");
|
|
1996
|
-
const parsed = JSON.parse(content);
|
|
1997
|
-
if (!url &&
|
|
1998
|
-
typeof parsed.url === "string" &&
|
|
1999
|
-
parsed.url.trim() !== "") {
|
|
2000
|
-
url = parsed.url.trim().replace(/\/$/, "");
|
|
2001
|
-
}
|
|
2002
|
-
if (typeof parsed.name === "string" && parsed.name.trim() !== "") {
|
|
2003
|
-
name = parsed.name.trim();
|
|
2004
|
-
}
|
|
2005
|
-
else if (typeof parsed.title === "string" &&
|
|
2006
|
-
parsed.title.trim() !== "") {
|
|
2007
|
-
name = parsed.title.trim();
|
|
2008
|
-
}
|
|
2009
|
-
if (typeof parsed.description === "string" &&
|
|
2010
|
-
parsed.description.trim() !== "") {
|
|
2011
|
-
description = parsed.description.trim();
|
|
2012
|
-
}
|
|
2013
|
-
}
|
|
2014
|
-
}
|
|
2015
|
-
catch (error) {
|
|
2016
|
-
console.warn(chalk.yellow("⚠️ Error reading config.json for llms metadata"), error);
|
|
2017
|
-
}
|
|
2018
|
-
return { url, name, description };
|
|
2019
|
-
}
|
|
2020
|
-
async readPageWithBody(page) {
|
|
2021
|
-
// Synthetic OpenAPI pages have no backing .mdx file; their markdown body
|
|
2022
|
-
// comes from the registry instead of disk.
|
|
2023
|
-
if (!page.path.endsWith(".mdx")) {
|
|
2024
|
-
return { ...page, body: this.apiRegistry.bodyForSlug(page.slug) ?? "" };
|
|
2025
|
-
}
|
|
2026
|
-
const { content: raw } = await this.readMdxSourceFile(page.path);
|
|
2027
|
-
const { content: body } = safeMatter(raw, page.path);
|
|
2028
|
-
return { ...page, body };
|
|
2029
|
-
}
|
|
2030
|
-
async findSourcePublicAsset(relativePath) {
|
|
2031
|
-
const sourcePublicDir = path.join(this.rootDir, "public");
|
|
2032
|
-
const normalized = relativePath.replace(/\\/g, "/");
|
|
2033
|
-
resolveWithin(sourcePublicDir, normalized);
|
|
2034
|
-
let rootStat;
|
|
2035
|
-
try {
|
|
2036
|
-
rootStat = await fs.lstat(sourcePublicDir);
|
|
2037
|
-
}
|
|
2038
|
-
catch (error) {
|
|
2039
|
-
if (errorCode(error) === "ENOENT")
|
|
2040
|
-
return null;
|
|
2041
|
-
throw error;
|
|
2042
|
-
}
|
|
2043
|
-
if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
|
|
2044
|
-
throw this.sourcePathError("public source", sourcePublicDir, "the public source root must be a real directory");
|
|
2045
|
-
}
|
|
2046
|
-
const realPublicDir = await this.realSourceRoot(sourcePublicDir, "public source", true);
|
|
2047
|
-
let currentPath = sourcePublicDir;
|
|
2048
|
-
const parts = normalized.split("/").filter(Boolean);
|
|
2049
|
-
for (const [index, part] of parts.entries()) {
|
|
2050
|
-
let entries;
|
|
2051
|
-
try {
|
|
2052
|
-
entries = await fs.readdir(currentPath);
|
|
2053
|
-
}
|
|
2054
|
-
catch {
|
|
2055
|
-
return null;
|
|
2056
|
-
}
|
|
2057
|
-
const actualName = entries.find((entry) => entry === part) ??
|
|
2058
|
-
entries.find((entry) => entry.toLowerCase() === part.toLowerCase());
|
|
2059
|
-
if (!actualName)
|
|
2060
|
-
return null;
|
|
2061
|
-
currentPath = path.join(currentPath, actualName);
|
|
2062
|
-
const stat = await fs.lstat(currentPath);
|
|
2063
|
-
if (stat.isSymbolicLink()) {
|
|
2064
|
-
throw this.sourcePathError("public source", currentPath, "the path is a symbolic link");
|
|
2065
|
-
}
|
|
2066
|
-
if (index < parts.length - 1 && !stat.isDirectory())
|
|
2067
|
-
return null;
|
|
2068
|
-
}
|
|
2069
|
-
const stat = await fs.lstat(currentPath);
|
|
2070
|
-
if (!stat.isFile())
|
|
2071
|
-
return null;
|
|
2072
|
-
const realPath = await fs.realpath(currentPath);
|
|
2073
|
-
if (!isPathInside(realPublicDir, realPath)) {
|
|
2074
|
-
throw this.sourcePathError("public source", currentPath, `the real path ${realPath} is outside ${realPublicDir}`);
|
|
2075
|
-
}
|
|
2076
|
-
return currentPath;
|
|
2077
|
-
}
|
|
2078
|
-
async writePublicAggregate(relativePath, content) {
|
|
2079
|
-
const sourcePath = await this.findSourcePublicAsset(relativePath);
|
|
2080
|
-
const targetPath = this.publicOutputFilePath(relativePath);
|
|
2081
|
-
if (sourcePath) {
|
|
2082
|
-
console.warn(chalk.yellow(`⚠️ Skipping generated public/${relativePath}; a project public asset owns that path`));
|
|
2083
|
-
await this.copyRegularPublicFile(path.join(this.rootDir, "public"), sourcePath, targetPath);
|
|
2084
|
-
return;
|
|
2085
|
-
}
|
|
2086
|
-
await fs.ensureDir(path.dirname(targetPath));
|
|
2087
|
-
await writeFileAtomic(targetPath, content);
|
|
773
|
+
return writeRobots(this.outputDir, () => this.loadSiteUrl());
|
|
2088
774
|
}
|
|
2089
775
|
async updateLlmsFiles(pages) {
|
|
2090
|
-
|
|
2091
|
-
await fs.ensureDir(publicDir);
|
|
2092
|
-
const { url: baseUrl, name, description } = await this.loadSiteMetadata();
|
|
2093
|
-
const resolvedPages = pages ?? (await this.buildAllPagesMeta());
|
|
2094
|
-
const pagesWithBodies = await Promise.all(resolvedPages.map((page) => this.readPageWithBody(page)));
|
|
2095
|
-
const docsContent = pagesWithBodies.map((page) => {
|
|
2096
|
-
const route = page.slug.replace(/^\/+|\/+$/g, "");
|
|
2097
|
-
const pagePath = route
|
|
2098
|
-
? `app/(site)/${route}/page.tsx`
|
|
2099
|
-
: "app/(site)/page.tsx";
|
|
2100
|
-
return {
|
|
2101
|
-
uri: `docs://${route || "/"}`,
|
|
2102
|
-
name: page.title,
|
|
2103
|
-
path: pagePath,
|
|
2104
|
-
content: page.body,
|
|
2105
|
-
};
|
|
2106
|
-
});
|
|
2107
|
-
await writeFileAtomic(this.outputPath("services", "mcp", "docs-content.json"), JSON.stringify(docsContent, null, 2) + "\n");
|
|
2108
|
-
const indexContent = llmsIndexTemplate({
|
|
2109
|
-
siteName: name,
|
|
2110
|
-
siteDescription: description,
|
|
2111
|
-
baseUrl,
|
|
2112
|
-
pages: resolvedPages,
|
|
2113
|
-
sectionsConfig: this.sectionsConfig,
|
|
2114
|
-
});
|
|
2115
|
-
const fullContent = llmsFullTemplate({
|
|
2116
|
-
siteName: name,
|
|
2117
|
-
siteDescription: description,
|
|
2118
|
-
baseUrl,
|
|
2119
|
-
pages: pagesWithBodies,
|
|
2120
|
-
sectionsConfig: this.sectionsConfig,
|
|
2121
|
-
});
|
|
2122
|
-
await this.writePublicAggregate("llms.txt", indexContent);
|
|
2123
|
-
await this.writePublicAggregate("llms-full.txt", fullContent);
|
|
2124
|
-
const skillContent = skillMdTemplate({
|
|
2125
|
-
siteName: name,
|
|
2126
|
-
siteDescription: description,
|
|
2127
|
-
baseUrl,
|
|
2128
|
-
pages: resolvedPages,
|
|
2129
|
-
sectionsConfig: this.sectionsConfig,
|
|
2130
|
-
});
|
|
2131
|
-
await this.writePublicAggregate("skill.md", skillContent);
|
|
2132
|
-
// MCP discovery manifest. Needs an absolute URL, so it only exists when
|
|
2133
|
-
// config.json declares the site url; it is pruned if the url is removed.
|
|
2134
|
-
const mcpRelativePath = ".well-known/mcp.json";
|
|
2135
|
-
const mcpJsonPath = this.publicOutputFilePath(mcpRelativePath);
|
|
2136
|
-
const sourceMcpJsonPath = await this.findSourcePublicAsset(mcpRelativePath);
|
|
2137
|
-
if (sourceMcpJsonPath) {
|
|
2138
|
-
console.warn(chalk.yellow(`⚠️ Skipping generated public/${mcpRelativePath}; a project public asset owns that path`));
|
|
2139
|
-
await this.copyRegularPublicFile(path.join(this.rootDir, "public"), sourceMcpJsonPath, mcpJsonPath);
|
|
2140
|
-
}
|
|
2141
|
-
else if (baseUrl) {
|
|
2142
|
-
const mcpJson = JSON.stringify({
|
|
2143
|
-
mcpServers: {
|
|
2144
|
-
[siteDocsSlug(name)]: {
|
|
2145
|
-
url: `${baseUrl}/api/mcp`,
|
|
2146
|
-
transport: "streamable-http",
|
|
2147
|
-
},
|
|
2148
|
-
},
|
|
2149
|
-
}, null, 2) + "\n";
|
|
2150
|
-
await fs.ensureDir(path.dirname(mcpJsonPath));
|
|
2151
|
-
await writeFileAtomic(mcpJsonPath, mcpJson);
|
|
2152
|
-
}
|
|
2153
|
-
else if (await fs.pathExists(mcpJsonPath)) {
|
|
2154
|
-
await fs.remove(mcpJsonPath);
|
|
2155
|
-
}
|
|
2156
|
-
const nextRelativePaths = new Set();
|
|
2157
|
-
await Promise.all(pagesWithBodies.map(async (page) => {
|
|
2158
|
-
const relPath = page.slug === "" ? "index.md" : `${page.slug}.md`;
|
|
2159
|
-
if (isPublicAggregate(relPath))
|
|
2160
|
-
return;
|
|
2161
|
-
const sourceAssetPath = await this.findSourcePublicAsset(relPath);
|
|
2162
|
-
if (sourceAssetPath) {
|
|
2163
|
-
console.warn(chalk.yellow(`⚠️ Skipping generated public/${relPath}; a project public asset owns that path`));
|
|
2164
|
-
const targetPath = this.publicOutputFilePath(relPath);
|
|
2165
|
-
await this.copyRegularPublicFile(path.join(this.rootDir, "public"), sourceAssetPath, targetPath);
|
|
2166
|
-
return;
|
|
2167
|
-
}
|
|
2168
|
-
const targetPath = this.publicOutputFilePath(relPath);
|
|
2169
|
-
await fs.ensureDir(path.dirname(targetPath));
|
|
2170
|
-
await writeFileAtomic(targetPath, llmsPageTemplate(page, baseUrl));
|
|
2171
|
-
nextRelativePaths.add(relPath);
|
|
2172
|
-
}));
|
|
2173
|
-
const previousRelativePaths = this.artifacts.llmsPageFiles();
|
|
2174
|
-
for (const stale of previousRelativePaths) {
|
|
2175
|
-
if (!nextRelativePaths.has(stale)) {
|
|
2176
|
-
try {
|
|
2177
|
-
if (isPublicAggregate(stale))
|
|
2178
|
-
continue;
|
|
2179
|
-
if (await this.findSourcePublicAsset(stale))
|
|
2180
|
-
continue;
|
|
2181
|
-
const stalePath = resolveOutputPath(publicDir, stale);
|
|
2182
|
-
if (await fs.pathExists(stalePath)) {
|
|
2183
|
-
await fs.remove(stalePath);
|
|
2184
|
-
}
|
|
2185
|
-
}
|
|
2186
|
-
catch {
|
|
2187
|
-
// ignore
|
|
2188
|
-
}
|
|
2189
|
-
}
|
|
2190
|
-
}
|
|
2191
|
-
this.artifacts.replaceLlmsPageFiles(nextRelativePaths);
|
|
2192
|
-
await this.artifacts.save();
|
|
2193
|
-
console.log(chalk.green(`🤖 Generated llms.txt and llms-full.txt with ${resolvedPages.length} page(s)${baseUrl ? ` using ${baseUrl}` : " (relative URLs)"}`));
|
|
776
|
+
return writeLlmsFiles(this.outputDir, this.sectionsConfig, async () => pages ?? (await this.buildAllPagesMeta()), (filePath) => this.readMdxSourceFile(filePath), (slug) => this.apiRegistry.bodyForSlug(slug), () => loadSiteMetadata(this.rootDir), this.publicAssetManager);
|
|
2194
777
|
}
|
|
2195
778
|
async stop() {
|
|
2196
|
-
|
|
2197
|
-
await this.watcher.close();
|
|
2198
|
-
console.log(chalk.yellow("👋 Stopped watching for MDX changes"));
|
|
2199
|
-
}
|
|
2200
|
-
if (this.configWatcher) {
|
|
2201
|
-
await this.configWatcher.close();
|
|
2202
|
-
console.log(chalk.yellow("👋 Stopped watching for config changes"));
|
|
2203
|
-
}
|
|
2204
|
-
if (this.fontWatcher) {
|
|
2205
|
-
await this.fontWatcher.close();
|
|
2206
|
-
console.log(chalk.yellow("👋 Stopped watching for font config changes"));
|
|
2207
|
-
}
|
|
2208
|
-
if (this.analyticsWatcher) {
|
|
2209
|
-
await this.analyticsWatcher.close();
|
|
2210
|
-
console.log(chalk.yellow("👋 Stopped watching for analytics config changes"));
|
|
2211
|
-
}
|
|
2212
|
-
if (this.openApiWatcher) {
|
|
2213
|
-
await this.openApiWatcher.close();
|
|
2214
|
-
console.log(chalk.yellow("👋 Stopped watching for OpenAPI spec changes"));
|
|
2215
|
-
}
|
|
2216
|
-
if (this.doccupineConfigWatcher) {
|
|
2217
|
-
await this.doccupineConfigWatcher.close();
|
|
2218
|
-
console.log(chalk.yellow("👋 Stopped watching for doccupine.json changes"));
|
|
2219
|
-
}
|
|
2220
|
-
if (this.publicWatcher) {
|
|
2221
|
-
await this.publicWatcher.close();
|
|
2222
|
-
console.log(chalk.yellow("👋 Stopped watching for public directory changes"));
|
|
2223
|
-
}
|
|
2224
|
-
if (this.rootDirWatcher) {
|
|
2225
|
-
await this.rootDirWatcher.close();
|
|
2226
|
-
}
|
|
2227
|
-
await this.mutationQueue;
|
|
779
|
+
return this.watchCoordinator.stop();
|
|
2228
780
|
}
|
|
2229
781
|
}
|