doccupine 0.0.145 → 0.0.146
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/dist/generator/generated-page-publisher.d.ts +21 -0
- package/dist/generator/generated-page-publisher.js +124 -0
- package/dist/generator/generated-route-manager.d.ts +3 -0
- package/dist/generator/generated-route-manager.js +21 -8
- package/dist/generator/mdx-pass-builder.d.ts +31 -0
- package/dist/generator/mdx-pass-builder.js +45 -0
- package/dist/generator/openapi-refresh-coordinator.d.ts +42 -0
- package/dist/generator/openapi-refresh-coordinator.js +211 -0
- package/dist/generator/section-index-generator.d.ts +10 -0
- package/dist/generator/section-index-generator.js +68 -0
- package/dist/generator/watch-coordinator.d.ts +8 -0
- package/dist/generator/watch-coordinator.js +128 -51
- package/dist/lib/output-safety.js +10 -3
- package/dist/mdx-to-nextjs-generator.d.ts +6 -25
- package/dist/mdx-to-nextjs-generator.js +88 -345
- package/dist/templates/utils/orderNavItems.d.ts +1 -1
- package/dist/templates/utils/orderNavItems.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { MDXFile } from "../lib/types.js";
|
|
2
|
+
import type { OperationDescriptor } from "../lib/openapi-types.js";
|
|
3
|
+
import { type HomepageSource } from "./page-renderer.js";
|
|
4
|
+
import { GeneratedRouteManager } from "./generated-route-manager.js";
|
|
5
|
+
export interface GeneratedPageCommit {
|
|
6
|
+
rollback(): Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
export declare class GeneratedPagePublisher {
|
|
9
|
+
private readonly outputDir;
|
|
10
|
+
private readonly routeManager;
|
|
11
|
+
constructor(outputDir: string, routeManager: GeneratedRouteManager);
|
|
12
|
+
private generatedFileSegments;
|
|
13
|
+
private readGeneratedFile;
|
|
14
|
+
private restoreGeneratedFile;
|
|
15
|
+
private commitRenderedPage;
|
|
16
|
+
generatePageFromMdx(mdxFile: MDXFile, options?: {
|
|
17
|
+
apiOperation?: OperationDescriptor;
|
|
18
|
+
}): Promise<GeneratedPageCommit>;
|
|
19
|
+
updateHomepage(source: HomepageSource | null, apiOperation?: OperationDescriptor): Promise<GeneratedPageCommit>;
|
|
20
|
+
updateSectionIndex(sectionSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string): Promise<GeneratedPageCommit>;
|
|
21
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import fs from "fs-extra";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { readOutputFileIfPresent, resolveOutputPath, } from "../lib/output-safety.js";
|
|
4
|
+
import { writeFileAtomic } from "../lib/utils.js";
|
|
5
|
+
import { renderHomepage, renderMdxPage, renderSectionPage, } from "./page-renderer.js";
|
|
6
|
+
export class GeneratedPagePublisher {
|
|
7
|
+
outputDir;
|
|
8
|
+
routeManager;
|
|
9
|
+
constructor(outputDir, routeManager) {
|
|
10
|
+
this.outputDir = outputDir;
|
|
11
|
+
this.routeManager = routeManager;
|
|
12
|
+
}
|
|
13
|
+
generatedFileSegments(filePath) {
|
|
14
|
+
return path
|
|
15
|
+
.relative(fs.realpathSync(this.outputDir), filePath)
|
|
16
|
+
.split(path.sep)
|
|
17
|
+
.filter(Boolean);
|
|
18
|
+
}
|
|
19
|
+
async readGeneratedFile(filePath) {
|
|
20
|
+
return readOutputFileIfPresent(this.outputDir, ...this.generatedFileSegments(filePath));
|
|
21
|
+
}
|
|
22
|
+
async restoreGeneratedFile(filePath, content) {
|
|
23
|
+
const target = resolveOutputPath(this.outputDir, ...this.generatedFileSegments(filePath));
|
|
24
|
+
if (content === null) {
|
|
25
|
+
await fs.remove(target);
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
await writeFileAtomic(target, content);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
async commitRenderedPage(pagePath, rendered) {
|
|
32
|
+
if (rendered.rssRoute.action === "preserve") {
|
|
33
|
+
const previousPage = await this.readGeneratedFile(pagePath);
|
|
34
|
+
await writeFileAtomic(pagePath, rendered.pageContent);
|
|
35
|
+
return {
|
|
36
|
+
rollback: () => this.restoreGeneratedFile(pagePath, previousPage),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const rssDir = resolveOutputPath(path.dirname(pagePath), "rss.xml");
|
|
40
|
+
const rssPath = resolveOutputPath(path.dirname(pagePath), "rss.xml", "route.ts");
|
|
41
|
+
const [previousPage, previousRss] = await Promise.all([
|
|
42
|
+
this.readGeneratedFile(pagePath),
|
|
43
|
+
this.readGeneratedFile(rssPath),
|
|
44
|
+
]);
|
|
45
|
+
let pageChanged = false;
|
|
46
|
+
let rssChanged = false;
|
|
47
|
+
try {
|
|
48
|
+
if (rendered.rssRoute.action === "write") {
|
|
49
|
+
await writeFileAtomic(rssPath, rendered.rssRoute.content);
|
|
50
|
+
rssChanged = true;
|
|
51
|
+
await writeFileAtomic(pagePath, rendered.pageContent);
|
|
52
|
+
pageChanged = true;
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
await writeFileAtomic(pagePath, rendered.pageContent);
|
|
56
|
+
pageChanged = true;
|
|
57
|
+
await fs.remove(rssPath);
|
|
58
|
+
rssChanged = true;
|
|
59
|
+
await this.routeManager.removeEmptyDirsUpTo(rssDir, path.dirname(pagePath));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
const rollbackErrors = [];
|
|
64
|
+
if (rssChanged) {
|
|
65
|
+
try {
|
|
66
|
+
await this.restoreGeneratedFile(rssPath, previousRss);
|
|
67
|
+
}
|
|
68
|
+
catch (rollbackError) {
|
|
69
|
+
rollbackErrors.push(rollbackError);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (pageChanged) {
|
|
73
|
+
try {
|
|
74
|
+
await this.restoreGeneratedFile(pagePath, previousPage);
|
|
75
|
+
}
|
|
76
|
+
catch (rollbackError) {
|
|
77
|
+
rollbackErrors.push(rollbackError);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (rollbackErrors.length > 0) {
|
|
81
|
+
throw new AggregateError([error, ...rollbackErrors], `Unable to publish or restore generated page ${pagePath}`);
|
|
82
|
+
}
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
rollback: async () => {
|
|
87
|
+
const rollbackErrors = [];
|
|
88
|
+
try {
|
|
89
|
+
await this.restoreGeneratedFile(rssPath, previousRss);
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
rollbackErrors.push(error);
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
await this.restoreGeneratedFile(pagePath, previousPage);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
rollbackErrors.push(error);
|
|
99
|
+
}
|
|
100
|
+
if (rollbackErrors.length > 0) {
|
|
101
|
+
throw new AggregateError(rollbackErrors, `Unable to restore generated page ${pagePath}`);
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
async generatePageFromMdx(mdxFile, options) {
|
|
107
|
+
const rendered = renderMdxPage(mdxFile, options);
|
|
108
|
+
const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", mdxFile.slug, "page.tsx");
|
|
109
|
+
await fs.ensureDir(path.dirname(pagePath));
|
|
110
|
+
return this.commitRenderedPage(pagePath, rendered);
|
|
111
|
+
}
|
|
112
|
+
async updateHomepage(source, apiOperation) {
|
|
113
|
+
const rendered = renderHomepage(source, apiOperation);
|
|
114
|
+
const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", "page.tsx");
|
|
115
|
+
await fs.ensureDir(path.dirname(pagePath));
|
|
116
|
+
return this.commitRenderedPage(pagePath, rendered);
|
|
117
|
+
}
|
|
118
|
+
async updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath) {
|
|
119
|
+
const rendered = renderSectionPage(sectionSlug, frontmatter, mdxContent, sourcePath);
|
|
120
|
+
const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", sectionSlug, "page.tsx");
|
|
121
|
+
await fs.ensureDir(path.dirname(pagePath));
|
|
122
|
+
return this.commitRenderedPage(pagePath, rendered);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -8,11 +8,14 @@ export declare class GeneratedRouteManager {
|
|
|
8
8
|
constructor(outputDir: string, artifacts: GeneratedArtifacts);
|
|
9
9
|
private outputPath;
|
|
10
10
|
routeForMdxSource(source: string): string | undefined;
|
|
11
|
+
sectionIndexSlugs(): Set<string>;
|
|
12
|
+
replaceSectionIndexSlugs(slugs: Iterable<string>): void;
|
|
11
13
|
replaceMdxRoutes(realPages: PageMeta[]): Promise<void>;
|
|
12
14
|
removeMdxRoute(source: string): Promise<void>;
|
|
13
15
|
removeOwnedRoute(slug: string): Promise<void>;
|
|
14
16
|
removeStaleMdxRoutes(realPages: PageMeta[], removeOwnedRoute: (slug: string) => Promise<void>, previousRoutes?: readonly RouteArtifact[]): Promise<void>;
|
|
15
17
|
cleanupStaleSectionIndexPages(nextSlugs: Set<string>, occupiedSlugs: Set<string>, removeEmptyDirs: (dir: string, stopDir: string) => Promise<void>): Promise<void>;
|
|
18
|
+
private removeSectionIndexPage;
|
|
16
19
|
/** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
|
|
17
20
|
removeEmptyDirsUpTo(dir: string, stopDir: string): Promise<void>;
|
|
18
21
|
}
|
|
@@ -17,6 +17,12 @@ export class GeneratedRouteManager {
|
|
|
17
17
|
routeForMdxSource(source) {
|
|
18
18
|
return this.artifacts.routeFor("mdx", source);
|
|
19
19
|
}
|
|
20
|
+
sectionIndexSlugs() {
|
|
21
|
+
return new Set(this.generatedSectionIndexSlugs);
|
|
22
|
+
}
|
|
23
|
+
replaceSectionIndexSlugs(slugs) {
|
|
24
|
+
this.generatedSectionIndexSlugs = new Set(slugs);
|
|
25
|
+
}
|
|
20
26
|
async replaceMdxRoutes(realPages) {
|
|
21
27
|
await this.artifacts.replaceRoutesAndSave("mdx", realPages
|
|
22
28
|
.filter((page) => page.slug !== "")
|
|
@@ -75,25 +81,32 @@ export class GeneratedRouteManager {
|
|
|
75
81
|
}
|
|
76
82
|
}
|
|
77
83
|
async cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs, removeEmptyDirs) {
|
|
84
|
+
const errors = [];
|
|
78
85
|
for (const stale of this.generatedSectionIndexSlugs) {
|
|
79
86
|
if (nextSlugs.has(stale))
|
|
80
87
|
continue;
|
|
81
88
|
if (occupiedSlugs.has(stale))
|
|
82
89
|
continue;
|
|
83
|
-
const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", stale, "page.tsx");
|
|
84
90
|
try {
|
|
85
|
-
|
|
86
|
-
continue;
|
|
87
|
-
await fs.remove(pagePath);
|
|
88
|
-
await removeEmptyDirs(path.dirname(pagePath), this.outputPath("app", "(site)"));
|
|
89
|
-
console.log(chalk.blue(`🧹 Removed stale section index redirect: /${stale}`));
|
|
91
|
+
await this.removeSectionIndexPage(stale, removeEmptyDirs);
|
|
90
92
|
}
|
|
91
|
-
catch {
|
|
92
|
-
|
|
93
|
+
catch (error) {
|
|
94
|
+
errors.push(error);
|
|
93
95
|
}
|
|
94
96
|
}
|
|
97
|
+
if (errors.length > 0) {
|
|
98
|
+
throw new AggregateError(errors, "Unable to remove stale section index redirects");
|
|
99
|
+
}
|
|
95
100
|
this.generatedSectionIndexSlugs = nextSlugs;
|
|
96
101
|
}
|
|
102
|
+
async removeSectionIndexPage(slug, removeEmptyDirs) {
|
|
103
|
+
const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", slug, "page.tsx");
|
|
104
|
+
if (!(await fs.pathExists(pagePath)))
|
|
105
|
+
return;
|
|
106
|
+
await fs.remove(pagePath);
|
|
107
|
+
await removeEmptyDirs(path.dirname(pagePath), this.outputPath("app", "(site)"));
|
|
108
|
+
console.log(chalk.blue(`🧹 Removed stale section index redirect: /${slug}`));
|
|
109
|
+
}
|
|
97
110
|
/** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
|
|
98
111
|
async removeEmptyDirsUpTo(dir, stopDir) {
|
|
99
112
|
const stop = path.resolve(stopDir);
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Stats } from "node:fs";
|
|
2
|
+
import type { PageMeta, SectionConfig } from "../lib/types.js";
|
|
3
|
+
import { SecureSourceFs } from "./secure-source-fs.js";
|
|
4
|
+
export interface MdxSourceSnapshot {
|
|
5
|
+
content: string;
|
|
6
|
+
stat: Stats;
|
|
7
|
+
}
|
|
8
|
+
export interface MdxPassSnapshot {
|
|
9
|
+
files: string[];
|
|
10
|
+
pages: PageMeta[];
|
|
11
|
+
sources: ReadonlyMap<string, MdxSourceSnapshot>;
|
|
12
|
+
sections: SectionConfig[] | null;
|
|
13
|
+
}
|
|
14
|
+
interface MdxPassBuilderOptions {
|
|
15
|
+
sourceFs: SecureSourceFs;
|
|
16
|
+
getAllMdxFiles(): Promise<string[]>;
|
|
17
|
+
getSections(): SectionConfig[] | null;
|
|
18
|
+
loadSectionsConfig(): Promise<SectionConfig[] | null>;
|
|
19
|
+
withApiReferenceSection(sections: SectionConfig[] | null): SectionConfig[] | null;
|
|
20
|
+
determineSectionForFile(filePath: string, frontmatter: Record<string, any>, sections: SectionConfig[] | null): {
|
|
21
|
+
sectionSlug: string;
|
|
22
|
+
pageSlug: string;
|
|
23
|
+
};
|
|
24
|
+
resolveHttpMethod(reference: string): string | undefined;
|
|
25
|
+
}
|
|
26
|
+
export declare class MdxPassBuilder {
|
|
27
|
+
private readonly options;
|
|
28
|
+
constructor(options: MdxPassBuilderOptions);
|
|
29
|
+
capture(files?: string[], seededSources?: ReadonlyMap<string, MdxSourceSnapshot>, refreshSections?: boolean): Promise<MdxPassSnapshot>;
|
|
30
|
+
}
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { safeMatter } from "../lib/utils.js";
|
|
2
|
+
import { buildRealPagesMeta, parseMdxPageMeta } from "./page-catalog.js";
|
|
3
|
+
import { discoverSections } from "./section-resolver.js";
|
|
4
|
+
export class MdxPassBuilder {
|
|
5
|
+
options;
|
|
6
|
+
constructor(options) {
|
|
7
|
+
this.options = options;
|
|
8
|
+
}
|
|
9
|
+
async capture(files, seededSources = new Map(), refreshSections = false) {
|
|
10
|
+
const resolvedFiles = files ?? (await this.options.getAllMdxFiles());
|
|
11
|
+
const sources = new Map(seededSources);
|
|
12
|
+
await Promise.all(resolvedFiles.map(async (file) => {
|
|
13
|
+
const source = file.replace(/\\/g, "/");
|
|
14
|
+
if (!sources.has(source)) {
|
|
15
|
+
sources.set(source, await this.options.sourceFs.readMdxSourceFile(file));
|
|
16
|
+
}
|
|
17
|
+
}));
|
|
18
|
+
let sections = this.options.getSections();
|
|
19
|
+
if (refreshSections) {
|
|
20
|
+
const configuredSections = await this.options.loadSectionsConfig();
|
|
21
|
+
if (configuredSections !== null) {
|
|
22
|
+
sections = this.options.withApiReferenceSection(configuredSections);
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
const documents = resolvedFiles.map((filePath) => {
|
|
26
|
+
const source = sources.get(filePath.replace(/\\/g, "/"));
|
|
27
|
+
if (!source)
|
|
28
|
+
throw new Error(`Unable to snapshot ${filePath}`);
|
|
29
|
+
return {
|
|
30
|
+
filePath,
|
|
31
|
+
frontmatter: safeMatter(source.content, filePath).data,
|
|
32
|
+
};
|
|
33
|
+
});
|
|
34
|
+
sections = this.options.withApiReferenceSection(discoverSections(documents));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const pages = await buildRealPagesMeta(resolvedFiles, async (file) => {
|
|
38
|
+
const source = sources.get(file.replace(/\\/g, "/"));
|
|
39
|
+
if (!source)
|
|
40
|
+
throw new Error(`Unable to snapshot ${file}`);
|
|
41
|
+
return parseMdxPageMeta(file, async () => source, (filePath, frontmatter) => this.options.determineSectionForFile(filePath, frontmatter, sections), (reference) => this.options.resolveHttpMethod(reference));
|
|
42
|
+
});
|
|
43
|
+
return { files: resolvedFiles, pages, sources, sections };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { RouteArtifact } from "../lib/generated-artifacts.js";
|
|
2
|
+
import { OpenApiRegistry } from "../lib/openapi.js";
|
|
3
|
+
import type { NormalizedOpenApiSpec, PageMeta, SectionConfig } from "../lib/types.js";
|
|
4
|
+
import { SecureSourceFs } from "./secure-source-fs.js";
|
|
5
|
+
export interface ApiPageWriteOptions {
|
|
6
|
+
writtenRoutes?: Map<string, string>;
|
|
7
|
+
additionalPreviousRoutes?: Iterable<RouteArtifact>;
|
|
8
|
+
}
|
|
9
|
+
interface OpenApiRefreshCoordinatorOptions {
|
|
10
|
+
rootDir: string;
|
|
11
|
+
watchDir: string;
|
|
12
|
+
outputDir: string;
|
|
13
|
+
configFile: string;
|
|
14
|
+
apiBaseSlug: string;
|
|
15
|
+
sourceFs: SecureSourceFs;
|
|
16
|
+
getRegistry(): OpenApiRegistry;
|
|
17
|
+
setRegistry(registry: OpenApiRegistry): void;
|
|
18
|
+
getSpecs(): NormalizedOpenApiSpec[];
|
|
19
|
+
setSpecs(specs: NormalizedOpenApiSpec[]): void;
|
|
20
|
+
getSections(): SectionConfig[] | null;
|
|
21
|
+
setSections(sections: SectionConfig[] | null): void;
|
|
22
|
+
getOpenApiRoutes(): RouteArtifact[];
|
|
23
|
+
getSuccessfulMdxPages(): PageMeta[];
|
|
24
|
+
resolveSections(): Promise<SectionConfig[] | null>;
|
|
25
|
+
writeApiPages(realPages?: PageMeta[], options?: ApiPageWriteOptions): Promise<Map<string, string>>;
|
|
26
|
+
refreshSiteAggregates(): Promise<void>;
|
|
27
|
+
syncWatcher(): Promise<void>;
|
|
28
|
+
removeOwnedRoute(slug: string): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export declare class OpenApiRefreshCoordinator {
|
|
31
|
+
private readonly options;
|
|
32
|
+
constructor(options: OpenApiRefreshCoordinatorOptions);
|
|
33
|
+
loadInitialRegistry(): Promise<void>;
|
|
34
|
+
private sourceState;
|
|
35
|
+
private loadStableRegistry;
|
|
36
|
+
private applyStableRefresh;
|
|
37
|
+
private restorePreviousRefresh;
|
|
38
|
+
private applyRefresh;
|
|
39
|
+
handleOpenApiChange(): Promise<void>;
|
|
40
|
+
handleConfigChange(): Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
export {};
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { normalizeOpenApiConfig, validateConfig, } from "../lib/config-manager.js";
|
|
4
|
+
import { OpenApiRegistry } from "../lib/openapi.js";
|
|
5
|
+
class OpenApiRestoreError extends AggregateError {
|
|
6
|
+
}
|
|
7
|
+
class OpenApiWatcherRestoreNeededError extends Error {
|
|
8
|
+
originalError;
|
|
9
|
+
constructor(originalError) {
|
|
10
|
+
super("OpenAPI watcher synchronization required verified restoration");
|
|
11
|
+
this.originalError = originalError;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export class OpenApiRefreshCoordinator {
|
|
15
|
+
options;
|
|
16
|
+
constructor(options) {
|
|
17
|
+
this.options = options;
|
|
18
|
+
}
|
|
19
|
+
async loadInitialRegistry() {
|
|
20
|
+
const specs = this.options.getSpecs();
|
|
21
|
+
if (specs.length === 0)
|
|
22
|
+
return;
|
|
23
|
+
const { registry } = await this.loadStableRegistry(specs);
|
|
24
|
+
this.options.setRegistry(registry);
|
|
25
|
+
if (!registry.isEmpty) {
|
|
26
|
+
console.log(chalk.blue(`📘 Loaded ${registry.all.length} API endpoint(s) from ${specs.length} spec(s)`));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async sourceState(registry) {
|
|
30
|
+
return (await Promise.all(registry.sourceFiles.map(async (sourcePath) => {
|
|
31
|
+
return `${sourcePath}:${await this.options.sourceFs.pathState(sourcePath, true)}`;
|
|
32
|
+
}))).join("\n");
|
|
33
|
+
}
|
|
34
|
+
async loadStableRegistry(specs) {
|
|
35
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
36
|
+
const registry = new OpenApiRegistry();
|
|
37
|
+
await registry.load(specs, this.options.rootDir, this.options.apiBaseSlug);
|
|
38
|
+
const current = await this.sourceState(registry);
|
|
39
|
+
if (registry.sourceFingerprint === current) {
|
|
40
|
+
return { registry, sourceState: current };
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
throw new Error("OpenAPI sources changed repeatedly while being loaded");
|
|
44
|
+
}
|
|
45
|
+
async applyStableRefresh(specs) {
|
|
46
|
+
const previousRegistry = this.options.getRegistry();
|
|
47
|
+
const previousSpecs = this.options.getSpecs();
|
|
48
|
+
let successfulApplications = 0;
|
|
49
|
+
try {
|
|
50
|
+
let candidate = await this.loadStableRegistry(specs);
|
|
51
|
+
await this.applyRefresh(candidate.registry, specs);
|
|
52
|
+
successfulApplications += 1;
|
|
53
|
+
// Recheck after watcher readiness so changes in the retargeting window are
|
|
54
|
+
// replayed explicitly instead of being missed by ignoreInitial watchers.
|
|
55
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
56
|
+
if ((await this.sourceState(candidate.registry)) === candidate.sourceState) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
candidate = await this.loadStableRegistry(specs);
|
|
60
|
+
await this.applyRefresh(candidate.registry, specs);
|
|
61
|
+
successfulApplications += 1;
|
|
62
|
+
}
|
|
63
|
+
if ((await this.sourceState(candidate.registry)) === candidate.sourceState) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
throw new Error("OpenAPI sources changed repeatedly while being generated");
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
const watcherRestoreNeeded = error instanceof OpenApiWatcherRestoreNeededError;
|
|
70
|
+
if (successfulApplications === 0 &&
|
|
71
|
+
!(error instanceof OpenApiRestoreError) &&
|
|
72
|
+
!watcherRestoreNeeded) {
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
await this.restorePreviousRefresh(previousRegistry, previousSpecs, previousSpecs !== specs || watcherRestoreNeeded);
|
|
77
|
+
}
|
|
78
|
+
catch (rollbackError) {
|
|
79
|
+
throw new AggregateError([error, rollbackError], "Unable to refresh or restore the previous OpenAPI reference");
|
|
80
|
+
}
|
|
81
|
+
throw watcherRestoreNeeded ? error.originalError : error;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async restorePreviousRefresh(fallbackRegistry, specs, verifySources) {
|
|
85
|
+
if (!verifySources || specs.length === 0) {
|
|
86
|
+
await this.applyRefresh(fallbackRegistry, specs);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
let candidate;
|
|
90
|
+
try {
|
|
91
|
+
candidate = await this.loadStableRegistry(specs);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
// Invalid previous sources still retain their last successful output.
|
|
95
|
+
await this.applyRefresh(fallbackRegistry, specs);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
99
|
+
await this.applyRefresh(candidate.registry, specs);
|
|
100
|
+
if ((await this.sourceState(candidate.registry)) === candidate.sourceState) {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (attempt < 3)
|
|
104
|
+
candidate = await this.loadStableRegistry(specs);
|
|
105
|
+
}
|
|
106
|
+
throw new Error("Previous OpenAPI sources changed repeatedly while being restored");
|
|
107
|
+
}
|
|
108
|
+
async applyRefresh(nextRegistry, nextSpecs) {
|
|
109
|
+
const previousRegistry = this.options.getRegistry();
|
|
110
|
+
const previousSpecs = this.options.getSpecs();
|
|
111
|
+
const previousSections = this.options.getSections();
|
|
112
|
+
const previousRoutes = this.options.getOpenApiRoutes();
|
|
113
|
+
const candidateRoutes = new Map();
|
|
114
|
+
let watcherSyncAttempted = false;
|
|
115
|
+
try {
|
|
116
|
+
this.options.setRegistry(nextRegistry);
|
|
117
|
+
this.options.setSpecs(nextSpecs);
|
|
118
|
+
this.options.setSections(await this.options.resolveSections());
|
|
119
|
+
await this.options.writeApiPages(undefined, {
|
|
120
|
+
writtenRoutes: candidateRoutes,
|
|
121
|
+
});
|
|
122
|
+
await this.options.refreshSiteAggregates();
|
|
123
|
+
watcherSyncAttempted = true;
|
|
124
|
+
await this.options.syncWatcher();
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
this.options.setRegistry(previousRegistry);
|
|
128
|
+
this.options.setSpecs(previousSpecs);
|
|
129
|
+
this.options.setSections(previousSections);
|
|
130
|
+
const rollbackErrors = [];
|
|
131
|
+
if (watcherSyncAttempted) {
|
|
132
|
+
try {
|
|
133
|
+
await this.options.syncWatcher();
|
|
134
|
+
}
|
|
135
|
+
catch (rollbackError) {
|
|
136
|
+
rollbackErrors.push(rollbackError);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const previousSlugs = new Set(previousRoutes.map((route) => route.slug));
|
|
140
|
+
const occupiedMdxSlugs = new Set(this.options.getSuccessfulMdxPages().map((page) => page.slug));
|
|
141
|
+
for (const slug of new Set(candidateRoutes.values())) {
|
|
142
|
+
if (previousSlugs.has(slug) || occupiedMdxSlugs.has(slug))
|
|
143
|
+
continue;
|
|
144
|
+
try {
|
|
145
|
+
await this.options.removeOwnedRoute(slug);
|
|
146
|
+
}
|
|
147
|
+
catch (rollbackError) {
|
|
148
|
+
rollbackErrors.push(rollbackError);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
await this.options.writeApiPages(undefined, {
|
|
153
|
+
additionalPreviousRoutes: [...candidateRoutes].map(([source, slug]) => ({ kind: "openapi", source, slug })),
|
|
154
|
+
});
|
|
155
|
+
await this.options.refreshSiteAggregates();
|
|
156
|
+
}
|
|
157
|
+
catch (rollbackError) {
|
|
158
|
+
rollbackErrors.push(rollbackError);
|
|
159
|
+
}
|
|
160
|
+
if (rollbackErrors.length > 0) {
|
|
161
|
+
throw new OpenApiRestoreError([error, ...rollbackErrors], "Unable to apply or restore the OpenAPI reference");
|
|
162
|
+
}
|
|
163
|
+
if (watcherSyncAttempted) {
|
|
164
|
+
throw new OpenApiWatcherRestoreNeededError(error);
|
|
165
|
+
}
|
|
166
|
+
throw error;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async handleOpenApiChange() {
|
|
170
|
+
console.log(chalk.cyan("📘 OpenAPI spec changed - regenerating API reference"));
|
|
171
|
+
try {
|
|
172
|
+
await this.applyStableRefresh(this.options.getSpecs());
|
|
173
|
+
console.log(chalk.green("✅ API reference updated"));
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
console.error(chalk.red("❌ Error updating API reference:"), error);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async handleConfigChange() {
|
|
180
|
+
const configPath = path.join(this.options.rootDir, this.options.configFile);
|
|
181
|
+
let config;
|
|
182
|
+
try {
|
|
183
|
+
const { data } = await this.options.sourceFs.readProjectSourceFile(configPath, "Doccupine configuration source");
|
|
184
|
+
config = validateConfig(JSON.parse(data.toString("utf8")), this.options.rootDir);
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
console.warn(chalk.yellow("⚠️ doccupine.json is missing or invalid - keeping the current configuration"), error instanceof Error ? error.message : error);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if ((config.watchDir &&
|
|
191
|
+
path.resolve(this.options.rootDir, config.watchDir) !==
|
|
192
|
+
this.options.watchDir) ||
|
|
193
|
+
(config.outputDir &&
|
|
194
|
+
path.resolve(this.options.rootDir, config.outputDir) !==
|
|
195
|
+
this.options.outputDir)) {
|
|
196
|
+
console.log(chalk.yellow("⚠️ watchDir/outputDir changes in doccupine.json need a restart to apply"));
|
|
197
|
+
}
|
|
198
|
+
const nextSpecs = normalizeOpenApiConfig(config.openapi);
|
|
199
|
+
if (JSON.stringify(nextSpecs) === JSON.stringify(this.options.getSpecs())) {
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
console.log(chalk.cyan("📘 OpenAPI configuration changed - updating API reference"));
|
|
203
|
+
try {
|
|
204
|
+
await this.applyStableRefresh(nextSpecs);
|
|
205
|
+
console.log(chalk.green("✅ API reference updated"));
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
console.error(chalk.red("❌ Error updating API reference:"), error);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { PageMeta, SectionConfig } from "../lib/types.js";
|
|
2
|
+
import { GeneratedRouteManager } from "./generated-route-manager.js";
|
|
3
|
+
type WriteRedirect = (slug: string, target: string) => Promise<void>;
|
|
4
|
+
export declare class SectionIndexGenerator {
|
|
5
|
+
private readonly outputDir;
|
|
6
|
+
private readonly routeManager;
|
|
7
|
+
constructor(outputDir: string, routeManager: GeneratedRouteManager);
|
|
8
|
+
generate(pages: PageMeta[], sections: SectionConfig[] | null, declaredSlugs: Set<string> | undefined, writeRedirect: WriteRedirect): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import fs from "fs-extra";
|
|
2
|
+
import { readOutputFileIfPresent, resolveOutputPath, } from "../lib/output-safety.js";
|
|
3
|
+
import { writeFileAtomic } from "../lib/utils.js";
|
|
4
|
+
export class SectionIndexGenerator {
|
|
5
|
+
outputDir;
|
|
6
|
+
routeManager;
|
|
7
|
+
constructor(outputDir, routeManager) {
|
|
8
|
+
this.outputDir = outputDir;
|
|
9
|
+
this.routeManager = routeManager;
|
|
10
|
+
}
|
|
11
|
+
async generate(pages, sections, declaredSlugs, writeRedirect) {
|
|
12
|
+
const occupiedSlugs = new Set(pages.map((page) => page.slug));
|
|
13
|
+
const resolvedDeclaredSlugs = new Set(occupiedSlugs);
|
|
14
|
+
for (const slug of declaredSlugs ?? [])
|
|
15
|
+
resolvedDeclaredSlugs.add(slug);
|
|
16
|
+
const redirects = new Map();
|
|
17
|
+
for (const section of sections ?? []) {
|
|
18
|
+
if (section.slug === "" || resolvedDeclaredSlugs.has(section.slug)) {
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
const sectionPages = pages
|
|
22
|
+
.filter((page) => page.section === section.slug)
|
|
23
|
+
.sort((a, b) => {
|
|
24
|
+
if (a.categoryOrder !== b.categoryOrder) {
|
|
25
|
+
return a.categoryOrder - b.categoryOrder;
|
|
26
|
+
}
|
|
27
|
+
return a.order - b.order;
|
|
28
|
+
});
|
|
29
|
+
const firstPage = sectionPages[0];
|
|
30
|
+
if (firstPage)
|
|
31
|
+
redirects.set(section.slug, firstPage.slug);
|
|
32
|
+
}
|
|
33
|
+
const previousSlugs = this.routeManager.sectionIndexSlugs();
|
|
34
|
+
const touchedSlugs = new Set([...previousSlugs, ...redirects.keys()]);
|
|
35
|
+
const previousFiles = new Map();
|
|
36
|
+
for (const slug of touchedSlugs) {
|
|
37
|
+
previousFiles.set(slug, await readOutputFileIfPresent(this.outputDir, "app", "(site)", slug, "page.tsx"));
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
for (const [slug, target] of redirects) {
|
|
41
|
+
await writeRedirect(slug, target);
|
|
42
|
+
}
|
|
43
|
+
await this.routeManager.cleanupStaleSectionIndexPages(new Set(redirects.keys()), occupiedSlugs, (dir, stopDir) => this.routeManager.removeEmptyDirsUpTo(dir, stopDir));
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
const rollbackErrors = [];
|
|
47
|
+
this.routeManager.replaceSectionIndexSlugs(previousSlugs);
|
|
48
|
+
for (const [slug, content] of previousFiles) {
|
|
49
|
+
try {
|
|
50
|
+
const target = resolveOutputPath(this.outputDir, "app", "(site)", slug, "page.tsx");
|
|
51
|
+
if (content === null) {
|
|
52
|
+
await fs.remove(target);
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
await writeFileAtomic(target, content);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
catch (rollbackError) {
|
|
59
|
+
rollbackErrors.push(rollbackError);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (rollbackErrors.length > 0) {
|
|
63
|
+
throw new AggregateError([error, ...rollbackErrors], "Unable to generate or restore section index redirects");
|
|
64
|
+
}
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -42,17 +42,25 @@ export declare class WatchCoordinator {
|
|
|
42
42
|
private mutationQueue;
|
|
43
43
|
private stopping;
|
|
44
44
|
private readyCancellations;
|
|
45
|
+
private pendingWatcherClosures;
|
|
45
46
|
private sourceSnapshot;
|
|
46
47
|
private publicWatcherStarting;
|
|
48
|
+
private publicWatcherRestartRequested;
|
|
47
49
|
constructor(options: WatchCoordinatorOptions);
|
|
48
50
|
private enqueueMutation;
|
|
51
|
+
private closeDetachedWatcher;
|
|
49
52
|
private waitForWatcherReady;
|
|
53
|
+
private trackWatcherReady;
|
|
54
|
+
private waitForPublicWatcherReady;
|
|
50
55
|
private captureSourceSnapshot;
|
|
51
56
|
establishSourceSnapshot(projectSourceStates?: Readonly<Record<string, string>>, openApiSourceState?: string, doccupineSourceState?: string): Promise<void>;
|
|
52
57
|
private reconcileWatchedSources;
|
|
53
58
|
startWatching(): Promise<void>;
|
|
59
|
+
private startWatchers;
|
|
54
60
|
private setupPublicWatcher;
|
|
55
61
|
syncOpenApiSpecWatcher(specs: readonly NormalizedOpenApiSpec[], sourceFiles?: readonly string[]): Promise<void>;
|
|
56
62
|
stop(): Promise<void>;
|
|
63
|
+
private drainMutationQueue;
|
|
64
|
+
private closeCurrentWatchers;
|
|
57
65
|
}
|
|
58
66
|
export {};
|