doccupine 0.0.144 → 0.0.145

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 (40) 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-route-manager.d.ts +4 -3
  6. package/dist/generator/generated-route-manager.js +34 -11
  7. package/dist/generator/page-catalog.d.ts +4 -0
  8. package/dist/generator/page-catalog.js +8 -1
  9. package/dist/generator/project-config-repository.d.ts +8 -0
  10. package/dist/generator/project-config-repository.js +73 -15
  11. package/dist/generator/secure-source-fs.d.ts +5 -1
  12. package/dist/generator/secure-source-fs.js +112 -3
  13. package/dist/generator/site-artifacts.d.ts +3 -2
  14. package/dist/generator/site-artifacts.js +6 -9
  15. package/dist/generator/watch-coordinator.d.ts +3 -2
  16. package/dist/generator/watch-coordinator.js +29 -11
  17. package/dist/lib/config-manager.d.ts +1 -0
  18. package/dist/lib/config-manager.js +194 -12
  19. package/dist/lib/generated-artifacts.d.ts +8 -2
  20. package/dist/lib/generated-artifacts.js +25 -6
  21. package/dist/lib/openapi.d.ts +4 -0
  22. package/dist/lib/openapi.js +36 -4
  23. package/dist/mdx-to-nextjs-generator.d.ts +43 -9
  24. package/dist/mdx-to-nextjs-generator.js +679 -211
  25. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  26. package/dist/templates/mdx/api-playground.mdx.js +11 -2
  27. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  28. package/dist/templates/mdx/commands.mdx.js +26 -1
  29. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  30. package/dist/templates/mdx/media-and-assets.mdx.js +5 -0
  31. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  32. package/dist/templates/mdx/model-context-protocol.mdx.js +2 -1
  33. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  34. package/dist/templates/mdx/platform/api-playground.mdx.js +2 -2
  35. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  36. package/dist/templates/mdx/platform/publishing.mdx.js +3 -3
  37. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  38. package/dist/templates/mdx/what-is-doccupine.mdx.js +8 -3
  39. package/dist/templates/package.js +1 -1
  40. package/package.json +2 -2
@@ -1,4 +1,5 @@
1
1
  import { GeneratedArtifacts } from "../lib/generated-artifacts.js";
2
+ import type { RouteArtifact } from "../lib/generated-artifacts.js";
2
3
  import { OpenApiRegistry } from "../lib/openapi.js";
3
4
  import type { OperationDescriptor } from "../lib/openapi-types.js";
4
5
  import type { MDXFile, PageMeta } from "../lib/types.js";
@@ -11,10 +12,11 @@ type CleanupStalePages = (nextRoutes: Map<string, string>, realSlugs: Set<string
11
12
  export declare class ApiReferenceGenerator {
12
13
  private readonly outputDir;
13
14
  private readonly artifacts;
15
+ private pendingStaleRoutes;
14
16
  constructor(outputDir: string, artifacts: GeneratedArtifacts);
15
17
  mergePages(registry: OpenApiRegistry, realPages: PageMeta[]): PageMeta[];
16
- writePages(registry: OpenApiRegistry, apiBaseSlug: string, realPages: PageMeta[], generatePage: GeneratePage, writeAllowlist: WriteAllowlist, cleanupStalePages: CleanupStalePages): Promise<void>;
18
+ writePages(registry: OpenApiRegistry, apiBaseSlug: string, realPages: PageMeta[], generatePage: GeneratePage, writeAllowlist: WriteAllowlist, cleanupStalePages: CleanupStalePages, writtenRoutes?: Map<string, string>): Promise<Map<string, string>>;
17
19
  writeAllowlist(registry: OpenApiRegistry): Promise<void>;
18
- cleanupStalePages(nextRoutes: Map<string, string>, realSlugs: Set<string>, removeOwnedRoute: RemoveOwnedRoute): Promise<void>;
20
+ cleanupStalePages(nextRoutes: Map<string, string>, occupiedMdxSlugs: Set<string>, removeOwnedRoute: RemoveOwnedRoute, additionalPreviousRoutes?: Iterable<RouteArtifact>): Promise<void>;
19
21
  }
20
22
  export {};
@@ -8,6 +8,7 @@ import { mergePages as mergePageCatalog } from "./page-catalog.js";
8
8
  export class ApiReferenceGenerator {
9
9
  outputDir;
10
10
  artifacts;
11
+ pendingStaleRoutes = new Map();
11
12
  constructor(outputDir, artifacts) {
12
13
  this.outputDir = outputDir;
13
14
  this.artifacts = artifacts;
@@ -15,28 +16,23 @@ export class ApiReferenceGenerator {
15
16
  mergePages(registry, realPages) {
16
17
  return mergePageCatalog(realPages, registry.isEmpty ? [] : registry.syntheticPages());
17
18
  }
18
- async writePages(registry, apiBaseSlug, realPages, generatePage, writeAllowlist, cleanupStalePages) {
19
+ async writePages(registry, apiBaseSlug, realPages, generatePage, writeAllowlist, cleanupStalePages, writtenRoutes = new Map()) {
19
20
  const realSlugs = new Set(realPages.map((page) => page.slug));
20
- const nextRoutes = new Map();
21
+ const nextRoutes = writtenRoutes;
21
22
  const indexPage = registry
22
23
  .syntheticPages()
23
24
  .find((page) => page.slug === apiBaseSlug);
24
25
  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
- }
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);
40
36
  }
41
37
  for (const op of registry.all) {
42
38
  const methodUpper = op.method.toUpperCase();
@@ -53,43 +49,48 @@ export class ApiReferenceGenerator {
53
49
  console.log(chalk.yellow(`⚠️ API page ${op.slug} is shadowed by a hand-written page; skipping`));
54
50
  continue;
55
51
  }
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
- }
52
+ await generatePage(mdxFile, { apiOperation: op });
53
+ nextRoutes.set(`@openapi/${op.slug}`, op.slug);
63
54
  }
64
55
  await writeAllowlist();
65
56
  await cleanupStalePages(nextRoutes, realSlugs);
66
57
  if (registry.all.length > 0) {
67
58
  console.log(chalk.green(`🧩 Generated ${nextRoutes.size} API reference page(s)`));
68
59
  }
60
+ return nextRoutes;
69
61
  }
70
62
  async writeAllowlist(registry) {
71
63
  const target = resolveOutputPath(this.outputDir, "services", "openapi", "playground-allowlist.json");
72
64
  await fs.ensureDir(path.dirname(target));
73
65
  await writeFileAtomic(target, `${JSON.stringify(registry.allowlist(), null, 2)}\n`);
74
66
  }
75
- async cleanupStalePages(nextRoutes, realSlugs, removeOwnedRoute) {
67
+ async cleanupStalePages(nextRoutes, occupiedMdxSlugs, removeOwnedRoute, additionalPreviousRoutes = []) {
68
+ const previousRoutes = new Map([
69
+ ...this.artifacts.routesFor("openapi"),
70
+ ...additionalPreviousRoutes,
71
+ ...this.pendingStaleRoutes.values(),
72
+ ].map((route) => [route.source, route]));
73
+ await this.artifacts.replaceRoutesAndSave("openapi", [...nextRoutes].map(([source, slug]) => ({ source, slug })));
76
74
  const nextSlugs = new Set(nextRoutes.values());
77
- for (const previous of this.artifacts.routesFor("openapi")) {
75
+ for (const previous of previousRoutes.values()) {
78
76
  if (nextRoutes.has(previous.source) || nextSlugs.has(previous.slug)) {
77
+ this.pendingStaleRoutes.delete(previous.source);
79
78
  continue;
80
79
  }
81
80
  // A hand-written page may have taken ownership of this route since the
82
81
  // previous OpenAPI pass. Never remove an output now claimed by MDX.
83
- if (realSlugs.has(previous.slug))
82
+ if (occupiedMdxSlugs.has(previous.slug)) {
83
+ this.pendingStaleRoutes.delete(previous.source);
84
84
  continue;
85
+ }
86
+ this.pendingStaleRoutes.set(previous.source, previous);
85
87
  try {
86
88
  await removeOwnedRoute(previous.slug);
89
+ this.pendingStaleRoutes.delete(previous.source);
87
90
  }
88
- catch {
89
- // ignore
91
+ catch (error) {
92
+ throw error;
90
93
  }
91
94
  }
92
- this.artifacts.replaceRoutes("openapi", [...nextRoutes].map(([source, slug]) => ({ source, slug })));
93
- await this.artifacts.save();
94
95
  }
95
96
  }
@@ -6,8 +6,7 @@ interface AppStructureCallbacks {
6
6
  updateLlmsFiles(): Promise<void>;
7
7
  }
8
8
  interface StarterDocumentCallbacks {
9
- getAllMdxFiles(): Promise<string[]>;
10
- ensureSafeStarterPath(relativePath: string): Promise<string>;
9
+ writeStarterFilesIfEmpty(files: Iterable<readonly [string, string | Uint8Array]>): Promise<void>;
11
10
  }
12
11
  export declare class AppScaffolder {
13
12
  private readonly outputDir;
@@ -44,11 +44,6 @@ export class AppScaffolder {
44
44
  await callbacks.updateLlmsFiles();
45
45
  }
46
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
- }
47
+ await callbacks.writeStarterFilesIfEmpty(Object.entries(startingDocsStructure));
53
48
  }
54
49
  }
@@ -1,17 +1,18 @@
1
- import { GeneratedArtifacts } from "../lib/generated-artifacts.js";
1
+ import { GeneratedArtifacts, type RouteArtifact } from "../lib/generated-artifacts.js";
2
2
  import type { PageMeta } from "../lib/types.js";
3
3
  export declare class GeneratedRouteManager {
4
4
  private readonly outputDir;
5
5
  private readonly artifacts;
6
6
  private generatedSectionIndexSlugs;
7
+ private pendingStaleMdxRoutes;
7
8
  constructor(outputDir: string, artifacts: GeneratedArtifacts);
8
9
  private outputPath;
9
10
  routeForMdxSource(source: string): string | undefined;
10
11
  replaceMdxRoutes(realPages: PageMeta[]): Promise<void>;
11
12
  removeMdxRoute(source: string): Promise<void>;
12
13
  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>;
14
+ removeStaleMdxRoutes(realPages: PageMeta[], removeOwnedRoute: (slug: string) => Promise<void>, previousRoutes?: readonly RouteArtifact[]): Promise<void>;
15
+ cleanupStaleSectionIndexPages(nextSlugs: Set<string>, occupiedSlugs: Set<string>, removeEmptyDirs: (dir: string, stopDir: string) => Promise<void>): Promise<void>;
15
16
  /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
16
17
  removeEmptyDirsUpTo(dir: string, stopDir: string): Promise<void>;
17
18
  }
@@ -6,6 +6,7 @@ export class GeneratedRouteManager {
6
6
  outputDir;
7
7
  artifacts;
8
8
  generatedSectionIndexSlugs = new Set();
9
+ pendingStaleMdxRoutes = new Map();
9
10
  constructor(outputDir, artifacts) {
10
11
  this.outputDir = outputDir;
11
12
  this.artifacts = artifacts;
@@ -17,14 +18,12 @@ export class GeneratedRouteManager {
17
18
  return this.artifacts.routeFor("mdx", source);
18
19
  }
19
20
  async replaceMdxRoutes(realPages) {
20
- this.artifacts.replaceRoutes("mdx", realPages
21
+ await this.artifacts.replaceRoutesAndSave("mdx", realPages
21
22
  .filter((page) => page.slug !== "")
22
23
  .map((page) => ({ source: page.path, slug: page.slug })));
23
- await this.artifacts.save();
24
24
  }
25
25
  async removeMdxRoute(source) {
26
- this.artifacts.removeRoute("mdx", source);
27
- await this.artifacts.save();
26
+ await this.artifacts.removeRouteAndSave("mdx", source);
28
27
  }
29
28
  async removeOwnedRoute(slug) {
30
29
  if (!slug)
@@ -37,30 +36,54 @@ export class GeneratedRouteManager {
37
36
  ]);
38
37
  await this.removeEmptyDirsUpTo(routeDir, siteDir);
39
38
  }
40
- async removeStaleMdxRoutes(realPages, removeOwnedRoute) {
39
+ async removeStaleMdxRoutes(realPages, removeOwnedRoute, previousRoutes = this.artifacts.routesFor("mdx")) {
41
40
  const nextBySource = new Map(realPages
42
41
  .filter((page) => page.slug !== "")
43
42
  .map((page) => [page.path.replace(/\\/g, "/"), page.slug]));
44
43
  const nextSlugs = new Set(nextBySource.values());
45
- for (const previous of this.artifacts.routesFor("mdx")) {
44
+ const openApiSlugs = new Set(this.artifacts.routesFor("openapi").map((route) => route.slug));
45
+ for (const previous of previousRoutes) {
46
46
  if (nextBySource.get(previous.source) === previous.slug)
47
47
  continue;
48
48
  if (nextSlugs.has(previous.slug))
49
49
  continue;
50
- await removeOwnedRoute(previous.slug);
50
+ if (openApiSlugs.has(previous.slug))
51
+ continue;
52
+ this.pendingStaleMdxRoutes.set(previous.slug, previous);
53
+ }
54
+ const errors = [];
55
+ for (const [slug] of this.pendingStaleMdxRoutes) {
56
+ if (nextSlugs.has(slug)) {
57
+ this.pendingStaleMdxRoutes.delete(slug);
58
+ continue;
59
+ }
60
+ try {
61
+ if (openApiSlugs.has(slug)) {
62
+ await fs.remove(resolveOutputPath(this.outputDir, "app", "(site)", slug, "rss.xml"));
63
+ }
64
+ else {
65
+ await removeOwnedRoute(slug);
66
+ }
67
+ this.pendingStaleMdxRoutes.delete(slug);
68
+ }
69
+ catch (error) {
70
+ errors.push(error);
71
+ }
72
+ }
73
+ if (errors.length > 0) {
74
+ throw new AggregateError(errors, "Unable to remove stale MDX routes");
51
75
  }
52
76
  }
53
- async cleanupStaleSectionIndexPages(nextSlugs, removeEmptyDirs) {
77
+ async cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs, removeEmptyDirs) {
54
78
  for (const stale of this.generatedSectionIndexSlugs) {
55
79
  if (nextSlugs.has(stale))
56
80
  continue;
81
+ if (occupiedSlugs.has(stale))
82
+ continue;
57
83
  const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", stale, "page.tsx");
58
84
  try {
59
85
  if (!(await fs.pathExists(pagePath)))
60
86
  continue;
61
- const content = await fs.readFile(pagePath, "utf8");
62
- if (!content.includes("function SectionIndex()"))
63
- continue;
64
87
  await fs.remove(pagePath);
65
88
  await removeEmptyDirs(path.dirname(pagePath), this.outputPath("app", "(site)"));
66
89
  console.log(chalk.blue(`🧹 Removed stale section index redirect: /${stale}`));
@@ -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
  }
@@ -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>;