doccupine 0.0.144 → 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.
Files changed (51) hide show
  1. package/dist/generator/api-reference-generator.d.ts +4 -2
  2. package/dist/generator/api-reference-generator.js +32 -31
  3. package/dist/generator/app-scaffolder.d.ts +1 -2
  4. package/dist/generator/app-scaffolder.js +1 -6
  5. package/dist/generator/generated-page-publisher.d.ts +21 -0
  6. package/dist/generator/generated-page-publisher.js +124 -0
  7. package/dist/generator/generated-route-manager.d.ts +7 -3
  8. package/dist/generator/generated-route-manager.js +55 -19
  9. package/dist/generator/mdx-pass-builder.d.ts +31 -0
  10. package/dist/generator/mdx-pass-builder.js +45 -0
  11. package/dist/generator/openapi-refresh-coordinator.d.ts +42 -0
  12. package/dist/generator/openapi-refresh-coordinator.js +211 -0
  13. package/dist/generator/page-catalog.d.ts +4 -0
  14. package/dist/generator/page-catalog.js +8 -1
  15. package/dist/generator/project-config-repository.d.ts +8 -0
  16. package/dist/generator/project-config-repository.js +73 -15
  17. package/dist/generator/section-index-generator.d.ts +10 -0
  18. package/dist/generator/section-index-generator.js +68 -0
  19. package/dist/generator/secure-source-fs.d.ts +5 -1
  20. package/dist/generator/secure-source-fs.js +112 -3
  21. package/dist/generator/site-artifacts.d.ts +3 -2
  22. package/dist/generator/site-artifacts.js +6 -9
  23. package/dist/generator/watch-coordinator.d.ts +11 -2
  24. package/dist/generator/watch-coordinator.js +157 -62
  25. package/dist/lib/config-manager.d.ts +1 -0
  26. package/dist/lib/config-manager.js +194 -12
  27. package/dist/lib/generated-artifacts.d.ts +8 -2
  28. package/dist/lib/generated-artifacts.js +25 -6
  29. package/dist/lib/openapi.d.ts +4 -0
  30. package/dist/lib/openapi.js +36 -4
  31. package/dist/lib/output-safety.js +10 -3
  32. package/dist/mdx-to-nextjs-generator.d.ts +38 -23
  33. package/dist/mdx-to-nextjs-generator.js +521 -310
  34. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  35. package/dist/templates/mdx/api-playground.mdx.js +11 -2
  36. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  37. package/dist/templates/mdx/commands.mdx.js +26 -1
  38. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  39. package/dist/templates/mdx/media-and-assets.mdx.js +5 -0
  40. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  41. package/dist/templates/mdx/model-context-protocol.mdx.js +2 -1
  42. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  43. package/dist/templates/mdx/platform/api-playground.mdx.js +2 -2
  44. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  45. package/dist/templates/mdx/platform/publishing.mdx.js +3 -3
  46. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  47. package/dist/templates/mdx/what-is-doccupine.mdx.js +8 -3
  48. package/dist/templates/package.js +1 -1
  49. package/dist/templates/utils/orderNavItems.d.ts +1 -1
  50. package/dist/templates/utils/orderNavItems.js +1 -1
  51. package/package.json +2 -2
@@ -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
+ }
@@ -11,6 +11,10 @@ type ResolveSectionRoute = (filePath: string, frontmatter: Record<string, any>)
11
11
  };
12
12
  type ResolveHttpMethod = (reference: string) => string | undefined;
13
13
  export declare function parseMdxPageMeta(filePath: string, readMdxSource: ReadMdxSource, resolveSectionRoute: ResolveSectionRoute, resolveHttpMethod: ResolveHttpMethod): Promise<PageMeta>;
14
+ export declare class RouteCollisionError extends Error {
15
+ readonly sources: readonly [string, string];
16
+ constructor(slug: string, sources: readonly [string, string]);
17
+ }
14
18
  export declare function validateRouteCollisions(pages: PageMeta[]): void;
15
19
  export declare function buildRealPagesMeta(files: string[], parsePage: (filePath: string) => Promise<PageMeta>): Promise<PageMeta[]>;
16
20
  export declare function mergePages(realPages: PageMeta[], syntheticPages: PageMeta[]): PageMeta[];
@@ -38,12 +38,19 @@ export async function parseMdxPageMeta(filePath, readMdxSource, resolveSectionRo
38
38
  lastModified,
39
39
  };
40
40
  }
41
+ export class RouteCollisionError extends Error {
42
+ sources;
43
+ constructor(slug, sources) {
44
+ super(`Route collision at "/${slug}": both "${sources[0]}" and "${sources[1]}" generate the same page.`);
45
+ this.sources = sources;
46
+ }
47
+ }
41
48
  export function validateRouteCollisions(pages) {
42
49
  const bySlug = new Map();
43
50
  for (const page of pages) {
44
51
  const existing = bySlug.get(page.slug);
45
52
  if (existing) {
46
- throw new Error(`Route collision at "/${page.slug}": both "${existing}" and "${page.path}" generate the same page.`);
53
+ throw new RouteCollisionError(page.slug, [existing, page.path]);
47
54
  }
48
55
  bySlug.set(page.slug, page.path);
49
56
  }
@@ -7,9 +7,17 @@ export declare class ProjectConfigRepository {
7
7
  private readonly configFiles;
8
8
  private readonly fontConfigFile;
9
9
  private readonly analyticsConfigFile;
10
+ private sourceSnapshot;
10
11
  constructor(rootDir: string, outputDir: string, sourceFs: SecureSourceFs, configFiles: readonly string[], fontConfigFile: string, analyticsConfigFile: string);
11
12
  private outputPath;
13
+ private hasRootSourceFile;
14
+ private readRootSourceFile;
12
15
  private copyRootSourceFile;
16
+ private readOptionalRootSourceFile;
17
+ readConfigFile(): Promise<string | null>;
18
+ preflightSourceFiles(): Promise<void>;
19
+ sourceSnapshotStates(): Record<string, string>;
20
+ clearSourceSnapshot(): void;
13
21
  copyConfigFile(configFile: string): Promise<void>;
14
22
  resetConfigFile(configFile: string): Promise<void>;
15
23
  copyCustomConfigFiles(): Promise<void>;
@@ -1,5 +1,6 @@
1
1
  import chalk from "chalk";
2
2
  import fs from "fs-extra";
3
+ import { createHash } from "node:crypto";
3
4
  import path from "node:path";
4
5
  import { resolveOutputPath } from "../lib/output-safety.js";
5
6
  import { validateAnalyticsConfig, validateFontConfig, } from "../lib/project-config.js";
@@ -17,6 +18,7 @@ export class ProjectConfigRepository {
17
18
  configFiles;
18
19
  fontConfigFile;
19
20
  analyticsConfigFile;
21
+ sourceSnapshot = null;
20
22
  constructor(rootDir, outputDir, sourceFs, configFiles, fontConfigFile, analyticsConfigFile) {
21
23
  this.rootDir = rootDir;
22
24
  this.outputDir = outputDir;
@@ -28,10 +30,69 @@ export class ProjectConfigRepository {
28
30
  outputPath(...segments) {
29
31
  return resolveOutputPath(this.outputDir, ...segments);
30
32
  }
33
+ async hasRootSourceFile(fileName) {
34
+ if (this.sourceSnapshot?.has(fileName)) {
35
+ return this.sourceSnapshot.get(fileName)?.data !== null;
36
+ }
37
+ return fs.pathExists(path.join(this.rootDir, fileName));
38
+ }
39
+ async readRootSourceFile(sourcePath, label) {
40
+ const fileName = path.basename(sourcePath);
41
+ if (this.sourceSnapshot?.has(fileName)) {
42
+ const data = this.sourceSnapshot.get(fileName)?.data;
43
+ if (data === null || data === undefined) {
44
+ throw new Error(`Source file ${sourcePath} is not in the snapshot`);
45
+ }
46
+ return data;
47
+ }
48
+ return (await this.sourceFs.readProjectSourceFile(sourcePath, label)).data;
49
+ }
31
50
  async copyRootSourceFile(sourcePath, destPath, label) {
32
- const { data } = await this.sourceFs.readProjectSourceFile(sourcePath, label);
51
+ const data = await this.readRootSourceFile(sourcePath, label);
33
52
  await writeFileAtomic(destPath, data);
34
53
  }
54
+ async readOptionalRootSourceFile(fileName, label) {
55
+ const sourcePath = path.join(this.rootDir, fileName);
56
+ if (!(await this.hasRootSourceFile(fileName)))
57
+ return null;
58
+ const data = await this.readRootSourceFile(sourcePath, label);
59
+ return data.toString("utf8");
60
+ }
61
+ async readConfigFile() {
62
+ return this.readOptionalRootSourceFile("config.json", "config source");
63
+ }
64
+ async preflightSourceFiles() {
65
+ const sources = [
66
+ ...this.configFiles.map((fileName) => [fileName, "config source"]),
67
+ [this.fontConfigFile, "font source"],
68
+ [this.analyticsConfigFile, "analytics source"],
69
+ ];
70
+ const snapshot = new Map();
71
+ for (const [fileName, label] of sources) {
72
+ const sourcePath = path.join(this.rootDir, fileName);
73
+ if (await fs.pathExists(sourcePath)) {
74
+ const { data, stat } = await this.sourceFs.readProjectSourceFile(sourcePath, label);
75
+ const hash = createHash("sha256").update(data).digest("hex");
76
+ snapshot.set(fileName, {
77
+ data,
78
+ state: `file:${stat.size}:${stat.mtimeMs}:${stat.dev}:${stat.ino}:${hash}`,
79
+ });
80
+ }
81
+ else {
82
+ snapshot.set(fileName, { data: null, state: "missing" });
83
+ }
84
+ }
85
+ this.sourceSnapshot = snapshot;
86
+ }
87
+ sourceSnapshotStates() {
88
+ return Object.fromEntries([...(this.sourceSnapshot ?? [])].map(([fileName, entry]) => [
89
+ fileName,
90
+ entry.state,
91
+ ]));
92
+ }
93
+ clearSourceSnapshot() {
94
+ this.sourceSnapshot = null;
95
+ }
35
96
  async copyConfigFile(configFile) {
36
97
  await this.copyRootSourceFile(path.join(this.rootDir, configFile), this.outputPath(configFile), "config source");
37
98
  }
@@ -43,7 +104,7 @@ export class ProjectConfigRepository {
43
104
  for (const configFile of this.configFiles) {
44
105
  const sourcePath = path.join(this.rootDir, configFile);
45
106
  console.log(chalk.gray(` Checking ${configFile}...`));
46
- if (await fs.pathExists(sourcePath)) {
107
+ if (await this.hasRootSourceFile(configFile)) {
47
108
  await this.copyConfigFile(configFile);
48
109
  console.log(chalk.green(` ✓ Copied ${configFile} to Next.js app`));
49
110
  }
@@ -58,7 +119,7 @@ export class ProjectConfigRepository {
58
119
  async copyFontConfig() {
59
120
  console.log(chalk.blue(`🔍 Checking for font configuration...`));
60
121
  const sourcePath = path.join(this.rootDir, this.fontConfigFile);
61
- if (await fs.pathExists(sourcePath)) {
122
+ if (await this.hasRootSourceFile(this.fontConfigFile)) {
62
123
  await this.copyFontConfigFile();
63
124
  console.log(chalk.green(` ✓ Copied ${this.fontConfigFile} to Next.js app`));
64
125
  }
@@ -74,11 +135,10 @@ export class ProjectConfigRepository {
74
135
  return true;
75
136
  }
76
137
  async loadFontConfig() {
77
- const fontPath = path.join(this.rootDir, this.fontConfigFile);
78
138
  try {
79
- if (await fs.pathExists(fontPath)) {
80
- const { data } = await this.sourceFs.readProjectSourceFile(fontPath, "font source");
81
- return validateFontConfig(JSON.parse(data.toString("utf8")));
139
+ const content = await this.readOptionalRootSourceFile(this.fontConfigFile, "font source");
140
+ if (content !== null) {
141
+ return validateFontConfig(JSON.parse(content));
82
142
  }
83
143
  }
84
144
  catch (error) {
@@ -87,11 +147,10 @@ export class ProjectConfigRepository {
87
147
  return null;
88
148
  }
89
149
  async loadAnalyticsConfig() {
90
- const analyticsPath = path.join(this.rootDir, this.analyticsConfigFile);
91
150
  try {
92
- if (await fs.pathExists(analyticsPath)) {
93
- const { data } = await this.sourceFs.readProjectSourceFile(analyticsPath, "analytics source");
94
- return validateAnalyticsConfig(JSON.parse(data.toString("utf8")));
151
+ const content = await this.readOptionalRootSourceFile(this.analyticsConfigFile, "analytics source");
152
+ if (content !== null) {
153
+ return validateAnalyticsConfig(JSON.parse(content));
95
154
  }
96
155
  }
97
156
  catch (error) {
@@ -105,7 +164,7 @@ export class ProjectConfigRepository {
105
164
  async copyAnalyticsConfig(loadConfig) {
106
165
  console.log(chalk.blue(`🔍 Checking for analytics configuration...`));
107
166
  const sourcePath = path.join(this.rootDir, this.analyticsConfigFile);
108
- if (await fs.pathExists(sourcePath)) {
167
+ if (await this.hasRootSourceFile(this.analyticsConfigFile)) {
109
168
  await this.writeAnalyticsConfig(await loadConfig());
110
169
  console.log(chalk.green(` ✓ Copied ${this.analyticsConfigFile} to Next.js app`));
111
170
  }
@@ -117,10 +176,9 @@ export class ProjectConfigRepository {
117
176
  await this.writeAnalyticsConfig(null);
118
177
  }
119
178
  async loadSectionsConfig() {
120
- const sectionsPath = path.join(this.rootDir, "sections.json");
121
179
  try {
122
- if (await fs.pathExists(sectionsPath)) {
123
- const content = await fs.readFile(sectionsPath, "utf8");
180
+ const content = await this.readOptionalRootSourceFile("sections.json", "sections source");
181
+ if (content !== null) {
124
182
  const parsed = JSON.parse(content);
125
183
  return validateSectionsConfig(parsed);
126
184
  }
@@ -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
+ }
@@ -18,7 +18,11 @@ export declare class SecureSourceFs {
18
18
  data: Buffer;
19
19
  stat: fs.Stats;
20
20
  }>;
21
- ensureSafeStarterPath(relativePath: string): Promise<string>;
21
+ private assertPinnedDocumentationRoot;
22
+ private pinDocumentationRoot;
23
+ private removeCreatedStarterFile;
24
+ private writeStarterFile;
25
+ writeStarterFilesIfEmpty(files: Iterable<readonly [string, string | Uint8Array]> | AsyncIterable<readonly [string, string | Uint8Array]>): Promise<void>;
22
26
  pathState(filePath: string, hashContents?: boolean): Promise<string>;
23
27
  treeState(root: string, includeFile: (relativePath: string) => boolean, hashContents?: boolean): Promise<string>;
24
28
  scanPublicFiles(): Promise<string[] | null>;
@@ -136,13 +136,52 @@ export class SecureSourceFs {
136
136
  async readPublicSourceFile(sourcePath) {
137
137
  return this.readSafeSourceFile(path.join(this.projectRoot, "public"), sourcePath, "public source", true);
138
138
  }
139
- async ensureSafeStarterPath(relativePath) {
139
+ async assertPinnedDocumentationRoot(pinned) {
140
+ try {
141
+ const currentRootStat = await fs.lstat(pinned.resolvedRoot);
142
+ const currentRealRoot = await fs.realpath(pinned.resolvedRoot);
143
+ const currentRealRootStat = await fs.stat(currentRealRoot);
144
+ if (currentRealRoot !== pinned.realRoot ||
145
+ !currentRealRootStat.isDirectory() ||
146
+ !sameFileIdentity(pinned.rootStat, currentRootStat) ||
147
+ !sameFileIdentity(pinned.realRootStat, currentRealRootStat)) {
148
+ throw new Error("changed");
149
+ }
150
+ }
151
+ catch {
152
+ throw this.sourcePathError("documentation source", pinned.resolvedRoot, "the source root changed while starter documents were being created");
153
+ }
154
+ }
155
+ async pinDocumentationRoot() {
140
156
  const resolvedRoot = path.resolve(this.documentationRoot);
157
+ const rootStat = await fs.lstat(resolvedRoot);
158
+ const realRoot = await this.realSourceRoot(resolvedRoot, "documentation source", false);
159
+ const realRootStat = await fs.stat(realRoot);
160
+ const pinned = { resolvedRoot, rootStat, realRoot, realRootStat };
161
+ await this.assertPinnedDocumentationRoot(pinned);
162
+ return pinned;
163
+ }
164
+ async removeCreatedStarterFile(targetPath, openedStat) {
165
+ try {
166
+ const currentStat = await fs.lstat(targetPath);
167
+ if (!currentStat.isSymbolicLink() &&
168
+ currentStat.isFile() &&
169
+ sameFileIdentity(openedStat, currentStat)) {
170
+ await fs.unlink(targetPath);
171
+ }
172
+ }
173
+ catch (error) {
174
+ if (errorCode(error) !== "ENOENT")
175
+ throw error;
176
+ }
177
+ }
178
+ async writeStarterFile(relativePath, content, pinned) {
179
+ await this.assertPinnedDocumentationRoot(pinned);
180
+ const { resolvedRoot, realRoot } = pinned;
141
181
  const targetPath = path.resolve(resolvedRoot, relativePath);
142
182
  if (!isPathInside(resolvedRoot, targetPath)) {
143
183
  throw this.sourcePathError("documentation source", targetPath, `the starter path is outside ${resolvedRoot}`);
144
184
  }
145
- const realRoot = await this.realSourceRoot(resolvedRoot, "documentation source", false);
146
185
  const parentRelativePath = path.relative(resolvedRoot, path.dirname(targetPath));
147
186
  let currentPath = resolvedRoot;
148
187
  for (const component of parentRelativePath
@@ -165,6 +204,9 @@ export class SecureSourceFs {
165
204
  throw this.sourcePathError("documentation source", currentPath, `the real path ${realPath} is outside ${realRoot}`);
166
205
  }
167
206
  }
207
+ const parentPath = path.dirname(targetPath);
208
+ const parentStat = await fs.lstat(parentPath);
209
+ const realParent = await fs.realpath(parentPath);
168
210
  try {
169
211
  const stat = await fs.lstat(targetPath);
170
212
  const detail = stat.isSymbolicLink()
@@ -176,7 +218,74 @@ export class SecureSourceFs {
176
218
  if (errorCode(error) !== "ENOENT")
177
219
  throw error;
178
220
  }
179
- return targetPath;
221
+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
222
+ let handle;
223
+ try {
224
+ handle = await open(targetPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow, 0o666);
225
+ }
226
+ catch (error) {
227
+ if (errorCode(error) === "EEXIST" || errorCode(error) === "ELOOP") {
228
+ throw this.sourcePathError("documentation source", targetPath, "the starter path changed before it could be created");
229
+ }
230
+ throw error;
231
+ }
232
+ let openedStat;
233
+ try {
234
+ openedStat = await handle.stat();
235
+ let currentParentStat;
236
+ let currentRealParent;
237
+ let currentTargetStat;
238
+ try {
239
+ currentParentStat = await fs.lstat(parentPath);
240
+ currentRealParent = await fs.realpath(parentPath);
241
+ currentTargetStat = await fs.lstat(targetPath);
242
+ }
243
+ catch {
244
+ throw this.sourcePathError("documentation source", targetPath, "the starter path changed while it was being created");
245
+ }
246
+ const stableRootSymlink = parentPath === resolvedRoot &&
247
+ parentStat.isSymbolicLink() &&
248
+ currentParentStat.isSymbolicLink() &&
249
+ sameFileIdentity(parentStat, currentParentStat);
250
+ if ((!currentParentStat.isDirectory() && !stableRootSymlink) ||
251
+ currentRealParent !== realParent ||
252
+ !isPathInside(realRoot, currentRealParent) ||
253
+ !sameFileIdentity(parentStat, currentParentStat) ||
254
+ currentTargetStat.isSymbolicLink() ||
255
+ !currentTargetStat.isFile() ||
256
+ !sameFileIdentity(openedStat, currentTargetStat)) {
257
+ throw this.sourcePathError("documentation source", targetPath, "the starter path changed while it was being created");
258
+ }
259
+ await handle.writeFile(content);
260
+ }
261
+ catch (error) {
262
+ try {
263
+ await handle.close();
264
+ }
265
+ catch {
266
+ // Preserve the creation failure; cleanup below still verifies identity.
267
+ }
268
+ if (openedStat) {
269
+ try {
270
+ await this.removeCreatedStarterFile(targetPath, openedStat);
271
+ }
272
+ catch {
273
+ // Preserve the original failure rather than masking its cause.
274
+ }
275
+ }
276
+ throw error;
277
+ }
278
+ await handle.close();
279
+ }
280
+ async writeStarterFilesIfEmpty(files) {
281
+ const pinned = await this.pinDocumentationRoot();
282
+ const existingFiles = await this.getAllMdxFiles();
283
+ await this.assertPinnedDocumentationRoot(pinned);
284
+ if (existingFiles.length > 0)
285
+ return;
286
+ for await (const [relativePath, content] of files) {
287
+ await this.writeStarterFile(relativePath, content, pinned);
288
+ }
180
289
  }
181
290
  async pathState(filePath, hashContents = false) {
182
291
  try {
@@ -12,8 +12,9 @@ type ReadMdxSource = (filePath: string) => Promise<{
12
12
  content: string;
13
13
  }>;
14
14
  type ReadOpenApiBody = (slug: string) => string | undefined;
15
- export declare function loadSiteUrl(rootDir: string): Promise<string | null>;
16
- export declare function loadSiteMetadata(rootDir: string): Promise<SiteMetadata>;
15
+ type ReadConfigSource = () => Promise<string | null>;
16
+ export declare function loadSiteUrl(readConfigSource: ReadConfigSource): Promise<string | null>;
17
+ export declare function loadSiteMetadata(readConfigSource: ReadConfigSource): Promise<SiteMetadata>;
17
18
  export declare function buildSitemapEntries(pages: PageMeta[], sectionsConfig: SectionConfig[] | null): SitemapEntry[];
18
19
  export declare function writeSitemap(outputDir: string, sectionsConfig: SectionConfig[] | null, resolvePages: ResolvePages, resolveSiteUrl: () => Promise<string | null>): Promise<void>;
19
20
  export declare function writeRobots(outputDir: string, resolveSiteUrl: () => Promise<string | null>): Promise<void>;