doccupine 0.0.145 → 0.0.146

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,7 @@ import chalk from "chalk";
5
5
  import { rootLayoutTemplate, siteLayoutTemplate } from "./lib/layout.js";
6
6
  import { normalizeOpenApiConfig, validateConfig, } from "./lib/config-manager.js";
7
7
  import { GeneratedArtifacts, } from "./lib/generated-artifacts.js";
8
- import { claimOutputDirectory, readOutputFileIfPresent, resolveOutputPath, } from "./lib/output-safety.js";
8
+ import { claimOutputDirectory, resolveOutputPath, } from "./lib/output-safety.js";
9
9
  import { OpenApiRegistry, DEFAULT_API_BASE_SLUG } from "./lib/openapi.js";
10
10
  import { getFullSlug, safeMatter, writeFileAtomic } from "./lib/utils.js";
11
11
  import { nextConfigTemplate } from "./templates/next.config.js";
@@ -13,13 +13,17 @@ import { proxyTemplate } from "./templates/proxy.js";
13
13
  import { SecureSourceFs } from "./generator/secure-source-fs.js";
14
14
  import { AppScaffolder } from "./generator/app-scaffolder.js";
15
15
  import { ApiReferenceGenerator } from "./generator/api-reference-generator.js";
16
+ import { GeneratedPagePublisher } from "./generator/generated-page-publisher.js";
16
17
  import { GeneratedRouteManager } from "./generator/generated-route-manager.js";
18
+ import { MdxPassBuilder, } from "./generator/mdx-pass-builder.js";
17
19
  import { ProjectConfigRepository } from "./generator/project-config-repository.js";
18
20
  import { PublicAssetManager } from "./generator/public-asset-manager.js";
19
21
  import { WatchCoordinator } from "./generator/watch-coordinator.js";
22
+ import { SectionIndexGenerator } from "./generator/section-index-generator.js";
23
+ import { OpenApiRefreshCoordinator, } from "./generator/openapi-refresh-coordinator.js";
20
24
  import { addApiReferenceSection, determineSectionRoute, discoverSections, } from "./generator/section-resolver.js";
21
- import { renderHomepage, renderMdxPage, renderSectionPage, } from "./generator/page-renderer.js";
22
- import { buildRealPagesMeta as buildRealPageCatalog, mergePages as mergePageCatalog, parseMdxPageMeta, RouteCollisionError, } from "./generator/page-catalog.js";
25
+ import { renderHomepage, } from "./generator/page-renderer.js";
26
+ import { mergePages as mergePageCatalog, RouteCollisionError, } from "./generator/page-catalog.js";
23
27
  import { loadSiteMetadata, loadSiteUrl as loadSiteUrlArtifact, writeLlmsFiles, writeRobots, writeSitemap, } from "./generator/site-artifacts.js";
24
28
  export class MDXToNextJSGenerator {
25
29
  watchDir;
@@ -47,7 +51,11 @@ export class MDXToNextJSGenerator {
47
51
  sourceFs;
48
52
  appScaffolder;
49
53
  apiReferenceGenerator;
54
+ generatedPagePublisher;
50
55
  generatedRouteManager;
56
+ mdxPassBuilder;
57
+ openApiRefreshCoordinator;
58
+ sectionIndexGenerator;
51
59
  projectConfigRepository;
52
60
  publicAssetManager;
53
61
  watchCoordinator;
@@ -67,6 +75,17 @@ export class MDXToNextJSGenerator {
67
75
  this.appScaffolder = new AppScaffolder(this.outputDir);
68
76
  this.apiReferenceGenerator = new ApiReferenceGenerator(this.outputDir, this.artifacts);
69
77
  this.generatedRouteManager = new GeneratedRouteManager(this.outputDir, this.artifacts);
78
+ this.generatedPagePublisher = new GeneratedPagePublisher(this.outputDir, this.generatedRouteManager);
79
+ this.sectionIndexGenerator = new SectionIndexGenerator(this.outputDir, this.generatedRouteManager);
80
+ this.mdxPassBuilder = new MdxPassBuilder({
81
+ sourceFs: this.sourceFs,
82
+ getAllMdxFiles: () => this.getAllMDXFiles(),
83
+ getSections: () => this.sectionsConfig,
84
+ loadSectionsConfig: () => this.loadSectionsConfig(),
85
+ withApiReferenceSection: (sections) => this.withApiReferenceSection(sections),
86
+ determineSectionForFile: (filePath, frontmatter, sections) => this.determineSectionForFile(filePath, frontmatter, sections),
87
+ resolveHttpMethod: (reference) => this.apiRegistry.lookup(reference)?.method,
88
+ });
70
89
  this.projectConfigRepository = new ProjectConfigRepository(this.rootDir, this.outputDir, this.sourceFs, this.configFiles, this.fontConfigFile, this.analyticsConfigFile);
71
90
  this.publicAssetManager = new PublicAssetManager(this.rootDir, this.outputDir, this.artifacts, this.sourceFs);
72
91
  this.watchCoordinator = new WatchCoordinator({
@@ -97,6 +116,33 @@ export class MDXToNextJSGenerator {
97
116
  processAllMDXFiles: () => this.reconcileMdxSources(),
98
117
  },
99
118
  });
119
+ this.openApiRefreshCoordinator = new OpenApiRefreshCoordinator({
120
+ rootDir: this.rootDir,
121
+ watchDir: this.watchDir,
122
+ outputDir: this.outputDir,
123
+ configFile: this.doccupineConfigFile,
124
+ apiBaseSlug: this.apiBaseSlug,
125
+ sourceFs: this.sourceFs,
126
+ getRegistry: () => this.apiRegistry,
127
+ setRegistry: (registry) => {
128
+ this.apiRegistry = registry;
129
+ },
130
+ getSpecs: () => this.openApiSpecs,
131
+ setSpecs: (specs) => {
132
+ this.openApiSpecs = specs;
133
+ },
134
+ getSections: () => this.sectionsConfig,
135
+ setSections: (sections) => {
136
+ this.sectionsConfig = sections;
137
+ },
138
+ getOpenApiRoutes: () => this.artifacts.routesFor("openapi"),
139
+ getSuccessfulMdxPages: () => [...this.successfulMdxPages.values()],
140
+ resolveSections: () => this.resolveSections(),
141
+ writeApiPages: (realPages, options) => this.writeApiPages(realPages, options),
142
+ refreshSiteAggregates: () => this.refreshSiteAggregates(),
143
+ syncWatcher: () => this.syncOpenApiSpecWatcher(),
144
+ removeOwnedRoute: (slug) => this.removeOwnedRoute(slug),
145
+ });
100
146
  }
101
147
  outputPath(...segments) {
102
148
  return resolveOutputPath(this.outputDir, ...segments);
@@ -245,8 +291,8 @@ export class MDXToNextJSGenerator {
245
291
  async reconcileMdxSources() {
246
292
  await this.processAllMDXFiles();
247
293
  }
248
- determineSectionForFile(filePath, frontmatter) {
249
- return determineSectionRoute(filePath, frontmatter, this.sectionsConfig);
294
+ determineSectionForFile(filePath, frontmatter, sections = this.sectionsConfig) {
295
+ return determineSectionRoute(filePath, frontmatter, sections);
250
296
  }
251
297
  async handleConfigFileChange(filePath) {
252
298
  const fileName = path.basename(filePath);
@@ -360,54 +406,18 @@ export class MDXToNextJSGenerator {
360
406
  async startWatching() {
361
407
  return this.watchCoordinator.startWatching();
362
408
  }
363
- async parseMDXFile(file, source) {
364
- return parseMdxPageMeta(file, source
365
- ? async () => source
366
- : (filePath) => this.readMdxSourceFile(filePath), (filePath, frontmatter) => this.determineSectionForFile(filePath, frontmatter), (reference) => this.apiRegistry.lookup(reference)?.method);
367
- }
368
409
  async captureMdxPass(files, seededSources = new Map(), refreshSections = false) {
369
- const resolvedFiles = files ?? (await this.getAllMDXFiles());
370
- const sources = new Map(seededSources);
371
- await Promise.all(resolvedFiles.map(async (file) => {
372
- const source = file.replace(/\\/g, "/");
373
- if (!sources.has(source)) {
374
- sources.set(source, await this.readMdxSourceFile(file));
375
- }
376
- }));
377
- if (refreshSections) {
378
- const configuredSections = await this.loadSectionsConfig();
379
- if (configuredSections !== null) {
380
- this.sectionsConfig = this.withApiReferenceSection(configuredSections);
381
- }
382
- else {
383
- const documents = resolvedFiles.map((filePath) => {
384
- const source = sources.get(filePath.replace(/\\/g, "/"));
385
- if (!source)
386
- throw new Error(`Unable to snapshot ${filePath}`);
387
- return {
388
- filePath,
389
- frontmatter: safeMatter(source.content, filePath).data,
390
- };
391
- });
392
- this.sectionsConfig = this.withApiReferenceSection(discoverSections(documents));
393
- }
394
- }
395
- const pages = await buildRealPageCatalog(resolvedFiles, (file) => {
396
- const source = sources.get(file.replace(/\\/g, "/"));
397
- if (!source)
398
- throw new Error(`Unable to snapshot ${file}`);
399
- return this.parseMDXFile(file, source);
400
- });
401
- return { files: resolvedFiles, pages, sources };
410
+ return this.mdxPassBuilder.capture(files, seededSources, refreshSections);
402
411
  }
403
412
  async buildRealPagesMeta() {
404
413
  return (await this.captureMdxPass()).pages;
405
414
  }
406
415
  async buildAllPagesMeta() {
407
416
  const real = await this.buildRealPagesMeta();
408
- return this.mergeAllPagesMeta(this.mdxSnapshotInitialized
417
+ const successful = this.mdxSnapshotInitialized
409
418
  ? this.successfulPagesInSourceOrder(real)
410
- : real, new Set(real.map((page) => page.slug)));
419
+ : real;
420
+ return this.mergeAllPagesMeta(successful, new Set([...real, ...successful].map((page) => page.slug)));
411
421
  }
412
422
  mergeAllPagesMeta(real, declaredRealSlugs = new Set(real.map((page) => page.slug))) {
413
423
  return mergePageCatalog(real, this.apiRegistry.isEmpty
@@ -417,10 +427,16 @@ export class MDXToNextJSGenerator {
417
427
  .filter((page) => !declaredRealSlugs.has(page.slug)));
418
428
  }
419
429
  successfulPagesInSourceOrder(realPages) {
420
- return realPages.flatMap((page) => {
430
+ const currentSources = new Set(realPages.map((page) => page.path.replace(/\\/g, "/")));
431
+ const ordered = realPages.flatMap((page) => {
421
432
  const successful = this.successfulMdxPages.get(page.path.replace(/\\/g, "/"));
422
433
  return successful ? [successful] : [];
423
434
  });
435
+ for (const [source, page] of this.successfulMdxPages) {
436
+ if (!currentSources.has(source))
437
+ ordered.push(page);
438
+ }
439
+ return ordered;
424
440
  }
425
441
  recordSuccessfulMdxPage(page, sourceContent) {
426
442
  const source = page.path.replace(/\\/g, "/");
@@ -667,7 +683,7 @@ export class MDXToNextJSGenerator {
667
683
  */
668
684
  async refreshSiteAggregates(resolvedPages, declaredSlugs) {
669
685
  const pages = resolvedPages ?? (await this.buildAllPagesMeta());
670
- await this.updatePagesIndex();
686
+ await this.updatePagesIndex(pages);
671
687
  await this.updateRootLayout(pages);
672
688
  await this.updateSitemap(pages);
673
689
  await this.updateLlmsFiles(pages);
@@ -688,6 +704,7 @@ export class MDXToNextJSGenerator {
688
704
  const currentPage = realPages.find((page) => page.path.replace(/\\/g, "/") === normalizedSource);
689
705
  if (!currentPage)
690
706
  throw new Error(`Unable to resolve ${filePath}`);
707
+ this.sectionsConfig = snapshot.sections;
691
708
  try {
692
709
  pageCommits.push(...(await this.writePageForFile(filePath, changedSource.content)));
693
710
  this.recordSuccessfulMdxPage(currentPage, changedSource.content);
@@ -738,12 +755,13 @@ export class MDXToNextJSGenerator {
738
755
  const pageCommits = [];
739
756
  try {
740
757
  const normalizedSource = filePath.replace(/\\/g, "/");
741
- this.removeSuccessfulMdxPage(normalizedSource);
742
- this.collisionBlockedMdxSources.delete(normalizedSource);
743
758
  if (filePath === "index.mdx" || filePath === "./index.mdx") {
744
759
  console.log(chalk.blue("🏠 Updating homepage - index.mdx deleted"));
745
760
  }
746
761
  const snapshot = await this.captureMdxPass(undefined, undefined, true);
762
+ this.removeSuccessfulMdxPage(normalizedSource);
763
+ this.collisionBlockedMdxSources.delete(normalizedSource);
764
+ this.sectionsConfig = snapshot.sections;
747
765
  const realPages = snapshot.pages;
748
766
  await this.retryMdxPages(snapshot, (source, page) => {
749
767
  return (this.collisionBlockedMdxSources.has(source) ||
@@ -788,6 +806,7 @@ export class MDXToNextJSGenerator {
788
806
  }
789
807
  throw error;
790
808
  }
809
+ this.sectionsConfig = snapshot.sections;
791
810
  const realPages = snapshot.pages;
792
811
  // Write each page first (the only genuinely per-file work), then run the
793
812
  // site-wide aggregations a single time. Doing the aggregations per file
@@ -844,167 +863,25 @@ export class MDXToNextJSGenerator {
844
863
  return siteLayoutTemplate(resolvedPages, this.sectionsConfig);
845
864
  }
846
865
  async generateSectionIndexPages(pages, declaredSlugs) {
847
- const nextSlugs = new Set();
848
866
  const resolvedPages = pages ?? (await this.buildAllPagesMeta());
849
- const occupiedSlugs = new Set(resolvedPages.map((page) => page.slug));
850
- const resolvedDeclaredSlugs = new Set(occupiedSlugs);
851
- for (const slug of declaredSlugs ?? [])
852
- resolvedDeclaredSlugs.add(slug);
853
- if (this.sectionsConfig && this.sectionsConfig.length > 0) {
854
- for (const section of this.sectionsConfig) {
855
- if (section.slug === "")
856
- continue;
857
- // Check if a page already exists at the section root
858
- const hasIndex = resolvedDeclaredSlugs.has(section.slug);
859
- if (hasIndex)
860
- continue;
861
- // Find the first page in this section
862
- const sectionPages = resolvedPages
863
- .filter((p) => p.section === section.slug)
864
- .sort((a, b) => {
865
- if (a.categoryOrder !== b.categoryOrder)
866
- return a.categoryOrder - b.categoryOrder;
867
- return a.order - b.order;
868
- });
869
- if (sectionPages.length === 0)
870
- continue;
871
- const firstPage = sectionPages[0];
872
- const redirectContent = `import { redirect } from "next/navigation";
867
+ return this.sectionIndexGenerator.generate(resolvedPages, this.sectionsConfig, declaredSlugs, (slug, target) => this.writeSectionIndexRedirect(slug, target));
868
+ }
869
+ async writeSectionIndexRedirect(slug, target) {
870
+ const content = `import { redirect } from "next/navigation";
873
871
 
874
872
  export default function SectionIndex() {
875
- redirect("/${firstPage.slug}");
873
+ redirect("/${target}");
876
874
  }
877
875
  `;
878
- const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", section.slug, "page.tsx");
879
- await fs.ensureDir(path.dirname(pagePath));
880
- await writeFileAtomic(pagePath, redirectContent);
881
- nextSlugs.add(section.slug);
882
- console.log(chalk.blue(`🔀 Generated section index redirect: /${section.slug} -> /${firstPage.slug}`));
883
- }
884
- }
885
- await this.cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs);
886
- }
887
- /**
888
- * Removes section index redirects written earlier in this session whose
889
- * section has since disappeared (e.g. the API Reference section after the
890
- * `openapi` config is removed mid-watch). Slugs now occupied by real pages
891
- * are preserved. Fresh processes start clean anyway - init() wipes app/ -
892
- * so in-session tracking is enough.
893
- */
894
- async cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs) {
895
- return this.generatedRouteManager.cleanupStaleSectionIndexPages(nextSlugs, occupiedSlugs, (dir, stopDir) => this.removeEmptyDirsUpTo(dir, stopDir));
896
- }
897
- /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
898
- async removeEmptyDirsUpTo(dir, stopDir) {
899
- return this.generatedRouteManager.removeEmptyDirsUpTo(dir, stopDir);
900
- }
901
- generatedFileSegments(filePath) {
902
- return path
903
- .relative(fs.realpathSync(this.outputDir), filePath)
904
- .split(path.sep)
905
- .filter(Boolean);
906
- }
907
- async readGeneratedFile(filePath) {
908
- return readOutputFileIfPresent(this.outputDir, ...this.generatedFileSegments(filePath));
909
- }
910
- async restoreGeneratedFile(filePath, content) {
911
- const target = this.outputPath(...this.generatedFileSegments(filePath));
912
- if (content === null) {
913
- await fs.remove(target);
914
- }
915
- else {
916
- await writeFileAtomic(target, content);
917
- }
918
- }
919
- async commitRenderedPage(pagePath, rendered) {
920
- if (rendered.rssRoute.action === "preserve") {
921
- const previousPage = await this.readGeneratedFile(pagePath);
922
- await writeFileAtomic(pagePath, rendered.pageContent);
923
- return {
924
- rollback: () => this.restoreGeneratedFile(pagePath, previousPage),
925
- };
926
- }
927
- const rssDir = resolveOutputPath(path.dirname(pagePath), "rss.xml");
928
- const rssPath = resolveOutputPath(path.dirname(pagePath), "rss.xml", "route.ts");
929
- const [previousPage, previousRss] = await Promise.all([
930
- this.readGeneratedFile(pagePath),
931
- this.readGeneratedFile(rssPath),
932
- ]);
933
- let pageChanged = false;
934
- let rssChanged = false;
935
- try {
936
- if (rendered.rssRoute.action === "write") {
937
- await writeFileAtomic(rssPath, rendered.rssRoute.content);
938
- rssChanged = true;
939
- await writeFileAtomic(pagePath, rendered.pageContent);
940
- pageChanged = true;
941
- }
942
- else {
943
- await writeFileAtomic(pagePath, rendered.pageContent);
944
- pageChanged = true;
945
- await fs.remove(rssPath);
946
- rssChanged = true;
947
- await this.removeEmptyDirsUpTo(rssDir, path.dirname(pagePath));
948
- }
949
- }
950
- catch (error) {
951
- const rollbackErrors = [];
952
- if (rssChanged) {
953
- try {
954
- await this.restoreGeneratedFile(rssPath, previousRss);
955
- }
956
- catch (rollbackError) {
957
- rollbackErrors.push(rollbackError);
958
- }
959
- }
960
- if (pageChanged) {
961
- try {
962
- await this.restoreGeneratedFile(pagePath, previousPage);
963
- }
964
- catch (rollbackError) {
965
- rollbackErrors.push(rollbackError);
966
- }
967
- }
968
- if (rollbackErrors.length > 0) {
969
- throw new AggregateError([error, ...rollbackErrors], `Unable to publish or restore generated page ${pagePath}`);
970
- }
971
- throw error;
972
- }
973
- return {
974
- rollback: async () => {
975
- const rollbackErrors = [];
976
- try {
977
- await this.restoreGeneratedFile(rssPath, previousRss);
978
- }
979
- catch (error) {
980
- rollbackErrors.push(error);
981
- }
982
- try {
983
- await this.restoreGeneratedFile(pagePath, previousPage);
984
- }
985
- catch (error) {
986
- rollbackErrors.push(error);
987
- }
988
- if (rollbackErrors.length > 0) {
989
- throw new AggregateError(rollbackErrors, `Unable to restore generated page ${pagePath}`);
990
- }
991
- },
992
- };
876
+ await writeFileAtomic(this.outputPath("app", "(site)", slug, "page.tsx"), content);
877
+ console.log(chalk.blue(`🔀 Generated section index redirect: /${slug} -> /${target}`));
993
878
  }
994
879
  async generatePageFromMDX(mdxFile, options) {
995
- const rendered = renderMdxPage(mdxFile, options);
996
- const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", mdxFile.slug, "page.tsx");
997
- await fs.ensureDir(path.dirname(pagePath));
998
- return this.commitRenderedPage(pagePath, rendered);
880
+ return this.generatedPagePublisher.generatePageFromMdx(mdxFile, options);
999
881
  }
1000
882
  /** Parses the configured OpenAPI spec(s) into the shared registry. */
1001
883
  async loadOpenApiRegistry() {
1002
- if (this.openApiSpecs.length === 0)
1003
- return;
1004
- this.apiRegistry = (await this.loadStableOpenApiRegistry(this.openApiSpecs)).registry;
1005
- if (!this.apiRegistry.isEmpty) {
1006
- console.log(chalk.blue(`📘 Loaded ${this.apiRegistry.all.length} API endpoint(s) from ${this.openApiSpecs.length} spec(s)`));
1007
- }
884
+ return this.openApiRefreshCoordinator.loadInitialRegistry();
1008
885
  }
1009
886
  /**
1010
887
  * Generates one page per OpenAPI operation, (re)writes the request-execution
@@ -1044,111 +921,9 @@ export default function SectionIndex() {
1044
921
  async syncOpenApiSpecWatcher() {
1045
922
  return this.watchCoordinator.syncOpenApiSpecWatcher(this.openApiSpecs, this.apiRegistry.sourceFiles);
1046
923
  }
1047
- async openApiSourceState(registry) {
1048
- return (await Promise.all(registry.sourceFiles.map(async (sourcePath) => {
1049
- return `${sourcePath}:${await this.sourceFs.pathState(sourcePath, true)}`;
1050
- }))).join("\n");
1051
- }
1052
- async loadStableOpenApiRegistry(specs) {
1053
- for (let attempt = 0; attempt < 3; attempt += 1) {
1054
- const registry = new OpenApiRegistry();
1055
- await registry.load(specs, this.rootDir, this.apiBaseSlug);
1056
- const current = await this.openApiSourceState(registry);
1057
- if (registry.sourceFingerprint === current) {
1058
- return { registry, sourceState: current };
1059
- }
1060
- }
1061
- throw new Error("OpenAPI sources changed repeatedly while being loaded");
1062
- }
1063
- async applyStableOpenApiRefresh(specs, syncWatcher) {
1064
- let candidate = await this.loadStableOpenApiRegistry(specs);
1065
- await this.applyOpenApiRefresh(candidate.registry, specs, syncWatcher);
1066
- // Once the new watcher is ready, compare its source against the exact
1067
- // version rendered above. A change in the retargeting window is replayed
1068
- // explicitly because ignoreInitial watchers cannot report it.
1069
- for (let attempt = 0; attempt < 3; attempt += 1) {
1070
- if ((await this.openApiSourceState(candidate.registry)) ===
1071
- candidate.sourceState) {
1072
- return;
1073
- }
1074
- candidate = await this.loadStableOpenApiRegistry(specs);
1075
- await this.applyOpenApiRefresh(candidate.registry, specs, false);
1076
- }
1077
- throw new Error("OpenAPI sources changed repeatedly while being generated");
1078
- }
1079
- /**
1080
- * Reparses the spec(s) and rewrites everything derived from them: the
1081
- * endpoint pages and allowlist, the sections (the "API Reference" section
1082
- * appears and disappears with the registry), and the site aggregates.
1083
- */
1084
- async applyOpenApiRefresh(nextRegistry, nextSpecs, syncWatcher) {
1085
- const previousRegistry = this.apiRegistry;
1086
- const previousSpecs = this.openApiSpecs;
1087
- const previousSections = this.sectionsConfig;
1088
- const previousRoutes = this.artifacts.routesFor("openapi");
1089
- const candidateRoutes = new Map();
1090
- let watcherSyncAttempted = false;
1091
- try {
1092
- this.apiRegistry = nextRegistry;
1093
- this.openApiSpecs = nextSpecs;
1094
- this.sectionsConfig = await this.resolveSections();
1095
- await this.writeApiPages(undefined, { writtenRoutes: candidateRoutes });
1096
- await this.refreshSiteAggregates();
1097
- if (syncWatcher) {
1098
- watcherSyncAttempted = true;
1099
- await this.syncOpenApiSpecWatcher();
1100
- }
1101
- }
1102
- catch (error) {
1103
- this.apiRegistry = previousRegistry;
1104
- this.openApiSpecs = previousSpecs;
1105
- this.sectionsConfig = previousSections;
1106
- const rollbackErrors = [];
1107
- if (watcherSyncAttempted) {
1108
- try {
1109
- await this.syncOpenApiSpecWatcher();
1110
- }
1111
- catch (rollbackError) {
1112
- rollbackErrors.push(rollbackError);
1113
- }
1114
- }
1115
- const previousSlugs = new Set(previousRoutes.map((route) => route.slug));
1116
- const occupiedMdxSlugs = new Set([...this.successfulMdxPages.values()].map((page) => page.slug));
1117
- for (const slug of new Set(candidateRoutes.values())) {
1118
- if (previousSlugs.has(slug) || occupiedMdxSlugs.has(slug))
1119
- continue;
1120
- try {
1121
- await this.removeOwnedRoute(slug);
1122
- }
1123
- catch (rollbackError) {
1124
- rollbackErrors.push(rollbackError);
1125
- }
1126
- }
1127
- try {
1128
- await this.writeApiPages(undefined, {
1129
- additionalPreviousRoutes: [...candidateRoutes].map(([source, slug]) => ({ kind: "openapi", source, slug })),
1130
- });
1131
- await this.refreshSiteAggregates();
1132
- }
1133
- catch (rollbackError) {
1134
- rollbackErrors.push(rollbackError);
1135
- }
1136
- if (rollbackErrors.length > 0) {
1137
- throw new AggregateError([error, ...rollbackErrors], "Unable to apply or restore the OpenAPI reference");
1138
- }
1139
- throw error;
1140
- }
1141
- }
1142
924
  /** Reparses the spec(s) and regenerates the API reference on a watch event. */
1143
925
  async handleOpenApiChange() {
1144
- console.log(chalk.cyan("📘 OpenAPI spec changed - regenerating API reference"));
1145
- try {
1146
- await this.applyStableOpenApiRefresh(this.openApiSpecs, true);
1147
- console.log(chalk.green("✅ API reference updated"));
1148
- }
1149
- catch (error) {
1150
- console.error(chalk.red("❌ Error updating API reference:"), error);
1151
- }
926
+ return this.openApiRefreshCoordinator.handleOpenApiChange();
1152
927
  }
1153
928
  /**
1154
929
  * Applies `openapi` edits in doccupine.json without a restart: reloads the
@@ -1159,40 +934,14 @@ export default function SectionIndex() {
1159
934
  * half-written editor save) keeps the current configuration.
1160
935
  */
1161
936
  async handleDoccupineConfigChange() {
1162
- const configPath = path.join(this.rootDir, this.doccupineConfigFile);
1163
- let config;
1164
- try {
1165
- const { data } = await this.sourceFs.readProjectSourceFile(configPath, "Doccupine configuration source");
1166
- config = validateConfig(JSON.parse(data.toString("utf8")), this.rootDir);
1167
- }
1168
- catch (error) {
1169
- console.warn(chalk.yellow("⚠️ doccupine.json is missing or invalid - keeping the current configuration"), error instanceof Error ? error.message : error);
1170
- return;
1171
- }
1172
- if ((config.watchDir &&
1173
- path.resolve(this.rootDir, config.watchDir) !== this.watchDir) ||
1174
- (config.outputDir &&
1175
- path.resolve(this.rootDir, config.outputDir) !== this.outputDir)) {
1176
- console.log(chalk.yellow("⚠️ watchDir/outputDir changes in doccupine.json need a restart to apply"));
1177
- }
1178
- const nextSpecs = normalizeOpenApiConfig(config.openapi);
1179
- if (JSON.stringify(nextSpecs) === JSON.stringify(this.openApiSpecs)) {
1180
- return;
1181
- }
1182
- console.log(chalk.cyan("📘 OpenAPI configuration changed - updating API reference"));
1183
- try {
1184
- // Validate the complete candidate before changing the active spec list or
1185
- // its watcher. A half-written/invalid replacement keeps both the current
1186
- // generated reference and its live watcher intact.
1187
- await this.applyStableOpenApiRefresh(nextSpecs, true);
1188
- console.log(chalk.green("✅ API reference updated"));
1189
- }
1190
- catch (error) {
1191
- console.error(chalk.red("❌ Error updating API reference:"), error);
1192
- }
1193
- }
1194
- async updatePagesIndex() {
1195
- const files = await this.getAllMDXFiles();
937
+ return this.openApiRefreshCoordinator.handleConfigChange();
938
+ }
939
+ async updatePagesIndex(pages) {
940
+ const files = pages
941
+ ? pages
942
+ .map((page) => page.path)
943
+ .filter((file) => file === "index.mdx" || file === "./index.mdx")
944
+ : await this.getAllMDXFiles();
1196
945
  let indexMDX = null;
1197
946
  for (const file of files) {
1198
947
  if (file === "index.mdx" || file === "./index.mdx") {
@@ -1214,16 +963,10 @@ export default function SectionIndex() {
1214
963
  console.error(chalk.red(`❌ openapi frontmatter "${indexMDX.openapi}" in index.mdx not found in any spec`));
1215
964
  }
1216
965
  }
1217
- const rendered = renderHomepage(indexMDX, apiOperation);
1218
- const homePath = this.outputPath("app", "(site)", "page.tsx");
1219
- await fs.ensureDir(path.dirname(homePath));
1220
- await this.commitRenderedPage(homePath, rendered);
966
+ await this.generatedPagePublisher.updateHomepage(indexMDX, apiOperation);
1221
967
  }
1222
968
  async updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath) {
1223
- const rendered = renderSectionPage(sectionSlug, frontmatter, mdxContent, sourcePath);
1224
- const pagePath = resolveOutputPath(this.outputDir, "app", "(site)", sectionSlug, "page.tsx");
1225
- await fs.ensureDir(path.dirname(pagePath));
1226
- return this.commitRenderedPage(pagePath, rendered);
969
+ return this.generatedPagePublisher.updateSectionIndex(sectionSlug, frontmatter, mdxContent, sourcePath);
1227
970
  }
1228
971
  async updateRootLayout(pages) {
1229
972
  await writeFileAtomic(this.outputPath("app", "layout.tsx"), await this.generateRootLayout());
@@ -1 +1 @@
1
- export declare const orderNavItemsTemplate = "export interface PagesProps {\n slug: string;\n title: string;\n date: string | null;\n category: string;\n description?: string;\n path?: string;\n categoryOrder?: number;\n order?: number;\n section?: string;\n navIcon?: string;\n categoryIcon?: string;\n httpMethod?: string;\n}\n\ninterface AccProps {\n [key: string]: {\n categoryOrder: number;\n icon?: string;\n pages: {\n date: string | null;\n slug: string;\n title: string;\n order: number;\n icon?: string;\n httpMethod?: string;\n }[];\n };\n}\n\nfunction transformPagesToGroupedStructure(pages: PagesProps[]) {\n const grouped = pages.reduce((acc: AccProps, page: PagesProps) => {\n const category = page.category || \"Uncategorized\";\n\n if (!acc[category]) {\n acc[category] = {\n categoryOrder: page.categoryOrder || 0,\n pages: [],\n };\n }\n\n // The first page in a category to declare a categoryIcon sets it.\n if (!acc[category].icon && page.categoryIcon) {\n acc[category].icon = page.categoryIcon;\n }\n\n acc[category].pages.push({\n date: page.date,\n slug: page.slug,\n title: page.title,\n order: page.order || 0,\n icon: page.navIcon,\n httpMethod: page.httpMethod,\n });\n\n return acc;\n }, {});\n\n return Object.entries(grouped)\n .sort(([, a], [, b]) => a.categoryOrder - b.categoryOrder)\n .map(([categoryName, categoryData], index) => ({\n slug: index === 0 ? \"\" : categoryName.toLowerCase().replace(/s+/g, \"-\"),\n label: categoryName,\n icon: categoryData.icon,\n links: categoryData.pages.sort((a, b) => a.order - b.order),\n }));\n}\n\nexport { transformPagesToGroupedStructure };\n";
1
+ export declare const orderNavItemsTemplate = "export interface PagesProps {\n slug: string;\n title: string;\n date: string | null;\n category: string;\n description?: string;\n path?: string;\n categoryOrder?: number;\n order?: number;\n section?: string;\n navIcon?: string;\n categoryIcon?: string;\n httpMethod?: string;\n}\n\ninterface AccProps {\n [key: string]: {\n categoryOrder: number;\n icon?: string;\n pages: {\n date: string | null;\n slug: string;\n title: string;\n order: number;\n icon?: string;\n httpMethod?: string;\n }[];\n };\n}\n\nfunction transformPagesToGroupedStructure(pages: PagesProps[]) {\n const grouped = pages.reduce((acc: AccProps, page: PagesProps) => {\n const category = page.category || \"Uncategorized\";\n\n if (!acc[category]) {\n acc[category] = {\n categoryOrder: page.categoryOrder || 0,\n pages: [],\n };\n }\n\n // The first page in a category to declare a categoryIcon sets it.\n if (!acc[category].icon && page.categoryIcon) {\n acc[category].icon = page.categoryIcon;\n }\n\n acc[category].pages.push({\n date: page.date,\n slug: page.slug,\n title: page.title,\n order: page.order || 0,\n icon: page.navIcon,\n httpMethod: page.httpMethod,\n });\n\n return acc;\n }, {});\n\n return Object.entries(grouped)\n .sort(([, a], [, b]) => a.categoryOrder - b.categoryOrder)\n .map(([categoryName, categoryData], index) => ({\n slug: index === 0 ? \"\" : categoryName.toLowerCase().replace(/\\s+/g, \"-\"),\n label: categoryName,\n icon: categoryData.icon,\n links: categoryData.pages.sort((a, b) => a.order - b.order),\n }));\n}\n\nexport { transformPagesToGroupedStructure };\n";
@@ -59,7 +59,7 @@ function transformPagesToGroupedStructure(pages: PagesProps[]) {
59
59
  return Object.entries(grouped)
60
60
  .sort(([, a], [, b]) => a.categoryOrder - b.categoryOrder)
61
61
  .map(([categoryName, categoryData], index) => ({
62
- slug: index === 0 ? "" : categoryName.toLowerCase().replace(/s+/g, "-"),
62
+ slug: index === 0 ? "" : categoryName.toLowerCase().replace(/\\s+/g, "-"),
63
63
  label: categoryName,
64
64
  icon: categoryData.icon,
65
65
  links: categoryData.pages.sort((a, b) => a.order - b.order),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "doccupine",
3
- "version": "0.0.145",
3
+ "version": "0.0.146",
4
4
  "description": "Free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {