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,6 +1,5 @@
1
1
  import chalk from "chalk";
2
2
  import fs from "fs-extra";
3
- import path from "node:path";
4
3
  import { resolveOutputPath } from "../lib/output-safety.js";
5
4
  import { safeMatter, writeFileAtomic } from "../lib/utils.js";
6
5
  import { robotsTemplate } from "../templates/app/robots.js";
@@ -8,14 +7,13 @@ import { sitemapTemplate, } from "../templates/app/sitemap.js";
8
7
  import { llmsFullTemplate, } from "../templates/llms/llmsFull.js";
9
8
  import { llmsIndexTemplate } from "../templates/llms/llmsIndex.js";
10
9
  import { skillMdTemplate } from "../templates/llms/skillMd.js";
11
- export async function loadSiteUrl(rootDir) {
10
+ export async function loadSiteUrl(readConfigSource) {
12
11
  const fromEnv = process.env.NEXT_PUBLIC_SITE_URL?.trim();
13
12
  if (fromEnv)
14
13
  return fromEnv.replace(/\/$/, "");
15
- const configPath = path.join(rootDir, "config.json");
16
14
  try {
17
- if (await fs.pathExists(configPath)) {
18
- const content = await fs.readFile(configPath, "utf8");
15
+ const content = await readConfigSource();
16
+ if (content !== null) {
19
17
  const parsed = JSON.parse(content);
20
18
  if (typeof parsed.url === "string" && parsed.url.trim() !== "") {
21
19
  return parsed.url.trim().replace(/\/$/, "");
@@ -27,8 +25,7 @@ export async function loadSiteUrl(rootDir) {
27
25
  }
28
26
  return null;
29
27
  }
30
- export async function loadSiteMetadata(rootDir) {
31
- const configPath = path.join(rootDir, "config.json");
28
+ export async function loadSiteMetadata(readConfigSource) {
32
29
  let url = null;
33
30
  let name = "Documentation";
34
31
  let description = "";
@@ -36,8 +33,8 @@ export async function loadSiteMetadata(rootDir) {
36
33
  const fromEnv = process.env.NEXT_PUBLIC_SITE_URL?.trim();
37
34
  if (fromEnv)
38
35
  url = fromEnv.replace(/\/$/, "");
39
- if (await fs.pathExists(configPath)) {
40
- const content = await fs.readFile(configPath, "utf8");
36
+ const content = await readConfigSource();
37
+ if (content !== null) {
41
38
  const parsed = JSON.parse(content);
42
39
  if (!url && typeof parsed.url === "string" && parsed.url.trim() !== "") {
43
40
  url = parsed.url.trim().replace(/\/$/, "");
@@ -26,6 +26,7 @@ interface WatchCoordinatorOptions {
26
26
  doccupineConfigFile: string;
27
27
  sourceFs: SecureSourceFs;
28
28
  getOpenApiSpecs(): readonly NormalizedOpenApiSpec[];
29
+ getOpenApiSourceFiles(): readonly string[];
29
30
  callbacks: WatchCoordinatorCallbacks;
30
31
  }
31
32
  export declare class WatchCoordinator {
@@ -47,11 +48,11 @@ export declare class WatchCoordinator {
47
48
  private enqueueMutation;
48
49
  private waitForWatcherReady;
49
50
  private captureSourceSnapshot;
50
- establishSourceSnapshot(): Promise<void>;
51
+ establishSourceSnapshot(projectSourceStates?: Readonly<Record<string, string>>, openApiSourceState?: string, doccupineSourceState?: string): Promise<void>;
51
52
  private reconcileWatchedSources;
52
53
  startWatching(): Promise<void>;
53
54
  private setupPublicWatcher;
54
- syncOpenApiSpecWatcher(specs: readonly NormalizedOpenApiSpec[]): Promise<void>;
55
+ syncOpenApiSpecWatcher(specs: readonly NormalizedOpenApiSpec[], sourceFiles?: readonly string[]): Promise<void>;
55
56
  stop(): Promise<void>;
56
57
  }
57
58
  export {};
@@ -53,14 +53,16 @@ export class WatchCoordinator {
53
53
  });
54
54
  }
55
55
  async captureSourceSnapshot() {
56
- const { analyticsConfigFile, configFiles, doccupineConfigFile, fontConfigFile, getOpenApiSpecs, rootDir, sourceFs, watchDir, } = this.options;
56
+ const { analyticsConfigFile, configFiles, doccupineConfigFile, fontConfigFile, getOpenApiSpecs, getOpenApiSourceFiles, rootDir, sourceFs, watchDir, } = this.options;
57
57
  const configs = Object.fromEntries(await Promise.all(configFiles.map(async (fileName) => [
58
58
  fileName,
59
59
  await sourceFs.pathState(path.join(rootDir, fileName), true),
60
60
  ])));
61
- const openapi = (await Promise.all(getOpenApiSpecs().map(async (spec) => {
62
- const specPath = path.resolve(rootDir, spec.file);
63
- return `${specPath}:${await sourceFs.pathState(specPath, true)}`;
61
+ const openApiSourceFiles = getOpenApiSourceFiles();
62
+ const openapi = (await Promise.all((openApiSourceFiles.length > 0
63
+ ? openApiSourceFiles
64
+ : getOpenApiSpecs().map((spec) => path.resolve(rootDir, spec.file))).map(async (sourcePath) => {
65
+ return `${sourcePath}:${await sourceFs.pathState(sourcePath, true)}`;
64
66
  }))).join("\n");
65
67
  return {
66
68
  mdx: await sourceFs.treeState(watchDir, (relativePath) => relativePath.toLowerCase().endsWith(".mdx"), true),
@@ -72,8 +74,21 @@ export class WatchCoordinator {
72
74
  openapi,
73
75
  };
74
76
  }
75
- async establishSourceSnapshot() {
76
- this.sourceSnapshot = await this.captureSourceSnapshot();
77
+ async establishSourceSnapshot(projectSourceStates = {}, openApiSourceState, doccupineSourceState) {
78
+ const snapshot = await this.captureSourceSnapshot();
79
+ for (const fileName of this.options.configFiles) {
80
+ if (projectSourceStates[fileName] !== undefined) {
81
+ snapshot.configs[fileName] = projectSourceStates[fileName];
82
+ }
83
+ }
84
+ snapshot.font =
85
+ projectSourceStates[this.options.fontConfigFile] ?? snapshot.font;
86
+ snapshot.analytics =
87
+ projectSourceStates[this.options.analyticsConfigFile] ??
88
+ snapshot.analytics;
89
+ snapshot.openapi = openApiSourceState ?? snapshot.openapi;
90
+ snapshot.doccupine = doccupineSourceState ?? snapshot.doccupine;
91
+ this.sourceSnapshot = snapshot;
77
92
  }
78
93
  async reconcileWatchedSources(previous, current) {
79
94
  const { analyticsConfigFile, callbacks, configFiles, doccupineConfigFile, fontConfigFile, getOpenApiSpecs, rootDir, } = this.options;
@@ -127,8 +142,7 @@ export class WatchCoordinator {
127
142
  }
128
143
  await callbacks.copyPublicFiles();
129
144
  }
130
- if (!doccupineChanged &&
131
- getOpenApiSpecs().length > 0 &&
145
+ if (getOpenApiSpecs().length > 0 &&
132
146
  (previous === null || previous.openapi !== current.openapi)) {
133
147
  await callbacks.handleOpenApiChange();
134
148
  }
@@ -319,7 +333,7 @@ export class WatchCoordinator {
319
333
  this.enqueueMutation("Error reconciling watched sources", async () => {
320
334
  const current = await this.captureSourceSnapshot();
321
335
  await this.reconcileWatchedSources(this.sourceSnapshot, current);
322
- this.sourceSnapshot = await this.captureSourceSnapshot();
336
+ this.sourceSnapshot = current;
323
337
  });
324
338
  await this.mutationQueue;
325
339
  }
@@ -363,7 +377,7 @@ export class WatchCoordinator {
363
377
  });
364
378
  return this.publicWatcher;
365
379
  }
366
- async syncOpenApiSpecWatcher(specs) {
380
+ async syncOpenApiSpecWatcher(specs, sourceFiles = []) {
367
381
  const previousWatcher = this.openApiWatcher;
368
382
  this.openApiWatcher = null;
369
383
  if (previousWatcher)
@@ -371,7 +385,11 @@ export class WatchCoordinator {
371
385
  if (this.stopping || specs.length === 0)
372
386
  return;
373
387
  const { callbacks, rootDir } = this.options;
374
- const specPaths = specs.map((spec) => path.resolve(rootDir, spec.file));
388
+ const specPaths = [
389
+ ...new Set(sourceFiles.length > 0
390
+ ? sourceFiles
391
+ : specs.map((spec) => path.resolve(rootDir, spec.file))),
392
+ ];
375
393
  const watcher = chokidar.watch(specPaths, {
376
394
  persistent: true,
377
395
  ignoreInitial: true,
@@ -27,6 +27,7 @@ export declare function normalizeConfigPaths(config: DoccupineConfig, rootDir?:
27
27
  };
28
28
  export declare class ConfigManager {
29
29
  private configPath;
30
+ private projectRoot;
30
31
  constructor(configPath?: string);
31
32
  loadConfig(): Promise<DoccupineConfig | null>;
32
33
  saveConfig(config: DoccupineConfig): Promise<void>;
@@ -1,4 +1,7 @@
1
1
  import fs from "fs-extra";
2
+ import { randomBytes } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { open, unlink } from "node:fs/promises";
2
5
  import path from "path";
3
6
  import chalk from "chalk";
4
7
  import prompts from "prompts";
@@ -6,6 +9,181 @@ import { isPathInside } from "./output-safety.js";
6
9
  function pathsOverlap(a, b) {
7
10
  return isPathInside(a, b) || isPathInside(b, a);
8
11
  }
12
+ function errorCode(error) {
13
+ return error && typeof error === "object" && "code" in error
14
+ ? String(error.code)
15
+ : undefined;
16
+ }
17
+ function sameFile(left, right) {
18
+ return left.dev === right.dev && left.ino === right.ino;
19
+ }
20
+ function configPathError(configPath, detail) {
21
+ return new Error(`Refusing to use ${configPath}: ${detail}`);
22
+ }
23
+ async function inspectConfigPath(projectRoot, configPath, allowMissingAncestor) {
24
+ if (!isPathInside(projectRoot, configPath)) {
25
+ throw configPathError(configPath, `the configuration path is outside the project root ${projectRoot}.`);
26
+ }
27
+ const relativePath = path.relative(projectRoot, configPath);
28
+ const paths = [
29
+ projectRoot,
30
+ ...relativePath
31
+ .split(path.sep)
32
+ .filter(Boolean)
33
+ .map((_, index, components) => path.join(projectRoot, ...components.slice(0, index + 1))),
34
+ ];
35
+ const entries = [];
36
+ for (const [index, currentPath] of paths.entries()) {
37
+ const isFinal = index === paths.length - 1;
38
+ let stat;
39
+ try {
40
+ stat = await fs.lstat(currentPath);
41
+ }
42
+ catch (error) {
43
+ if (errorCode(error) === "ENOENT") {
44
+ if (allowMissingAncestor)
45
+ return null;
46
+ if (isFinal)
47
+ return { entries };
48
+ }
49
+ throw error;
50
+ }
51
+ if (stat.isSymbolicLink()) {
52
+ throw configPathError(configPath, `${currentPath} is a symbolic link. Replace it with a real file or directory inside the project root.`);
53
+ }
54
+ if (!isFinal && !stat.isDirectory()) {
55
+ throw configPathError(configPath, `${currentPath} is not a directory.`);
56
+ }
57
+ entries.push({ filePath: currentPath, stat });
58
+ }
59
+ return {
60
+ entries,
61
+ finalStat: entries.at(-1)?.stat,
62
+ };
63
+ }
64
+ async function assertPathEntriesUnchanged(configPath, entries) {
65
+ for (const entry of entries) {
66
+ let currentStat;
67
+ try {
68
+ currentStat = await fs.lstat(entry.filePath);
69
+ }
70
+ catch {
71
+ throw configPathError(configPath, `${entry.filePath} changed during the configuration operation.`);
72
+ }
73
+ if (currentStat.isSymbolicLink() || !sameFile(entry.stat, currentStat)) {
74
+ throw configPathError(configPath, `${entry.filePath} changed during the configuration operation.`);
75
+ }
76
+ }
77
+ }
78
+ async function readConfigFile(projectRoot, configPath) {
79
+ const inspected = await inspectConfigPath(projectRoot, configPath, true);
80
+ if (!inspected)
81
+ return null;
82
+ if (!inspected.finalStat?.isFile()) {
83
+ throw configPathError(configPath, "expected a regular configuration file.");
84
+ }
85
+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
86
+ let handle;
87
+ try {
88
+ handle = await open(configPath, constants.O_RDONLY | noFollow);
89
+ }
90
+ catch (error) {
91
+ if (errorCode(error) === "ELOOP") {
92
+ throw configPathError(configPath, "the configuration file became a symbolic link while it was being opened.");
93
+ }
94
+ throw error;
95
+ }
96
+ try {
97
+ const beforeRead = await handle.stat();
98
+ if (!beforeRead.isFile() || !sameFile(inspected.finalStat, beforeRead)) {
99
+ throw configPathError(configPath, "the configuration file changed while it was being opened.");
100
+ }
101
+ await assertPathEntriesUnchanged(configPath, inspected.entries);
102
+ const content = await handle.readFile("utf8");
103
+ const afterRead = await handle.stat();
104
+ if (!sameFile(beforeRead, afterRead) ||
105
+ beforeRead.size !== afterRead.size ||
106
+ beforeRead.mtimeMs !== afterRead.mtimeMs ||
107
+ beforeRead.ctimeMs !== afterRead.ctimeMs) {
108
+ throw configPathError(configPath, "the configuration file changed while it was being read.");
109
+ }
110
+ await assertPathEntriesUnchanged(configPath, inspected.entries);
111
+ return content;
112
+ }
113
+ finally {
114
+ await handle.close();
115
+ }
116
+ }
117
+ async function createConfigTempFile(configPath, mode) {
118
+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
119
+ const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow;
120
+ for (let attempt = 0; attempt < 10; attempt += 1) {
121
+ const tempPath = path.join(path.dirname(configPath), `.doccupine-config-${process.pid}-${randomBytes(16).toString("hex")}.tmp`);
122
+ try {
123
+ return { handle: await open(tempPath, flags, mode), tempPath };
124
+ }
125
+ catch (error) {
126
+ if (errorCode(error) !== "EEXIST")
127
+ throw error;
128
+ }
129
+ }
130
+ throw new Error(`Unable to create a unique temporary file for ${configPath}`);
131
+ }
132
+ async function removeConfigTempFile(tempPath) {
133
+ try {
134
+ await unlink(tempPath);
135
+ }
136
+ catch (error) {
137
+ if (errorCode(error) !== "ENOENT")
138
+ throw error;
139
+ }
140
+ }
141
+ async function writeConfigFileAtomic(projectRoot, configPath, content) {
142
+ const inspected = await inspectConfigPath(projectRoot, configPath, false);
143
+ if (inspected?.finalStat && !inspected.finalStat.isFile()) {
144
+ throw configPathError(configPath, "expected a regular configuration file.");
145
+ }
146
+ const parentEntries = inspected?.entries.filter((entry) => entry.filePath !== configPath) ?? [];
147
+ const mode = inspected?.finalStat?.isFile()
148
+ ? inspected.finalStat.mode & 0o777
149
+ : 0o666;
150
+ let handle;
151
+ let tempPath;
152
+ try {
153
+ ({ handle, tempPath } = await createConfigTempFile(configPath, mode));
154
+ if (inspected?.finalStat?.isFile())
155
+ await handle.chmod(mode);
156
+ await assertPathEntriesUnchanged(configPath, parentEntries);
157
+ await inspectConfigPath(projectRoot, configPath, false);
158
+ await handle.writeFile(content, "utf8");
159
+ await handle.sync();
160
+ await handle.close();
161
+ handle = undefined;
162
+ await assertPathEntriesUnchanged(configPath, parentEntries);
163
+ await inspectConfigPath(projectRoot, configPath, false);
164
+ await fs.rename(tempPath, configPath);
165
+ tempPath = undefined;
166
+ }
167
+ catch (error) {
168
+ if (handle) {
169
+ try {
170
+ await handle.close();
171
+ }
172
+ catch {
173
+ // Preserve the original write error.
174
+ }
175
+ }
176
+ if (tempPath) {
177
+ try {
178
+ await removeConfigTempFile(tempPath);
179
+ }
180
+ catch {
181
+ // Cleanup is best effort and must not hide the original error.
182
+ }
183
+ }
184
+ throw error;
185
+ }
186
+ }
9
187
  function isValidOpenApiConfig(value) {
10
188
  if (value === undefined || typeof value === "string")
11
189
  return true;
@@ -177,32 +355,36 @@ export function normalizeConfigPaths(config, rootDir = process.cwd()) {
177
355
  }
178
356
  export class ConfigManager {
179
357
  configPath;
358
+ projectRoot;
180
359
  constructor(configPath = "doccupine.json") {
181
- this.configPath = path.resolve(process.cwd(), configPath);
360
+ this.projectRoot = path.resolve(process.cwd());
361
+ this.configPath = path.resolve(this.projectRoot, configPath);
182
362
  }
183
363
  async loadConfig() {
184
364
  try {
185
- if (await fs.pathExists(this.configPath)) {
186
- const configContent = await fs.readFile(this.configPath, "utf8");
187
- const config = validateConfig(JSON.parse(configContent));
188
- console.log(chalk.blue("📄 Using existing configuration from doccupine.json"));
189
- return config;
190
- }
365
+ const configContent = await readConfigFile(this.projectRoot, this.configPath);
366
+ if (configContent === null)
367
+ return null;
368
+ const config = validateConfig(JSON.parse(configContent), this.projectRoot);
369
+ console.log(chalk.blue("📄 Using existing configuration from doccupine.json"));
370
+ return config;
191
371
  }
192
372
  catch (error) {
193
- if (await fs.pathExists(this.configPath)) {
194
- throw new Error(`Unable to use ${this.configPath}: ${error instanceof Error ? error.message : String(error)}. Run "doccupine config --reset" to repair the configuration.`);
195
- }
373
+ const message = error instanceof Error ? error.message : String(error);
374
+ const symlinkRepair = message.includes("symbolic link")
375
+ ? " Remove or replace the symbolic link first."
376
+ : "";
377
+ throw new Error(`Unable to use ${this.configPath}: ${message}.${symlinkRepair} Run "doccupine config --reset" to repair the configuration.`);
196
378
  }
197
- return null;
198
379
  }
199
380
  async saveConfig(config) {
200
381
  try {
201
- await fs.writeFile(this.configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
382
+ await writeConfigFileAtomic(this.projectRoot, this.configPath, `${JSON.stringify(config, null, 2)}\n`);
202
383
  console.log(chalk.green("💾 Configuration saved to doccupine.json"));
203
384
  }
204
385
  catch (error) {
205
386
  console.error(chalk.red("❌ Error saving config file:"), error);
387
+ throw error;
206
388
  }
207
389
  }
208
390
  async promptForConfig(existingConfig) {
@@ -1,5 +1,5 @@
1
1
  export type RouteOwnerKind = "mdx" | "openapi";
2
- interface RouteArtifact {
2
+ export interface RouteArtifact {
3
3
  kind: RouteOwnerKind;
4
4
  source: string;
5
5
  slug: string;
@@ -15,15 +15,21 @@ export declare class GeneratedArtifacts {
15
15
  load(): Promise<void>;
16
16
  routeFor(kind: RouteOwnerKind, source: string): string | undefined;
17
17
  routesFor(kind: RouteOwnerKind): RouteArtifact[];
18
+ private routesWithReplacement;
18
19
  replaceRoutes(kind: RouteOwnerKind, routes: Iterable<{
19
20
  source: string;
20
21
  slug: string;
21
22
  }>): void;
23
+ replaceRoutesAndSave(kind: RouteOwnerKind, routes: Iterable<{
24
+ source: string;
25
+ slug: string;
26
+ }>): Promise<void>;
22
27
  removeRoute(kind: RouteOwnerKind, source: string): void;
28
+ removeRouteAndSave(kind: RouteOwnerKind, source: string): Promise<void>;
23
29
  llmsPageFiles(): Set<string>;
24
30
  replaceLlmsPageFiles(files: Iterable<string>): void;
25
31
  publicFiles(): Set<string>;
26
32
  replacePublicFiles(files: Iterable<string>): void;
33
+ private writeManifest;
27
34
  save(): Promise<void>;
28
35
  }
29
- export {};
@@ -119,22 +119,38 @@ export class GeneratedArtifacts {
119
119
  routesFor(kind) {
120
120
  return [...this.routes.values()].filter((route) => route.kind === kind);
121
121
  }
122
- replaceRoutes(kind, routes) {
123
- for (const [key, route] of this.routes) {
122
+ routesWithReplacement(kind, routes) {
123
+ const next = new Map(this.routes);
124
+ for (const [key, route] of next) {
124
125
  if (route.kind === kind)
125
- this.routes.delete(key);
126
+ next.delete(key);
126
127
  }
127
128
  for (const value of routes) {
128
129
  const route = normalizeRoute({ kind, ...value });
129
130
  if (!route) {
130
131
  throw new Error(`Refusing to record unsafe ${kind} route ownership`);
131
132
  }
132
- this.routes.set(this.routeKey(kind, route.source), route);
133
+ next.set(this.routeKey(kind, route.source), route);
133
134
  }
135
+ return next;
136
+ }
137
+ replaceRoutes(kind, routes) {
138
+ this.routes = this.routesWithReplacement(kind, routes);
139
+ }
140
+ async replaceRoutesAndSave(kind, routes) {
141
+ const next = this.routesWithReplacement(kind, routes);
142
+ await this.writeManifest(next);
143
+ this.routes = next;
134
144
  }
135
145
  removeRoute(kind, source) {
136
146
  this.routes.delete(this.routeKey(kind, source));
137
147
  }
148
+ async removeRouteAndSave(kind, source) {
149
+ const next = new Map(this.routes);
150
+ next.delete(this.routeKey(kind, source));
151
+ await this.writeManifest(next);
152
+ this.routes = next;
153
+ }
138
154
  llmsPageFiles() {
139
155
  return new Set(this.llmsFiles);
140
156
  }
@@ -161,13 +177,16 @@ export class GeneratedArtifacts {
161
177
  }
162
178
  this.publicFilePaths = next;
163
179
  }
164
- async save() {
180
+ async writeManifest(routes) {
165
181
  const manifest = {
166
182
  schemaVersion: 2,
167
- routes: [...this.routes.values()].sort((a, b) => `${a.kind}:${a.source}`.localeCompare(`${b.kind}:${b.source}`)),
183
+ routes: [...routes.values()].sort((a, b) => `${a.kind}:${a.source}`.localeCompare(`${b.kind}:${b.source}`)),
168
184
  llmsPageFiles: [...this.llmsFiles].sort(),
169
185
  publicFiles: [...this.publicFilePaths].sort(),
170
186
  };
171
187
  await writeFileAtomic(this.manifestPath(MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`);
172
188
  }
189
+ async save() {
190
+ await this.writeManifest(this.routes);
191
+ }
173
192
  }
@@ -33,8 +33,12 @@ export declare class OpenApiRegistry {
33
33
  private pages;
34
34
  private bodies;
35
35
  private allowlistEntries;
36
+ private sourceFilePaths;
37
+ private sourceFingerprintValue;
36
38
  get all(): OperationDescriptor[];
37
39
  get isEmpty(): boolean;
40
+ get sourceFiles(): readonly string[];
41
+ get sourceFingerprint(): string;
38
42
  load(specs: NormalizedOpenApiSpec[], rootDir: string, apiBaseSlug?: string): Promise<void>;
39
43
  /** Fresh copies of the synthetic pages (caller may mutate/spread safely). */
40
44
  syntheticPages(): PageMeta[];
@@ -1,5 +1,6 @@
1
1
  import path from "path";
2
2
  import net from "node:net";
3
+ import { createHash } from "node:crypto";
3
4
  import { constants } from "node:fs";
4
5
  import fs from "node:fs/promises";
5
6
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -321,7 +322,18 @@ async function readOpenApiSnapshot(referenceRootRealPath, realPath, reference) {
321
322
  openedStat.ino !== currentStat.ino) {
322
323
  throw new Error(`OpenAPI file "${reference}" changed while being read`);
323
324
  }
324
- return await handle.readFile();
325
+ const contents = await handle.readFile();
326
+ const afterRead = await handle.stat();
327
+ if (openedStat.size !== afterRead.size ||
328
+ openedStat.mtimeMs !== afterRead.mtimeMs ||
329
+ openedStat.ctimeMs !== afterRead.ctimeMs) {
330
+ throw new Error(`OpenAPI file "${reference}" changed while being read`);
331
+ }
332
+ const hash = createHash("sha256").update(contents).digest("hex");
333
+ return {
334
+ contents,
335
+ state: `file:${openedStat.size}:${openedStat.mtimeMs}:${openedStat.dev}:${openedStat.ino}:${hash}`,
336
+ };
325
337
  }
326
338
  finally {
327
339
  await handle.close();
@@ -362,6 +374,7 @@ async function snapshotOpenApiDocuments(rootFile) {
362
374
  const referenceRootRealPath = path.dirname(rootFile);
363
375
  const byRealPath = new Map();
364
376
  const snapshots = new Map();
377
+ const sourceStates = new Map();
365
378
  const visit = async (candidate, reference, configuredRoot = false) => {
366
379
  if (!configuredRoot) {
367
380
  assertAllowedOpenApiReference(referenceRootRealPath, candidate, reference);
@@ -373,7 +386,8 @@ async function snapshotOpenApiDocuments(rootFile) {
373
386
  const existing = byRealPath.get(realPath);
374
387
  if (existing)
375
388
  return existing.url;
376
- const contents = await readOpenApiSnapshot(referenceRootRealPath, realPath, reference);
389
+ const { contents, state } = await readOpenApiSnapshot(referenceRootRealPath, realPath, reference);
390
+ sourceStates.set(realPath, state);
377
391
  const document = await parseOpenApiSnapshot(realPath, contents);
378
392
  const snapshotUrl = `file:///__doccupine_openapi_snapshot__/${byRealPath.size}.json`;
379
393
  byRealPath.set(realPath, { document, url: snapshotUrl });
@@ -401,7 +415,7 @@ async function snapshotOpenApiDocuments(rootFile) {
401
415
  return snapshotUrl;
402
416
  };
403
417
  const rootUrl = await visit(rootFile, rootFile, true);
404
- return { rootDocument: snapshots.get(rootUrl), snapshots };
418
+ return { rootDocument: snapshots.get(rootUrl), snapshots, sourceStates };
405
419
  }
406
420
  async function dereferenceOpenApiSnapshots(rootDocument, snapshots) {
407
421
  const snapshotResolver = parserFileResolver({
@@ -437,17 +451,26 @@ export class OpenApiRegistry {
437
451
  pages = [];
438
452
  bodies = new Map();
439
453
  allowlistEntries = [];
454
+ sourceFilePaths = [];
455
+ sourceFingerprintValue = "";
440
456
  get all() {
441
457
  return this.operations;
442
458
  }
443
459
  get isEmpty() {
444
460
  return this.operations.length === 0;
445
461
  }
462
+ get sourceFiles() {
463
+ return this.sourceFilePaths;
464
+ }
465
+ get sourceFingerprint() {
466
+ return this.sourceFingerprintValue;
467
+ }
446
468
  async load(specs, rootDir, apiBaseSlug = DEFAULT_API_BASE_SLUG) {
447
469
  const next = new OpenApiRegistry();
448
470
  const multi = specs.length > 1;
449
471
  const usedSlugs = new Set();
450
472
  const allowlistKeys = new Set();
473
+ const sourceStates = new Map();
451
474
  const rootRealPath = specs.length > 0 ? await fs.realpath(rootDir) : path.resolve(rootDir);
452
475
  for (const spec of specs) {
453
476
  let doc;
@@ -459,7 +482,10 @@ export class OpenApiRegistry {
459
482
  ? path.normalize(spec.file)
460
483
  : path.resolve(rootDir, spec.file);
461
484
  const absolute = await resolveLocalOpenApiFile(rootRealPath, configuredPath, spec.file, "rootDir");
462
- const { rootDocument, snapshots } = await snapshotOpenApiDocuments(absolute);
485
+ const { rootDocument, snapshots, sourceStates: capturedSourceStates, } = await snapshotOpenApiDocuments(absolute);
486
+ for (const [sourcePath, state] of capturedSourceStates) {
487
+ sourceStates.set(sourcePath, state);
488
+ }
463
489
  doc = await dereferenceOpenApiSnapshots(rootDocument, snapshots);
464
490
  }
465
491
  catch (error) {
@@ -472,6 +498,10 @@ export class OpenApiRegistry {
472
498
  throw new Error(`Failed to process OpenAPI spec "${spec.file}": ${error instanceof Error ? error.message : String(error)}`, { cause: error });
473
499
  }
474
500
  }
501
+ next.sourceFilePaths = [...sourceStates.keys()].sort();
502
+ next.sourceFingerprintValue = next.sourceFilePaths
503
+ .map((sourcePath) => `${sourcePath}:${sourceStates.get(sourcePath)}`)
504
+ .join("\n");
475
505
  if (next.operations.length > 0) {
476
506
  const body = buildApiIndexBody(next.operations);
477
507
  next.pages.unshift({
@@ -493,6 +523,8 @@ export class OpenApiRegistry {
493
523
  this.pages = next.pages;
494
524
  this.bodies = next.bodies;
495
525
  this.allowlistEntries = next.allowlistEntries;
526
+ this.sourceFilePaths = next.sourceFilePaths;
527
+ this.sourceFingerprintValue = next.sourceFingerprintValue;
496
528
  }
497
529
  /** Fresh copies of the synthetic pages (caller may mutate/spread safely). */
498
530
  syntheticPages() {