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.
@@ -16,8 +16,10 @@ export class WatchCoordinator {
16
16
  mutationQueue = Promise.resolve();
17
17
  stopping = false;
18
18
  readyCancellations = new Set();
19
+ pendingWatcherClosures = new Set();
19
20
  sourceSnapshot = null;
20
21
  publicWatcherStarting = false;
22
+ publicWatcherRestartRequested = false;
21
23
  constructor(options) {
22
24
  this.options = options;
23
25
  }
@@ -26,6 +28,15 @@ export class WatchCoordinator {
26
28
  console.error(chalk.red(`❌ ${label}:`), error);
27
29
  });
28
30
  }
31
+ async closeDetachedWatcher(watcher) {
32
+ try {
33
+ await watcher.close();
34
+ }
35
+ catch (error) {
36
+ this.pendingWatcherClosures.add(watcher);
37
+ throw error;
38
+ }
39
+ }
29
40
  waitForWatcherReady(watcher) {
30
41
  if (this.stopping)
31
42
  return Promise.resolve();
@@ -52,6 +63,33 @@ export class WatchCoordinator {
52
63
  watcher.once("error", onError);
53
64
  });
54
65
  }
66
+ trackWatcherReady(ready, promise) {
67
+ // Startup performs other async work before awaiting the full ready set.
68
+ // Attach a handler now so an early watcher error is never unhandled.
69
+ void promise.catch(() => { });
70
+ ready.push(promise);
71
+ }
72
+ async waitForPublicWatcherReady() {
73
+ const watcher = this.setupPublicWatcher();
74
+ try {
75
+ await this.waitForWatcherReady(watcher);
76
+ }
77
+ catch (error) {
78
+ watcher.removeAllListeners();
79
+ watcher.on("error", (watcherError) => {
80
+ console.error(chalk.red("❌ Detached public watcher error:"), watcherError);
81
+ });
82
+ if (this.publicWatcher === watcher)
83
+ this.publicWatcher = null;
84
+ try {
85
+ await this.closeDetachedWatcher(watcher);
86
+ }
87
+ catch (closeError) {
88
+ throw new AggregateError([error, closeError], "Public watcher startup failed and cleanup was incomplete");
89
+ }
90
+ throw error;
91
+ }
92
+ }
55
93
  async captureSourceSnapshot() {
56
94
  const { analyticsConfigFile, configFiles, doccupineConfigFile, fontConfigFile, getOpenApiSpecs, getOpenApiSourceFiles, rootDir, sourceFs, watchDir, } = this.options;
57
95
  const configs = Object.fromEntries(await Promise.all(configFiles.map(async (fileName) => [
@@ -136,7 +174,7 @@ export class WatchCoordinator {
136
174
  if (!this.stopping &&
137
175
  !this.publicWatcher &&
138
176
  (await fs.pathExists(publicDir))) {
139
- await this.waitForWatcherReady(this.setupPublicWatcher());
177
+ await this.waitForPublicWatcherReady();
140
178
  if (this.stopping)
141
179
  return;
142
180
  }
@@ -152,8 +190,23 @@ export class WatchCoordinator {
152
190
  }
153
191
  }
154
192
  async startWatching() {
193
+ try {
194
+ await this.startWatchers();
195
+ }
196
+ catch (error) {
197
+ try {
198
+ await this.stop();
199
+ }
200
+ catch (cleanupError) {
201
+ throw new AggregateError([error, cleanupError], "Watcher startup failed and cleanup was incomplete");
202
+ }
203
+ throw error;
204
+ }
205
+ }
206
+ async startWatchers() {
155
207
  const { analyticsConfigFile, callbacks, configFiles, doccupineConfigFile, fontConfigFile, rootDir, watchDir, } = this.options;
156
208
  this.stopping = false;
209
+ this.publicWatcherRestartRequested = false;
157
210
  console.log(chalk.yellow(`👀 Watching for changes in: ${watchDir}`));
158
211
  const ready = [];
159
212
  this.watcher = chokidar.watch(watchDir, {
@@ -172,7 +225,7 @@ export class WatchCoordinator {
172
225
  return false;
173
226
  },
174
227
  });
175
- ready.push(this.waitForWatcherReady(this.watcher));
228
+ this.trackWatcherReady(ready, this.waitForWatcherReady(this.watcher));
176
229
  this.watcher
177
230
  .on("add", (filePath) => {
178
231
  const relativePath = path.relative(watchDir, filePath);
@@ -197,7 +250,7 @@ export class WatchCoordinator {
197
250
  persistent: true,
198
251
  ignoreInitial: true,
199
252
  });
200
- ready.push(this.waitForWatcherReady(this.configWatcher));
253
+ this.trackWatcherReady(ready, this.waitForWatcherReady(this.configWatcher));
201
254
  this.configWatcher
202
255
  .on("add", (filePath) => {
203
256
  console.log(chalk.cyan(`📝 Config file added: ${path.basename(filePath)}`));
@@ -219,7 +272,7 @@ export class WatchCoordinator {
219
272
  persistent: true,
220
273
  ignoreInitial: true,
221
274
  });
222
- ready.push(this.waitForWatcherReady(this.fontWatcher));
275
+ this.trackWatcherReady(ready, this.waitForWatcherReady(this.fontWatcher));
223
276
  this.fontWatcher
224
277
  .on("add", () => {
225
278
  console.log(chalk.cyan(`🔤 Font configuration added`));
@@ -239,7 +292,7 @@ export class WatchCoordinator {
239
292
  persistent: true,
240
293
  ignoreInitial: true,
241
294
  });
242
- ready.push(this.waitForWatcherReady(this.analyticsWatcher));
295
+ this.trackWatcherReady(ready, this.waitForWatcherReady(this.analyticsWatcher));
243
296
  this.analyticsWatcher
244
297
  .on("add", () => {
245
298
  console.log(chalk.cyan(`📊 Analytics configuration added`));
@@ -262,7 +315,7 @@ export class WatchCoordinator {
262
315
  persistent: true,
263
316
  ignoreInitial: true,
264
317
  });
265
- ready.push(this.waitForWatcherReady(this.doccupineConfigWatcher));
318
+ this.trackWatcherReady(ready, this.waitForWatcherReady(this.doccupineConfigWatcher));
266
319
  this.doccupineConfigWatcher
267
320
  .on("add", () => this.enqueueMutation("Error applying doccupine.json", () => callbacks.handleDoccupineConfigChange()))
268
321
  .on("change", () => this.enqueueMutation("Error applying doccupine.json", () => callbacks.handleDoccupineConfigChange()))
@@ -273,7 +326,7 @@ export class WatchCoordinator {
273
326
  if (await fs.pathExists(publicDir)) {
274
327
  if (this.stopping)
275
328
  return;
276
- ready.push(this.waitForWatcherReady(this.setupPublicWatcher()));
329
+ this.trackWatcherReady(ready, this.waitForPublicWatcherReady());
277
330
  }
278
331
  if (this.stopping)
279
332
  return;
@@ -282,24 +335,33 @@ export class WatchCoordinator {
282
335
  ignoreInitial: true,
283
336
  depth: 1,
284
337
  });
285
- ready.push(this.waitForWatcherReady(this.rootDirWatcher));
338
+ this.trackWatcherReady(ready, this.waitForWatcherReady(this.rootDirWatcher));
286
339
  const queuePublicWatcherStart = () => {
287
- if (this.stopping || this.publicWatcher || this.publicWatcherStarting) {
340
+ if (this.stopping)
341
+ return;
342
+ if (this.publicWatcherStarting) {
343
+ this.publicWatcherRestartRequested = true;
288
344
  return;
289
345
  }
346
+ if (this.publicWatcher)
347
+ return;
290
348
  this.publicWatcherStarting = true;
291
349
  this.enqueueMutation("Error initializing public directory", async () => {
292
350
  try {
293
351
  if (this.stopping)
294
352
  return;
295
353
  console.log(chalk.cyan("📁 Public directory created"));
296
- await this.waitForWatcherReady(this.setupPublicWatcher());
354
+ await this.waitForPublicWatcherReady();
297
355
  if (this.stopping)
298
356
  return;
299
357
  await callbacks.copyPublicFiles();
300
358
  }
301
359
  finally {
302
360
  this.publicWatcherStarting = false;
361
+ if (this.publicWatcherRestartRequested) {
362
+ this.publicWatcherRestartRequested = false;
363
+ queuePublicWatcherStart();
364
+ }
303
365
  }
304
366
  });
305
367
  };
@@ -321,7 +383,11 @@ export class WatchCoordinator {
321
383
  }
322
384
  const watcher = this.publicWatcher;
323
385
  this.publicWatcher = null;
324
- void watcher?.close();
386
+ if (watcher) {
387
+ void this.closeDetachedWatcher(watcher).catch((error) => {
388
+ console.error(chalk.red("❌ Public watcher close error:"), error);
389
+ });
390
+ }
325
391
  this.enqueueMutation("Error removing public directory", () => callbacks.copyPublicFiles());
326
392
  })
327
393
  .on("error", (error) => {
@@ -369,7 +435,11 @@ export class WatchCoordinator {
369
435
  return;
370
436
  const watcher = this.publicWatcher;
371
437
  this.publicWatcher = null;
372
- void watcher?.close();
438
+ if (watcher) {
439
+ void this.closeDetachedWatcher(watcher).catch((error) => {
440
+ console.error(chalk.red("❌ Public watcher close error:"), error);
441
+ });
442
+ }
373
443
  this.enqueueMutation("Error removing public directory", () => callbacks.copyPublicFiles());
374
444
  })
375
445
  .on("error", (error) => {
@@ -381,7 +451,7 @@ export class WatchCoordinator {
381
451
  const previousWatcher = this.openApiWatcher;
382
452
  this.openApiWatcher = null;
383
453
  if (previousWatcher)
384
- await previousWatcher.close();
454
+ await this.closeDetachedWatcher(previousWatcher);
385
455
  if (this.stopping || specs.length === 0)
386
456
  return;
387
457
  const { callbacks, rootDir } = this.options;
@@ -412,45 +482,52 @@ export class WatchCoordinator {
412
482
  this.stopping = true;
413
483
  for (const cancel of [...this.readyCancellations])
414
484
  cancel();
415
- if (this.watcher) {
416
- await this.watcher.close();
417
- console.log(chalk.yellow("👋 Stopped watching for MDX changes"));
418
- }
419
- if (this.configWatcher) {
420
- await this.configWatcher.close();
421
- console.log(chalk.yellow("👋 Stopped watching for config changes"));
422
- }
423
- if (this.fontWatcher) {
424
- await this.fontWatcher.close();
425
- console.log(chalk.yellow("👋 Stopped watching for font config changes"));
426
- }
427
- if (this.analyticsWatcher) {
428
- await this.analyticsWatcher.close();
429
- console.log(chalk.yellow("👋 Stopped watching for analytics config changes"));
430
- }
431
- if (this.openApiWatcher) {
432
- await this.openApiWatcher.close();
433
- console.log(chalk.yellow("👋 Stopped watching for OpenAPI spec changes"));
434
- }
435
- if (this.doccupineConfigWatcher) {
436
- await this.doccupineConfigWatcher.close();
437
- console.log(chalk.yellow("👋 Stopped watching for doccupine.json changes"));
438
- }
439
- if (this.publicWatcher) {
440
- await this.publicWatcher.close();
441
- console.log(chalk.yellow("👋 Stopped watching for public directory changes"));
442
- }
443
- if (this.rootDirWatcher) {
444
- await this.rootDirWatcher.close();
445
- }
446
- await this.mutationQueue;
447
- if (this.openApiWatcher) {
448
- await this.openApiWatcher.close();
449
- this.openApiWatcher = null;
485
+ await this.closeCurrentWatchers();
486
+ await this.drainMutationQueue();
487
+ const errors = await this.closeCurrentWatchers();
488
+ await this.drainMutationQueue();
489
+ if (errors.length > 0) {
490
+ throw new AggregateError(errors, "Unable to close all source watchers");
450
491
  }
451
- if (this.publicWatcher) {
452
- await this.publicWatcher.close();
453
- this.publicWatcher = null;
492
+ }
493
+ async drainMutationQueue() {
494
+ while (true) {
495
+ const queue = this.mutationQueue;
496
+ await queue;
497
+ if (queue === this.mutationQueue)
498
+ return;
454
499
  }
455
500
  }
501
+ async closeCurrentWatchers() {
502
+ const watchers = [
503
+ ...this.pendingWatcherClosures,
504
+ this.watcher,
505
+ this.configWatcher,
506
+ this.fontWatcher,
507
+ this.analyticsWatcher,
508
+ this.openApiWatcher,
509
+ this.doccupineConfigWatcher,
510
+ this.publicWatcher,
511
+ this.rootDirWatcher,
512
+ ].filter((watcher) => watcher !== null);
513
+ this.pendingWatcherClosures.clear();
514
+ this.watcher = null;
515
+ this.configWatcher = null;
516
+ this.fontWatcher = null;
517
+ this.analyticsWatcher = null;
518
+ this.openApiWatcher = null;
519
+ this.doccupineConfigWatcher = null;
520
+ this.publicWatcher = null;
521
+ this.rootDirWatcher = null;
522
+ const uniqueWatchers = [...new Set(watchers)];
523
+ const results = await Promise.allSettled(uniqueWatchers.map((watcher) => Promise.resolve().then(() => watcher.close())));
524
+ const errors = [];
525
+ results.forEach((result, index) => {
526
+ if (result.status === "fulfilled")
527
+ return;
528
+ this.pendingWatcherClosures.add(uniqueWatchers[index]);
529
+ errors.push(result.reason);
530
+ });
531
+ return errors;
532
+ }
456
533
  }
@@ -3,6 +3,7 @@ import { open } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  const MARKER_FILE = ".doccupine-generated.json";
5
5
  const SAFE_UNOWNED_FILES = new Set([".DS_Store", ".gitkeep", ".env"]);
6
+ const SAFE_UNOWNED_CACHE_DIRECTORIES = new Set([".next", "node_modules"]);
6
7
  const GENERATED_SUBTREES = new Set([
7
8
  "app",
8
9
  "components",
@@ -60,8 +61,13 @@ const LEGACY_FILE_FINGERPRINTS = [
60
61
  ],
61
62
  },
62
63
  ];
63
- function isSafeUnownedEntry(name) {
64
- return SAFE_UNOWNED_FILES.has(name) || name.startsWith(".env.");
64
+ async function isSafeUnownedEntry(outputDir, name) {
65
+ if (SAFE_UNOWNED_FILES.has(name) || name.startsWith(".env."))
66
+ return true;
67
+ if (!SAFE_UNOWNED_CACHE_DIRECTORIES.has(name))
68
+ return false;
69
+ const stat = await lstatIfPresent(path.join(outputDir, name));
70
+ return stat?.isDirectory() === true;
65
71
  }
66
72
  export function isPathInside(parent, candidate) {
67
73
  const relative = path.relative(path.resolve(parent), path.resolve(candidate));
@@ -409,7 +415,8 @@ export async function claimOutputDirectory(outputDir) {
409
415
  return;
410
416
  }
411
417
  const entries = await fs.readdir(realOutputDir);
412
- const canClaim = entries.every(isSafeUnownedEntry) ||
418
+ const safeUnownedEntries = await Promise.all(entries.map((name) => isSafeUnownedEntry(realOutputDir, name)));
419
+ const canClaim = safeUnownedEntries.every(Boolean) ||
413
420
  (await looksLikeLegacyGeneratedApp(realOutputDir));
414
421
  if (!canClaim) {
415
422
  throw new Error(`Refusing to overwrite non-empty directory ${outputDir}. Choose an empty outputDir or a Doccupine-generated directory.`);
@@ -23,7 +23,11 @@ export declare class MDXToNextJSGenerator {
23
23
  private sourceFs;
24
24
  private appScaffolder;
25
25
  private apiReferenceGenerator;
26
+ private generatedPagePublisher;
26
27
  private generatedRouteManager;
28
+ private mdxPassBuilder;
29
+ private openApiRefreshCoordinator;
30
+ private sectionIndexGenerator;
27
31
  private projectConfigRepository;
28
32
  private publicAssetManager;
29
33
  private watchCoordinator;
@@ -70,7 +74,6 @@ export declare class MDXToNextJSGenerator {
70
74
  handlePublicFileChange(filePath: string): Promise<void>;
71
75
  handlePublicFileDelete(filePath: string): Promise<void>;
72
76
  startWatching(): Promise<void>;
73
- private parseMDXFile;
74
77
  private captureMdxPass;
75
78
  private buildRealPagesMeta;
76
79
  private buildAllPagesMeta;
@@ -113,20 +116,7 @@ export declare class MDXToNextJSGenerator {
113
116
  generateRootLayout(): Promise<string>;
114
117
  generateSiteLayout(pages?: PageMeta[]): Promise<string>;
115
118
  generateSectionIndexPages(pages?: PageMeta[], declaredSlugs?: Set<string>): Promise<void>;
116
- /**
117
- * Removes section index redirects written earlier in this session whose
118
- * section has since disappeared (e.g. the API Reference section after the
119
- * `openapi` config is removed mid-watch). Slugs now occupied by real pages
120
- * are preserved. Fresh processes start clean anyway - init() wipes app/ -
121
- * so in-session tracking is enough.
122
- */
123
- private cleanupStaleSectionIndexPages;
124
- /** Best-effort removal of now-empty directories up to (not incl.) stopDir. */
125
- private removeEmptyDirsUpTo;
126
- private generatedFileSegments;
127
- private readGeneratedFile;
128
- private restoreGeneratedFile;
129
- private commitRenderedPage;
119
+ private writeSectionIndexRedirect;
130
120
  generatePageFromMDX(mdxFile: MDXFile, options?: {
131
121
  apiOperation?: OperationDescriptor;
132
122
  }): Promise<GeneratedPageCommit>;
@@ -150,15 +140,6 @@ export declare class MDXToNextJSGenerator {
150
140
  * so specs added mid-session are watched without a restart.
151
141
  */
152
142
  private syncOpenApiSpecWatcher;
153
- private openApiSourceState;
154
- private loadStableOpenApiRegistry;
155
- private applyStableOpenApiRefresh;
156
- /**
157
- * Reparses the spec(s) and rewrites everything derived from them: the
158
- * endpoint pages and allowlist, the sections (the "API Reference" section
159
- * appears and disappears with the registry), and the site aggregates.
160
- */
161
- private applyOpenApiRefresh;
162
143
  /** Reparses the spec(s) and regenerates the API reference on a watch event. */
163
144
  handleOpenApiChange(): Promise<void>;
164
145
  /**
@@ -170,7 +151,7 @@ export declare class MDXToNextJSGenerator {
170
151
  * half-written editor save) keeps the current configuration.
171
152
  */
172
153
  handleDoccupineConfigChange(): Promise<void>;
173
- updatePagesIndex(): Promise<void>;
154
+ updatePagesIndex(pages?: readonly PageMeta[]): Promise<void>;
174
155
  updateSectionIndex(sectionSlug: string, frontmatter: Record<string, any>, mdxContent: string, sourcePath?: string): Promise<GeneratedPageCommit>;
175
156
  updateRootLayout(pages?: PageMeta[]): Promise<void>;
176
157
  loadSiteUrl(): Promise<string | null>;