doccupine 0.0.143 → 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.
Files changed (48) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.d.ts +6 -0
  3. package/dist/cli.js +130 -22
  4. package/dist/generator/api-reference-generator.d.ts +20 -0
  5. package/dist/generator/api-reference-generator.js +95 -0
  6. package/dist/generator/app-scaffolder.d.ts +19 -0
  7. package/dist/generator/app-scaffolder.js +54 -0
  8. package/dist/generator/generated-route-manager.d.ts +17 -0
  9. package/dist/generator/generated-route-manager.js +91 -0
  10. package/dist/generator/page-catalog.d.ts +17 -0
  11. package/dist/generator/page-catalog.js +68 -0
  12. package/dist/generator/page-renderer.d.ts +31 -0
  13. package/dist/generator/page-renderer.js +248 -0
  14. package/dist/generator/project-config-repository.d.ts +25 -0
  15. package/dist/generator/project-config-repository.js +133 -0
  16. package/dist/generator/public-asset-manager.d.ts +20 -0
  17. package/dist/generator/public-asset-manager.js +225 -0
  18. package/dist/generator/section-resolver.d.ts +13 -0
  19. package/dist/generator/section-resolver.js +150 -0
  20. package/dist/generator/secure-source-fs.d.ts +27 -0
  21. package/dist/generator/secure-source-fs.js +361 -0
  22. package/dist/generator/site-artifacts.d.ts +22 -0
  23. package/dist/generator/site-artifacts.js +159 -0
  24. package/dist/generator/watch-coordinator.d.ts +57 -0
  25. package/dist/generator/watch-coordinator.js +438 -0
  26. package/dist/lib/generated-artifacts.d.ts +3 -0
  27. package/dist/lib/generated-artifacts.js +27 -1
  28. package/dist/lib/layout.d.ts +1 -17
  29. package/dist/lib/layout.js +5 -4
  30. package/dist/lib/project-config.d.ts +3 -0
  31. package/dist/lib/project-config.js +110 -0
  32. package/dist/lib/types.d.ts +14 -1
  33. package/dist/mdx-to-nextjs-generator.d.ts +7 -25
  34. package/dist/mdx-to-nextjs-generator.js +126 -1574
  35. package/dist/templates/app/api/rag/route.d.ts +1 -1
  36. package/dist/templates/app/api/rag/route.js +2 -1
  37. package/dist/templates/components/Chat.d.ts +1 -1
  38. package/dist/templates/components/Chat.js +2 -1
  39. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  40. package/dist/templates/components/layout/Accordion.js +2 -3
  41. package/dist/templates/mdx/space.mdx.d.ts +1 -1
  42. package/dist/templates/mdx/space.mdx.js +1 -5
  43. package/dist/templates/next.config.js +2 -2
  44. package/dist/templates/package.js +2 -2
  45. package/dist/templates/proxy.js +1 -1
  46. package/dist/templates/services/mcp/server.d.ts +1 -1
  47. package/dist/templates/services/mcp/server.js +2 -12
  48. package/package.json +2 -2
package/README.md CHANGED
@@ -21,7 +21,7 @@
21
21
 
22
22
  ## Quick Start
23
23
 
24
- Make sure you have [Node.js](https://nodejs.org) (v22+) installed.
24
+ Make sure you have [Node.js](https://nodejs.org) (v22.12.0+) installed.
25
25
 
26
26
  ```bash
27
27
  npx doccupine
package/dist/cli.d.ts CHANGED
@@ -1 +1,7 @@
1
+ import { type ChildProcess } from "child_process";
2
+ import type { EventEmitter } from "events";
3
+ export type WatchSignal = "SIGINT" | "SIGTERM";
4
+ type WatchChildProcess = EventEmitter & Pick<ChildProcess, "exitCode" | "signalCode" | "kill" | "pid">;
5
+ export declare function superviseWatchLifecycle(devServer: WatchChildProcess, stopGenerator: () => Promise<void>, signalSource?: EventEmitter): Promise<WatchSignal>;
1
6
  export declare function runCli(argv?: string[]): Promise<void>;
7
+ export {};
package/dist/cli.js CHANGED
@@ -8,6 +8,120 @@ import chalk from "chalk";
8
8
  import { ConfigManager, normalizeOpenApiConfig } from "./lib/config-manager.js";
9
9
  import { findAvailablePort, resolvePackageManager, writeFileAtomic, } from "./lib/utils.js";
10
10
  import { MDXToNextJSGenerator } from "./mdx-to-nextjs-generator.js";
11
+ const CHILD_EXIT_TIMEOUT_MS = 5_000;
12
+ const CHILD_FORCE_EXIT_TIMEOUT_MS = 1_000;
13
+ function signalChildProcessTree(child, signal) {
14
+ if (process.platform !== "win32" && child.pid !== undefined) {
15
+ try {
16
+ process.kill(-child.pid, signal);
17
+ return true;
18
+ }
19
+ catch (error) {
20
+ if (error &&
21
+ typeof error === "object" &&
22
+ "code" in error &&
23
+ error.code === "ESRCH") {
24
+ return false;
25
+ }
26
+ throw error;
27
+ }
28
+ }
29
+ return child.kill(signal);
30
+ }
31
+ function waitForChildClose(child, timeoutMs) {
32
+ if (child.exitCode !== null || child.signalCode !== null) {
33
+ return Promise.resolve(true);
34
+ }
35
+ return new Promise((resolve) => {
36
+ const done = (closed) => {
37
+ clearTimeout(timer);
38
+ child.removeListener("close", onClose);
39
+ resolve(closed);
40
+ };
41
+ const onClose = () => done(true);
42
+ const timer = setTimeout(() => done(false), timeoutMs);
43
+ timer.unref();
44
+ child.once("close", onClose);
45
+ });
46
+ }
47
+ async function terminateChildProcess(child) {
48
+ if (child.exitCode !== null || child.signalCode !== null)
49
+ return;
50
+ const closed = waitForChildClose(child, CHILD_EXIT_TIMEOUT_MS);
51
+ signalChildProcessTree(child, "SIGTERM");
52
+ if (await closed)
53
+ return;
54
+ const forceClosed = waitForChildClose(child, CHILD_FORCE_EXIT_TIMEOUT_MS);
55
+ signalChildProcessTree(child, "SIGKILL");
56
+ if (!(await forceClosed)) {
57
+ throw new Error("Next.js dev server did not terminate");
58
+ }
59
+ }
60
+ export function superviseWatchLifecycle(devServer, stopGenerator, signalSource = process) {
61
+ return new Promise((resolve, reject) => {
62
+ let finishing = false;
63
+ const removeSignalListeners = () => {
64
+ signalSource.removeListener("SIGINT", onSigint);
65
+ signalSource.removeListener("SIGTERM", onSigterm);
66
+ };
67
+ const finish = (outcome, terminateChild) => {
68
+ if (finishing)
69
+ return;
70
+ finishing = true;
71
+ removeSignalListeners();
72
+ void (async () => {
73
+ const cleanupErrors = [];
74
+ const cleanup = [stopGenerator()];
75
+ if (terminateChild)
76
+ cleanup.push(terminateChildProcess(devServer));
77
+ for (const result of await Promise.allSettled(cleanup)) {
78
+ if (result.status === "rejected")
79
+ cleanupErrors.push(result.reason);
80
+ }
81
+ if ("error" in outcome) {
82
+ if (cleanupErrors.length > 0) {
83
+ reject(new AggregateError([outcome.error, ...cleanupErrors], outcome.error.message));
84
+ }
85
+ else {
86
+ reject(outcome.error);
87
+ }
88
+ }
89
+ else if (cleanupErrors.length > 0) {
90
+ reject(new AggregateError(cleanupErrors, "Failed to shut down cleanly"));
91
+ }
92
+ else {
93
+ resolve(outcome.signal);
94
+ }
95
+ })();
96
+ };
97
+ const onError = (error) => {
98
+ finish({
99
+ error: new Error(`Error starting Next.js dev server: ${error.message}`, {
100
+ cause: error,
101
+ }),
102
+ }, false);
103
+ };
104
+ const onClose = (code, signal) => {
105
+ devServer.removeListener("error", onError);
106
+ if (finishing)
107
+ return;
108
+ const detail = code !== null
109
+ ? ` with code ${code}`
110
+ : signal
111
+ ? ` from signal ${signal}`
112
+ : "";
113
+ finish({
114
+ error: new Error(`Next.js dev server exited unexpectedly${detail}`),
115
+ }, false);
116
+ };
117
+ const onSigint = () => finish({ signal: "SIGINT" }, true);
118
+ const onSigterm = () => finish({ signal: "SIGTERM" }, true);
119
+ devServer.once("error", onError);
120
+ devServer.once("close", onClose);
121
+ signalSource.once("SIGINT", onSigint);
122
+ signalSource.once("SIGTERM", onSigterm);
123
+ });
124
+ }
11
125
  async function dependencyFingerprint(outputDir, packageManager) {
12
126
  const packageJson = await fs.readFile(path.join(outputDir, "package.json"), "utf8");
13
127
  return createHash("sha256")
@@ -58,7 +172,6 @@ export async function runCli(argv) {
58
172
  // Config paths are project-relative; child processes get an absolute cwd.
59
173
  const outputDir = path.resolve(process.cwd(), config.outputDir);
60
174
  await generator.init();
61
- let devServer = null;
62
175
  // Prefer pnpm (the generated app ships a pnpm workspace) and fall back to
63
176
  // npm. A --package-manager flag or a "packageManager" field in
64
177
  // doccupine.json overrides detection; the flag wins.
@@ -96,14 +209,23 @@ export async function runCli(argv) {
96
209
  console.log(chalk.yellow(`⚠️ Port ${config.port} is in use, using port ${port} instead`));
97
210
  }
98
211
  console.log(chalk.blue(`🚀 Starting Next.js dev server on port ${port}...`));
212
+ await generator.startWatching();
99
213
  const portStr = String(port);
100
214
  const devArgs = packageManager.name === "npm"
101
215
  ? ["run", "dev", "--", "--port", portStr]
102
216
  : ["run", "dev", "--port", portStr];
103
- devServer = spawn(packageManager.bin, devArgs, {
104
- cwd: outputDir,
105
- stdio: ["ignore", "pipe", "pipe"],
106
- });
217
+ let devServer;
218
+ try {
219
+ devServer = spawn(packageManager.bin, devArgs, {
220
+ cwd: outputDir,
221
+ stdio: ["ignore", "pipe", "pipe"],
222
+ detached: process.platform !== "win32",
223
+ });
224
+ }
225
+ catch (error) {
226
+ await generator.stop();
227
+ throw error;
228
+ }
107
229
  devServer.stdout?.on("data", (data) => {
108
230
  const output = data.toString();
109
231
  if (output.includes("Ready") || output.includes("started")) {
@@ -126,25 +248,11 @@ export async function runCli(argv) {
126
248
  process.stderr.write(chalk.red("[Next.js] ") + output);
127
249
  }
128
250
  });
129
- devServer.on("error", (error) => {
130
- console.error(chalk.red("❌ Error starting dev server:"), error);
131
- });
132
- devServer.on("close", (code) => {
133
- if (code && code !== 0) {
134
- console.error(chalk.red(`❌ Next.js dev server exited with code ${code}`));
135
- }
136
- });
137
- await generator.startWatching();
138
- process.on("SIGINT", async () => {
139
- console.log(chalk.yellow("\n🛑 Shutting down..."));
140
- await generator.stop();
141
- if (devServer) {
142
- devServer.kill();
143
- }
144
- process.exit(0);
145
- });
146
251
  console.log(chalk.green("🎉 Generator is running! Press Ctrl+C to stop."));
147
252
  console.log(chalk.cyan(`📝 Edit your MDX files in: ${config.watchDir}`));
253
+ const signal = await superviseWatchLifecycle(devServer, () => generator.stop());
254
+ console.log(chalk.yellow("\n🛑 Shutting down..."));
255
+ process.exitCode = signal === "SIGINT" ? 130 : 143;
148
256
  });
149
257
  program
150
258
  .command("build")
@@ -0,0 +1,20 @@
1
+ import { GeneratedArtifacts } from "../lib/generated-artifacts.js";
2
+ import { OpenApiRegistry } from "../lib/openapi.js";
3
+ import type { OperationDescriptor } from "../lib/openapi-types.js";
4
+ import type { MDXFile, PageMeta } from "../lib/types.js";
5
+ type GeneratePage = (mdxFile: MDXFile, options?: {
6
+ apiOperation?: OperationDescriptor;
7
+ }) => Promise<void>;
8
+ type RemoveOwnedRoute = (slug: string) => Promise<void>;
9
+ type WriteAllowlist = () => Promise<void>;
10
+ type CleanupStalePages = (nextRoutes: Map<string, string>, realSlugs: Set<string>) => Promise<void>;
11
+ export declare class ApiReferenceGenerator {
12
+ private readonly outputDir;
13
+ private readonly artifacts;
14
+ constructor(outputDir: string, artifacts: GeneratedArtifacts);
15
+ mergePages(registry: OpenApiRegistry, realPages: PageMeta[]): PageMeta[];
16
+ writePages(registry: OpenApiRegistry, apiBaseSlug: string, realPages: PageMeta[], generatePage: GeneratePage, writeAllowlist: WriteAllowlist, cleanupStalePages: CleanupStalePages): Promise<void>;
17
+ writeAllowlist(registry: OpenApiRegistry): Promise<void>;
18
+ cleanupStalePages(nextRoutes: Map<string, string>, realSlugs: Set<string>, removeOwnedRoute: RemoveOwnedRoute): Promise<void>;
19
+ }
20
+ export {};
@@ -0,0 +1,95 @@
1
+ import chalk from "chalk";
2
+ import fs from "fs-extra";
3
+ import path from "node:path";
4
+ import { buildEndpointDoc } from "../lib/openapi.js";
5
+ import { resolveOutputPath } from "../lib/output-safety.js";
6
+ import { writeFileAtomic } from "../lib/utils.js";
7
+ import { mergePages as mergePageCatalog } from "./page-catalog.js";
8
+ export class ApiReferenceGenerator {
9
+ outputDir;
10
+ artifacts;
11
+ constructor(outputDir, artifacts) {
12
+ this.outputDir = outputDir;
13
+ this.artifacts = artifacts;
14
+ }
15
+ mergePages(registry, realPages) {
16
+ return mergePageCatalog(realPages, registry.isEmpty ? [] : registry.syntheticPages());
17
+ }
18
+ async writePages(registry, apiBaseSlug, realPages, generatePage, writeAllowlist, cleanupStalePages) {
19
+ const realSlugs = new Set(realPages.map((page) => page.slug));
20
+ const nextRoutes = new Map();
21
+ const indexPage = registry
22
+ .syntheticPages()
23
+ .find((page) => page.slug === apiBaseSlug);
24
+ if (indexPage && !realSlugs.has(indexPage.slug)) {
25
+ try {
26
+ await generatePage({
27
+ path: indexPage.path,
28
+ content: registry.bodyForSlug(indexPage.slug) ?? "",
29
+ frontmatter: {
30
+ title: indexPage.title,
31
+ description: indexPage.description,
32
+ },
33
+ slug: indexPage.slug,
34
+ });
35
+ nextRoutes.set(`@openapi/${indexPage.slug}`, indexPage.slug);
36
+ }
37
+ catch (error) {
38
+ console.error(chalk.red(`❌ Error generating API index ${indexPage.slug}:`), error);
39
+ }
40
+ }
41
+ for (const op of registry.all) {
42
+ const methodUpper = op.method.toUpperCase();
43
+ const mdxFile = {
44
+ path: `@openapi/${op.specName}/${op.method}${op.path}`,
45
+ content: buildEndpointDoc(op),
46
+ frontmatter: {
47
+ title: op.summary ?? `${methodUpper} ${op.path}`,
48
+ description: op.summary ?? "",
49
+ },
50
+ slug: op.slug,
51
+ };
52
+ if (realSlugs.has(op.slug)) {
53
+ console.log(chalk.yellow(`⚠️ API page ${op.slug} is shadowed by a hand-written page; skipping`));
54
+ continue;
55
+ }
56
+ try {
57
+ await generatePage(mdxFile, { apiOperation: op });
58
+ nextRoutes.set(`@openapi/${op.slug}`, op.slug);
59
+ }
60
+ catch (error) {
61
+ console.error(chalk.red(`❌ Error generating API page ${op.slug}:`), error);
62
+ }
63
+ }
64
+ await writeAllowlist();
65
+ await cleanupStalePages(nextRoutes, realSlugs);
66
+ if (registry.all.length > 0) {
67
+ console.log(chalk.green(`🧩 Generated ${nextRoutes.size} API reference page(s)`));
68
+ }
69
+ }
70
+ async writeAllowlist(registry) {
71
+ const target = resolveOutputPath(this.outputDir, "services", "openapi", "playground-allowlist.json");
72
+ await fs.ensureDir(path.dirname(target));
73
+ await writeFileAtomic(target, `${JSON.stringify(registry.allowlist(), null, 2)}\n`);
74
+ }
75
+ async cleanupStalePages(nextRoutes, realSlugs, removeOwnedRoute) {
76
+ const nextSlugs = new Set(nextRoutes.values());
77
+ for (const previous of this.artifacts.routesFor("openapi")) {
78
+ if (nextRoutes.has(previous.source) || nextSlugs.has(previous.slug)) {
79
+ continue;
80
+ }
81
+ // A hand-written page may have taken ownership of this route since the
82
+ // previous OpenAPI pass. Never remove an output now claimed by MDX.
83
+ if (realSlugs.has(previous.slug))
84
+ continue;
85
+ try {
86
+ await removeOwnedRoute(previous.slug);
87
+ }
88
+ catch {
89
+ // ignore
90
+ }
91
+ }
92
+ this.artifacts.replaceRoutes("openapi", [...nextRoutes].map(([source, slug]) => ({ source, slug })));
93
+ await this.artifacts.save();
94
+ }
95
+ }
@@ -0,0 +1,19 @@
1
+ import type { AnalyticsConfig } from "../lib/types.js";
2
+ interface AppStructureCallbacks {
3
+ generateRootLayout(): Promise<string>;
4
+ generateSiteLayout(): Promise<string>;
5
+ updateSitemap(): Promise<void>;
6
+ updateLlmsFiles(): Promise<void>;
7
+ }
8
+ interface StarterDocumentCallbacks {
9
+ getAllMdxFiles(): Promise<string[]>;
10
+ ensureSafeStarterPath(relativePath: string): Promise<string>;
11
+ }
12
+ export declare class AppScaffolder {
13
+ private readonly outputDir;
14
+ constructor(outputDir: string);
15
+ private outputPath;
16
+ createNextJsStructure(analyticsConfig: AnalyticsConfig | null, callbacks: AppStructureCallbacks): Promise<void>;
17
+ createStartingDocs(callbacks: StarterDocumentCallbacks): Promise<void>;
18
+ }
19
+ export {};
@@ -0,0 +1,54 @@
1
+ import fs from "fs-extra";
2
+ import path from "node:path";
3
+ import { appStructure, obsoleteFiles, startingDocsStructure, } from "../lib/structures.js";
4
+ import { resolveOutputPath } from "../lib/output-safety.js";
5
+ import { writeFileAtomic } from "../lib/utils.js";
6
+ import { robotsTemplate } from "../templates/app/robots.js";
7
+ import { nextConfigTemplate } from "../templates/next.config.js";
8
+ import { pnpmWorkspaceTemplate } from "../templates/pnpmWorkspace.js";
9
+ import { proxyTemplate } from "../templates/proxy.js";
10
+ export class AppScaffolder {
11
+ outputDir;
12
+ constructor(outputDir) {
13
+ this.outputDir = outputDir;
14
+ }
15
+ outputPath(...segments) {
16
+ return resolveOutputPath(this.outputDir, ...segments);
17
+ }
18
+ async createNextJsStructure(analyticsConfig, callbacks) {
19
+ // Everything under app/ is generated, so clear stale routes before writing
20
+ // the current structure. Other generated directories remain untouched.
21
+ await fs.remove(this.outputPath("app"));
22
+ await Promise.all(obsoleteFiles.map((file) => fs.remove(this.outputPath(file))));
23
+ const structure = {
24
+ ...appStructure,
25
+ "next.config.ts": nextConfigTemplate(analyticsConfig),
26
+ "pnpm-workspace.yaml": pnpmWorkspaceTemplate,
27
+ "proxy.ts": proxyTemplate(analyticsConfig),
28
+ "analytics.json": `{}\n`,
29
+ "config.json": `{}\n`,
30
+ "links.json": `[]\n`,
31
+ "navigation.json": `[]\n`,
32
+ "sections.json": `[]\n`,
33
+ "theme.json": `{}\n`,
34
+ "app/robots.ts": robotsTemplate,
35
+ "app/layout.tsx": callbacks.generateRootLayout(),
36
+ "app/(site)/layout.tsx": callbacks.generateSiteLayout(),
37
+ };
38
+ for (const [filePath, content] of Object.entries(structure)) {
39
+ const fullPath = this.outputPath(filePath);
40
+ await fs.ensureDir(path.dirname(fullPath));
41
+ await writeFileAtomic(fullPath, String(await content));
42
+ }
43
+ await callbacks.updateSitemap();
44
+ await callbacks.updateLlmsFiles();
45
+ }
46
+ async createStartingDocs(callbacks) {
47
+ if ((await callbacks.getAllMdxFiles()).length > 0)
48
+ return;
49
+ for (const [filePath, content] of Object.entries(startingDocsStructure)) {
50
+ const fullPath = await callbacks.ensureSafeStarterPath(filePath);
51
+ await writeFileAtomic(fullPath, String(content));
52
+ }
53
+ }
54
+ }
@@ -0,0 +1,17 @@
1
+ import { GeneratedArtifacts } from "../lib/generated-artifacts.js";
2
+ import type { PageMeta } from "../lib/types.js";
3
+ export declare class GeneratedRouteManager {
4
+ private readonly outputDir;
5
+ private readonly artifacts;
6
+ private generatedSectionIndexSlugs;
7
+ constructor(outputDir: string, artifacts: GeneratedArtifacts);
8
+ private outputPath;
9
+ routeForMdxSource(source: string): string | undefined;
10
+ replaceMdxRoutes(realPages: PageMeta[]): Promise<void>;
11
+ removeMdxRoute(source: string): Promise<void>;
12
+ removeOwnedRoute(slug: string): Promise<void>;
13
+ removeStaleMdxRoutes(realPages: PageMeta[], removeOwnedRoute: (slug: string) => Promise<void>): Promise<void>;
14
+ cleanupStaleSectionIndexPages(nextSlugs: Set<string>, removeEmptyDirs: (dir: string, stopDir: string) => Promise<void>): Promise<void>;
15
+ /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
16
+ removeEmptyDirsUpTo(dir: string, stopDir: string): Promise<void>;
17
+ }
@@ -0,0 +1,91 @@
1
+ import chalk from "chalk";
2
+ import fs from "fs-extra";
3
+ import path from "node:path";
4
+ import { resolveOutputPath } from "../lib/output-safety.js";
5
+ export class GeneratedRouteManager {
6
+ outputDir;
7
+ artifacts;
8
+ generatedSectionIndexSlugs = new Set();
9
+ constructor(outputDir, artifacts) {
10
+ this.outputDir = outputDir;
11
+ this.artifacts = artifacts;
12
+ }
13
+ outputPath(...segments) {
14
+ return resolveOutputPath(this.outputDir, ...segments);
15
+ }
16
+ routeForMdxSource(source) {
17
+ return this.artifacts.routeFor("mdx", source);
18
+ }
19
+ async replaceMdxRoutes(realPages) {
20
+ this.artifacts.replaceRoutes("mdx", realPages
21
+ .filter((page) => page.slug !== "")
22
+ .map((page) => ({ source: page.path, slug: page.slug })));
23
+ await this.artifacts.save();
24
+ }
25
+ async removeMdxRoute(source) {
26
+ this.artifacts.removeRoute("mdx", source);
27
+ await this.artifacts.save();
28
+ }
29
+ async removeOwnedRoute(slug) {
30
+ if (!slug)
31
+ return;
32
+ const siteDir = this.outputPath("app", "(site)");
33
+ const routeDir = resolveOutputPath(siteDir, slug);
34
+ await Promise.all([
35
+ fs.remove(resolveOutputPath(siteDir, slug, "page.tsx")),
36
+ fs.remove(resolveOutputPath(siteDir, slug, "rss.xml")),
37
+ ]);
38
+ await this.removeEmptyDirsUpTo(routeDir, siteDir);
39
+ }
40
+ async removeStaleMdxRoutes(realPages, removeOwnedRoute) {
41
+ const nextBySource = new Map(realPages
42
+ .filter((page) => page.slug !== "")
43
+ .map((page) => [page.path.replace(/\\/g, "/"), page.slug]));
44
+ const nextSlugs = new Set(nextBySource.values());
45
+ for (const previous of this.artifacts.routesFor("mdx")) {
46
+ if (nextBySource.get(previous.source) === previous.slug)
47
+ continue;
48
+ if (nextSlugs.has(previous.slug))
49
+ continue;
50
+ await removeOwnedRoute(previous.slug);
51
+ }
52
+ }
53
+ async cleanupStaleSectionIndexPages(nextSlugs, removeEmptyDirs) {
54
+ for (const stale of this.generatedSectionIndexSlugs) {
55
+ if (nextSlugs.has(stale))
56
+ continue;
57
+ const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", stale, "page.tsx");
58
+ try {
59
+ if (!(await fs.pathExists(pagePath)))
60
+ continue;
61
+ const content = await fs.readFile(pagePath, "utf8");
62
+ if (!content.includes("function SectionIndex()"))
63
+ continue;
64
+ await fs.remove(pagePath);
65
+ await removeEmptyDirs(path.dirname(pagePath), this.outputPath("app", "(site)"));
66
+ console.log(chalk.blue(`🧹 Removed stale section index redirect: /${stale}`));
67
+ }
68
+ catch {
69
+ // ignore
70
+ }
71
+ }
72
+ this.generatedSectionIndexSlugs = nextSlugs;
73
+ }
74
+ /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
75
+ async removeEmptyDirsUpTo(dir, stopDir) {
76
+ const stop = path.resolve(stopDir);
77
+ let current = path.resolve(dir);
78
+ while (current !== stop && current.startsWith(stop + path.sep)) {
79
+ try {
80
+ const entries = await fs.readdir(current);
81
+ if (entries.length > 0)
82
+ return;
83
+ await fs.remove(current);
84
+ }
85
+ catch {
86
+ return;
87
+ }
88
+ current = path.dirname(current);
89
+ }
90
+ }
91
+ }
@@ -0,0 +1,17 @@
1
+ import type { PageMeta } from "../lib/types.js";
2
+ type ReadMdxSource = (filePath: string) => Promise<{
3
+ content: string;
4
+ stat: {
5
+ mtime: Date;
6
+ };
7
+ }>;
8
+ type ResolveSectionRoute = (filePath: string, frontmatter: Record<string, any>) => {
9
+ sectionSlug: string;
10
+ pageSlug: string;
11
+ };
12
+ type ResolveHttpMethod = (reference: string) => string | undefined;
13
+ export declare function parseMdxPageMeta(filePath: string, readMdxSource: ReadMdxSource, resolveSectionRoute: ResolveSectionRoute, resolveHttpMethod: ResolveHttpMethod): Promise<PageMeta>;
14
+ export declare function validateRouteCollisions(pages: PageMeta[]): void;
15
+ export declare function buildRealPagesMeta(files: string[], parsePage: (filePath: string) => Promise<PageMeta>): Promise<PageMeta[]>;
16
+ export declare function mergePages(realPages: PageMeta[], syntheticPages: PageMeta[]): PageMeta[];
17
+ export {};
@@ -0,0 +1,68 @@
1
+ import chalk from "chalk";
2
+ import { getFullSlug, safeMatter } from "../lib/utils.js";
3
+ export async function parseMdxPageMeta(filePath, readMdxSource, resolveSectionRoute, resolveHttpMethod) {
4
+ const { content, stat } = await readMdxSource(filePath);
5
+ const { data: frontmatter } = safeMatter(content, filePath);
6
+ const { sectionSlug, pageSlug } = resolveSectionRoute(filePath, frontmatter);
7
+ const fullSlug = getFullSlug(pageSlug, sectionSlug);
8
+ let lastModified;
9
+ const authoredLastModified = frontmatter.updated ?? frontmatter.date;
10
+ if (authoredLastModified) {
11
+ const parsed = new Date(authoredLastModified);
12
+ if (!Number.isNaN(parsed.getTime())) {
13
+ lastModified = parsed.toISOString();
14
+ }
15
+ }
16
+ if (!lastModified) {
17
+ lastModified = stat.mtime.toISOString();
18
+ }
19
+ // Hand-written OpenAPI pages receive the same method badge as generated ones.
20
+ const httpMethod = frontmatter.openapi
21
+ ? resolveHttpMethod(String(frontmatter.openapi))?.toUpperCase()
22
+ : undefined;
23
+ return {
24
+ slug: fullSlug,
25
+ title: frontmatter.title || "Untitled",
26
+ description: frontmatter.description || "",
27
+ date: frontmatter.date || null,
28
+ category: frontmatter.category || "",
29
+ path: filePath,
30
+ categoryOrder: frontmatter.categoryOrder || 0,
31
+ order: frontmatter.order || 0,
32
+ section: sectionSlug,
33
+ ...(frontmatter.navIcon ? { navIcon: String(frontmatter.navIcon) } : {}),
34
+ ...(frontmatter.categoryIcon
35
+ ? { categoryIcon: String(frontmatter.categoryIcon) }
36
+ : {}),
37
+ ...(httpMethod ? { httpMethod } : {}),
38
+ lastModified,
39
+ };
40
+ }
41
+ export function validateRouteCollisions(pages) {
42
+ const bySlug = new Map();
43
+ for (const page of pages) {
44
+ const existing = bySlug.get(page.slug);
45
+ if (existing) {
46
+ throw new Error(`Route collision at "/${page.slug}": both "${existing}" and "${page.path}" generate the same page.`);
47
+ }
48
+ bySlug.set(page.slug, page.path);
49
+ }
50
+ }
51
+ export async function buildRealPagesMeta(files, parsePage) {
52
+ const pages = await Promise.all(files.map((file) => parsePage(file)));
53
+ validateRouteCollisions(pages);
54
+ return pages;
55
+ }
56
+ export function mergePages(realPages, syntheticPages) {
57
+ if (syntheticPages.length === 0)
58
+ return realPages;
59
+ const realSlugs = new Set(realPages.map((page) => page.slug));
60
+ const unshadowedSyntheticPages = syntheticPages.filter((page) => {
61
+ if (realSlugs.has(page.slug)) {
62
+ console.log(chalk.yellow(`⚠️ API page ${page.slug} is shadowed by a hand-written page; skipping`));
63
+ return false;
64
+ }
65
+ return true;
66
+ });
67
+ return [...realPages, ...unshadowedSyntheticPages];
68
+ }
@@ -0,0 +1,31 @@
1
+ import type { OperationDescriptor } from "../lib/openapi-types.js";
2
+ import type { MDXFile } from "../lib/types.js";
3
+ export type RssRouteState = {
4
+ action: "write";
5
+ content: string;
6
+ } | {
7
+ action: "remove";
8
+ } | {
9
+ action: "preserve";
10
+ };
11
+ export interface RenderedPage {
12
+ pageContent: string;
13
+ rssRoute: RssRouteState;
14
+ }
15
+ export interface HomepageSource {
16
+ content: string;
17
+ title: string;
18
+ description: string;
19
+ icon?: string;
20
+ image?: string;
21
+ name?: string;
22
+ date?: string;
23
+ updated?: string;
24
+ openapi?: string;
25
+ rss?: boolean;
26
+ }
27
+ export declare function renderMdxPage(mdxFile: MDXFile, options?: {
28
+ apiOperation?: OperationDescriptor;
29
+ }): RenderedPage;
30
+ export declare function renderHomepage(indexMDX: HomepageSource | null, apiOperation?: OperationDescriptor): RenderedPage;
31
+ export declare function renderSectionPage(sectionSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string): RenderedPage;