doccupine 0.0.145 → 0.0.147

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 (54) hide show
  1. package/README.md +11 -2
  2. package/dist/cli.d.ts +7 -0
  3. package/dist/cli.js +41 -0
  4. package/dist/generator/generated-page-publisher.d.ts +21 -0
  5. package/dist/generator/generated-page-publisher.js +124 -0
  6. package/dist/generator/generated-route-manager.d.ts +3 -0
  7. package/dist/generator/generated-route-manager.js +21 -8
  8. package/dist/generator/mdx-pass-builder.d.ts +31 -0
  9. package/dist/generator/mdx-pass-builder.js +45 -0
  10. package/dist/generator/mdx-reconciliation-coordinator.d.ts +83 -0
  11. package/dist/generator/mdx-reconciliation-coordinator.js +471 -0
  12. package/dist/generator/openapi-refresh-coordinator.d.ts +42 -0
  13. package/dist/generator/openapi-refresh-coordinator.js +211 -0
  14. package/dist/generator/page-renderer.js +18 -13
  15. package/dist/generator/section-index-generator.d.ts +10 -0
  16. package/dist/generator/section-index-generator.js +68 -0
  17. package/dist/generator/secure-source-fs.js +5 -4
  18. package/dist/generator/site-artifacts.js +2 -2
  19. package/dist/generator/watch-coordinator.d.ts +8 -0
  20. package/dist/generator/watch-coordinator.js +131 -53
  21. package/dist/index.js +8 -2
  22. package/dist/lib/layout.js +18 -10
  23. package/dist/lib/openapi-rendering.d.ts +17 -0
  24. package/dist/lib/openapi-rendering.js +193 -0
  25. package/dist/lib/openapi.d.ts +1 -7
  26. package/dist/lib/openapi.js +2 -192
  27. package/dist/lib/output-safety.js +10 -3
  28. package/dist/lib/structures.js +4 -0
  29. package/dist/lib/utils.d.ts +14 -0
  30. package/dist/lib/utils.js +30 -8
  31. package/dist/mdx-to-nextjs-generator.d.ts +7 -65
  32. package/dist/mdx-to-nextjs-generator.js +94 -783
  33. package/dist/templates/components/Chat.d.ts +1 -1
  34. package/dist/templates/components/Chat.js +20 -691
  35. package/dist/templates/components/ChatStyles.d.ts +1 -0
  36. package/dist/templates/components/ChatStyles.js +695 -0
  37. package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
  38. package/dist/templates/components/layout/ApiPlayground.js +14 -148
  39. package/dist/templates/mdx/platform/analytics.mdx.d.ts +1 -1
  40. package/dist/templates/mdx/platform/analytics.mdx.js +13 -0
  41. package/dist/templates/mdx/platform/fonts-settings.mdx.d.ts +1 -1
  42. package/dist/templates/mdx/platform/fonts-settings.mdx.js +16 -0
  43. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  44. package/dist/templates/mdx/platform/publishing.mdx.js +16 -1
  45. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  46. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +17 -5
  47. package/dist/templates/package.js +3 -2
  48. package/dist/templates/prettierignore.d.ts +1 -1
  49. package/dist/templates/prettierignore.js +11 -0
  50. package/dist/templates/utils/apiPlayground.d.ts +1 -0
  51. package/dist/templates/utils/apiPlayground.js +149 -0
  52. package/dist/templates/utils/orderNavItems.d.ts +1 -1
  53. package/dist/templates/utils/orderNavItems.js +1 -1
  54. package/package.json +1 -1
@@ -3,6 +3,7 @@ import chokidar from "chokidar";
3
3
  import fs from "fs-extra";
4
4
  import path from "node:path";
5
5
  import { isPathInside } from "../lib/output-safety.js";
6
+ import { isMdxPath } from "../lib/utils.js";
6
7
  export class WatchCoordinator {
7
8
  options;
8
9
  watcher = null;
@@ -16,8 +17,10 @@ export class WatchCoordinator {
16
17
  mutationQueue = Promise.resolve();
17
18
  stopping = false;
18
19
  readyCancellations = new Set();
20
+ pendingWatcherClosures = new Set();
19
21
  sourceSnapshot = null;
20
22
  publicWatcherStarting = false;
23
+ publicWatcherRestartRequested = false;
21
24
  constructor(options) {
22
25
  this.options = options;
23
26
  }
@@ -26,6 +29,15 @@ export class WatchCoordinator {
26
29
  console.error(chalk.red(`❌ ${label}:`), error);
27
30
  });
28
31
  }
32
+ async closeDetachedWatcher(watcher) {
33
+ try {
34
+ await watcher.close();
35
+ }
36
+ catch (error) {
37
+ this.pendingWatcherClosures.add(watcher);
38
+ throw error;
39
+ }
40
+ }
29
41
  waitForWatcherReady(watcher) {
30
42
  if (this.stopping)
31
43
  return Promise.resolve();
@@ -52,6 +64,33 @@ export class WatchCoordinator {
52
64
  watcher.once("error", onError);
53
65
  });
54
66
  }
67
+ trackWatcherReady(ready, promise) {
68
+ // Startup performs other async work before awaiting the full ready set.
69
+ // Attach a handler now so an early watcher error is never unhandled.
70
+ void promise.catch(() => { });
71
+ ready.push(promise);
72
+ }
73
+ async waitForPublicWatcherReady() {
74
+ const watcher = this.setupPublicWatcher();
75
+ try {
76
+ await this.waitForWatcherReady(watcher);
77
+ }
78
+ catch (error) {
79
+ watcher.removeAllListeners();
80
+ watcher.on("error", (watcherError) => {
81
+ console.error(chalk.red("❌ Detached public watcher error:"), watcherError);
82
+ });
83
+ if (this.publicWatcher === watcher)
84
+ this.publicWatcher = null;
85
+ try {
86
+ await this.closeDetachedWatcher(watcher);
87
+ }
88
+ catch (closeError) {
89
+ throw new AggregateError([error, closeError], "Public watcher startup failed and cleanup was incomplete");
90
+ }
91
+ throw error;
92
+ }
93
+ }
55
94
  async captureSourceSnapshot() {
56
95
  const { analyticsConfigFile, configFiles, doccupineConfigFile, fontConfigFile, getOpenApiSpecs, getOpenApiSourceFiles, rootDir, sourceFs, watchDir, } = this.options;
57
96
  const configs = Object.fromEntries(await Promise.all(configFiles.map(async (fileName) => [
@@ -65,7 +104,7 @@ export class WatchCoordinator {
65
104
  return `${sourcePath}:${await sourceFs.pathState(sourcePath, true)}`;
66
105
  }))).join("\n");
67
106
  return {
68
- mdx: await sourceFs.treeState(watchDir, (relativePath) => relativePath.toLowerCase().endsWith(".mdx"), true),
107
+ mdx: await sourceFs.treeState(watchDir, isMdxPath, true),
69
108
  configs,
70
109
  font: await sourceFs.pathState(path.join(rootDir, fontConfigFile), true),
71
110
  analytics: await sourceFs.pathState(path.join(rootDir, analyticsConfigFile), true),
@@ -136,7 +175,7 @@ export class WatchCoordinator {
136
175
  if (!this.stopping &&
137
176
  !this.publicWatcher &&
138
177
  (await fs.pathExists(publicDir))) {
139
- await this.waitForWatcherReady(this.setupPublicWatcher());
178
+ await this.waitForPublicWatcherReady();
140
179
  if (this.stopping)
141
180
  return;
142
181
  }
@@ -152,8 +191,23 @@ export class WatchCoordinator {
152
191
  }
153
192
  }
154
193
  async startWatching() {
194
+ try {
195
+ await this.startWatchers();
196
+ }
197
+ catch (error) {
198
+ try {
199
+ await this.stop();
200
+ }
201
+ catch (cleanupError) {
202
+ throw new AggregateError([error, cleanupError], "Watcher startup failed and cleanup was incomplete");
203
+ }
204
+ throw error;
205
+ }
206
+ }
207
+ async startWatchers() {
155
208
  const { analyticsConfigFile, callbacks, configFiles, doccupineConfigFile, fontConfigFile, rootDir, watchDir, } = this.options;
156
209
  this.stopping = false;
210
+ this.publicWatcherRestartRequested = false;
157
211
  console.log(chalk.yellow(`👀 Watching for changes in: ${watchDir}`));
158
212
  const ready = [];
159
213
  this.watcher = chokidar.watch(watchDir, {
@@ -166,13 +220,13 @@ export class WatchCoordinator {
166
220
  if (configFiles.includes(fileName)) {
167
221
  return true;
168
222
  }
169
- if (isFile && !filePath.endsWith(".mdx")) {
223
+ if (isFile && !isMdxPath(filePath)) {
170
224
  return true;
171
225
  }
172
226
  return false;
173
227
  },
174
228
  });
175
- ready.push(this.waitForWatcherReady(this.watcher));
229
+ this.trackWatcherReady(ready, this.waitForWatcherReady(this.watcher));
176
230
  this.watcher
177
231
  .on("add", (filePath) => {
178
232
  const relativePath = path.relative(watchDir, filePath);
@@ -197,7 +251,7 @@ export class WatchCoordinator {
197
251
  persistent: true,
198
252
  ignoreInitial: true,
199
253
  });
200
- ready.push(this.waitForWatcherReady(this.configWatcher));
254
+ this.trackWatcherReady(ready, this.waitForWatcherReady(this.configWatcher));
201
255
  this.configWatcher
202
256
  .on("add", (filePath) => {
203
257
  console.log(chalk.cyan(`📝 Config file added: ${path.basename(filePath)}`));
@@ -219,7 +273,7 @@ export class WatchCoordinator {
219
273
  persistent: true,
220
274
  ignoreInitial: true,
221
275
  });
222
- ready.push(this.waitForWatcherReady(this.fontWatcher));
276
+ this.trackWatcherReady(ready, this.waitForWatcherReady(this.fontWatcher));
223
277
  this.fontWatcher
224
278
  .on("add", () => {
225
279
  console.log(chalk.cyan(`🔤 Font configuration added`));
@@ -239,7 +293,7 @@ export class WatchCoordinator {
239
293
  persistent: true,
240
294
  ignoreInitial: true,
241
295
  });
242
- ready.push(this.waitForWatcherReady(this.analyticsWatcher));
296
+ this.trackWatcherReady(ready, this.waitForWatcherReady(this.analyticsWatcher));
243
297
  this.analyticsWatcher
244
298
  .on("add", () => {
245
299
  console.log(chalk.cyan(`📊 Analytics configuration added`));
@@ -262,7 +316,7 @@ export class WatchCoordinator {
262
316
  persistent: true,
263
317
  ignoreInitial: true,
264
318
  });
265
- ready.push(this.waitForWatcherReady(this.doccupineConfigWatcher));
319
+ this.trackWatcherReady(ready, this.waitForWatcherReady(this.doccupineConfigWatcher));
266
320
  this.doccupineConfigWatcher
267
321
  .on("add", () => this.enqueueMutation("Error applying doccupine.json", () => callbacks.handleDoccupineConfigChange()))
268
322
  .on("change", () => this.enqueueMutation("Error applying doccupine.json", () => callbacks.handleDoccupineConfigChange()))
@@ -273,7 +327,7 @@ export class WatchCoordinator {
273
327
  if (await fs.pathExists(publicDir)) {
274
328
  if (this.stopping)
275
329
  return;
276
- ready.push(this.waitForWatcherReady(this.setupPublicWatcher()));
330
+ this.trackWatcherReady(ready, this.waitForPublicWatcherReady());
277
331
  }
278
332
  if (this.stopping)
279
333
  return;
@@ -282,24 +336,33 @@ export class WatchCoordinator {
282
336
  ignoreInitial: true,
283
337
  depth: 1,
284
338
  });
285
- ready.push(this.waitForWatcherReady(this.rootDirWatcher));
339
+ this.trackWatcherReady(ready, this.waitForWatcherReady(this.rootDirWatcher));
286
340
  const queuePublicWatcherStart = () => {
287
- if (this.stopping || this.publicWatcher || this.publicWatcherStarting) {
341
+ if (this.stopping)
342
+ return;
343
+ if (this.publicWatcherStarting) {
344
+ this.publicWatcherRestartRequested = true;
288
345
  return;
289
346
  }
347
+ if (this.publicWatcher)
348
+ return;
290
349
  this.publicWatcherStarting = true;
291
350
  this.enqueueMutation("Error initializing public directory", async () => {
292
351
  try {
293
352
  if (this.stopping)
294
353
  return;
295
354
  console.log(chalk.cyan("📁 Public directory created"));
296
- await this.waitForWatcherReady(this.setupPublicWatcher());
355
+ await this.waitForPublicWatcherReady();
297
356
  if (this.stopping)
298
357
  return;
299
358
  await callbacks.copyPublicFiles();
300
359
  }
301
360
  finally {
302
361
  this.publicWatcherStarting = false;
362
+ if (this.publicWatcherRestartRequested) {
363
+ this.publicWatcherRestartRequested = false;
364
+ queuePublicWatcherStart();
365
+ }
303
366
  }
304
367
  });
305
368
  };
@@ -321,7 +384,11 @@ export class WatchCoordinator {
321
384
  }
322
385
  const watcher = this.publicWatcher;
323
386
  this.publicWatcher = null;
324
- void watcher?.close();
387
+ if (watcher) {
388
+ void this.closeDetachedWatcher(watcher).catch((error) => {
389
+ console.error(chalk.red("❌ Public watcher close error:"), error);
390
+ });
391
+ }
325
392
  this.enqueueMutation("Error removing public directory", () => callbacks.copyPublicFiles());
326
393
  })
327
394
  .on("error", (error) => {
@@ -369,7 +436,11 @@ export class WatchCoordinator {
369
436
  return;
370
437
  const watcher = this.publicWatcher;
371
438
  this.publicWatcher = null;
372
- void watcher?.close();
439
+ if (watcher) {
440
+ void this.closeDetachedWatcher(watcher).catch((error) => {
441
+ console.error(chalk.red("❌ Public watcher close error:"), error);
442
+ });
443
+ }
373
444
  this.enqueueMutation("Error removing public directory", () => callbacks.copyPublicFiles());
374
445
  })
375
446
  .on("error", (error) => {
@@ -381,7 +452,7 @@ export class WatchCoordinator {
381
452
  const previousWatcher = this.openApiWatcher;
382
453
  this.openApiWatcher = null;
383
454
  if (previousWatcher)
384
- await previousWatcher.close();
455
+ await this.closeDetachedWatcher(previousWatcher);
385
456
  if (this.stopping || specs.length === 0)
386
457
  return;
387
458
  const { callbacks, rootDir } = this.options;
@@ -412,45 +483,52 @@ export class WatchCoordinator {
412
483
  this.stopping = true;
413
484
  for (const cancel of [...this.readyCancellations])
414
485
  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;
486
+ await this.closeCurrentWatchers();
487
+ await this.drainMutationQueue();
488
+ const errors = await this.closeCurrentWatchers();
489
+ await this.drainMutationQueue();
490
+ if (errors.length > 0) {
491
+ throw new AggregateError(errors, "Unable to close all source watchers");
450
492
  }
451
- if (this.publicWatcher) {
452
- await this.publicWatcher.close();
453
- this.publicWatcher = null;
493
+ }
494
+ async drainMutationQueue() {
495
+ while (true) {
496
+ const queue = this.mutationQueue;
497
+ await queue;
498
+ if (queue === this.mutationQueue)
499
+ return;
454
500
  }
455
501
  }
502
+ async closeCurrentWatchers() {
503
+ const watchers = [
504
+ ...this.pendingWatcherClosures,
505
+ this.watcher,
506
+ this.configWatcher,
507
+ this.fontWatcher,
508
+ this.analyticsWatcher,
509
+ this.openApiWatcher,
510
+ this.doccupineConfigWatcher,
511
+ this.publicWatcher,
512
+ this.rootDirWatcher,
513
+ ].filter((watcher) => watcher !== null);
514
+ this.pendingWatcherClosures.clear();
515
+ this.watcher = null;
516
+ this.configWatcher = null;
517
+ this.fontWatcher = null;
518
+ this.analyticsWatcher = null;
519
+ this.openApiWatcher = null;
520
+ this.doccupineConfigWatcher = null;
521
+ this.publicWatcher = null;
522
+ this.rootDirWatcher = null;
523
+ const uniqueWatchers = [...new Set(watchers)];
524
+ const results = await Promise.allSettled(uniqueWatchers.map((watcher) => Promise.resolve().then(() => watcher.close())));
525
+ const errors = [];
526
+ results.forEach((result, index) => {
527
+ if (result.status === "fulfilled")
528
+ return;
529
+ this.pendingWatcherClosures.add(uniqueWatchers[index]);
530
+ errors.push(result.reason);
531
+ });
532
+ return errors;
533
+ }
456
534
  }
package/dist/index.js CHANGED
@@ -23,6 +23,12 @@ export function isProcessEntrypoint(entry = process.argv[1], self = __filename)
23
23
  }
24
24
  }
25
25
  if (isProcessEntrypoint()) {
26
- const { runCli } = await import("./cli.js");
27
- await runCli();
26
+ const { runCli, reportCliError } = await import("./cli.js");
27
+ try {
28
+ await runCli();
29
+ }
30
+ catch (error) {
31
+ reportCliError(error);
32
+ process.exitCode = 1;
33
+ }
28
34
  }
@@ -44,24 +44,32 @@ function fontImportLine(fontConfig) {
44
44
  : 'import { Inter } from "next/font/google";';
45
45
  }
46
46
  function fontDeclLine(fontConfig) {
47
- return isGoogleFont(fontConfig)
48
- ? `const font = ${fontConfig.googleFont.fontName}({ ${[
47
+ if (isGoogleFont(fontConfig)) {
48
+ const options = [
49
49
  fontConfig.googleFont.subsets?.length
50
- ? `subsets: ${JSON.stringify(fontConfig.googleFont.subsets)}`
50
+ ? `subsets: [${fontConfig.googleFont.subsets
51
+ .map((subset) => JSON.stringify(subset))
52
+ .join(", ")}]`
51
53
  : "",
52
54
  fontConfig.googleFont.weight?.length
53
55
  ? `weight: ${Array.isArray(fontConfig.googleFont.weight)
54
- ? JSON.stringify(fontConfig.googleFont.weight)
56
+ ? `[${fontConfig.googleFont.weight
57
+ .map((weight) => JSON.stringify(weight))
58
+ .join(", ")}]`
55
59
  : JSON.stringify(fontConfig.googleFont.weight)}`
56
60
  : "",
57
- ]
58
- .filter(Boolean)
59
- .join(", ")} });`
60
- : isLocalFont(fontConfig)
61
- ? `const font = localFont({
61
+ ].filter(Boolean);
62
+ return options.length
63
+ ? `const font = ${fontConfig.googleFont.fontName}({
64
+ ${options.join(",\n ")},
65
+ });`
66
+ : `const font = ${fontConfig.googleFont.fontName}({});`;
67
+ }
68
+ return isLocalFont(fontConfig)
69
+ ? `const font = localFont({
62
70
  src: ${getLocalFontSrc(fontConfig)},
63
71
  });`
64
- : 'const font = Inter({ subsets: ["latin"] });';
72
+ : 'const font = Inter({ subsets: ["latin"] });';
65
73
  }
66
74
  // The inline blocking script that resolves dark mode before the first paint.
67
75
  // It only has to decide the mode and record it on <html>: every painted color
@@ -0,0 +1,17 @@
1
+ import type { OperationDescriptor } from "./openapi-types.js";
2
+ export declare function firstLine(text: unknown): string;
3
+ /**
4
+ * Builds the API-reference landing page as safe MDX. Endpoint metadata is
5
+ * emitted through JSX string expressions, so arbitrary OpenAPI summaries,
6
+ * paths, tags, and descriptions remain text rather than executable MDX.
7
+ */
8
+ export declare function buildApiIndexBody(operations: OperationDescriptor[]): string;
9
+ /** Minimal markdown body for an endpoint, used by the llms.txt aggregation. */
10
+ export declare function buildEndpointBody(title: string, methodUpper: string, pathKey: string, opRaw: any): string;
11
+ /**
12
+ * Builds the MDX body for a generated endpoint page: the operation description,
13
+ * followed by `<Field>` documentation for the parameters and request body, and
14
+ * a schema/example code block per response. Spec-derived strings are emitted
15
+ * only through serialized JSX expressions. Rendered above the playground.
16
+ */
17
+ export declare function buildEndpointDoc(op: OperationDescriptor): string;
@@ -0,0 +1,193 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ export function firstLine(text) {
3
+ if (typeof text !== "string")
4
+ return "";
5
+ return text.split("\n")[0]?.trim() ?? "";
6
+ }
7
+ /**
8
+ * Builds the API-reference landing page as safe MDX. Endpoint metadata is
9
+ * emitted through JSX string expressions, so arbitrary OpenAPI summaries,
10
+ * paths, tags, and descriptions remain text rather than executable MDX.
11
+ */
12
+ export function buildApiIndexBody(operations) {
13
+ const bySpec = new Map();
14
+ for (const operation of operations) {
15
+ const tag = operation.tags[0] ?? "Endpoints";
16
+ let byTag = bySpec.get(operation.specName);
17
+ if (!byTag) {
18
+ byTag = new Map();
19
+ bySpec.set(operation.specName, byTag);
20
+ }
21
+ const endpoints = byTag.get(tag) ?? [];
22
+ endpoints.push(operation);
23
+ byTag.set(tag, endpoints);
24
+ }
25
+ const lines = [
26
+ "# API Reference",
27
+ "",
28
+ `Browse all ${operations.length} API endpoint${operations.length === 1 ? "" : "s"}. Select an endpoint to view its parameters, responses, and live request playground.`,
29
+ ];
30
+ const multipleSpecs = bySpec.size > 1;
31
+ for (const [specName, byTag] of bySpec) {
32
+ if (multipleSpecs) {
33
+ lines.push("", `<h2>{${JSON.stringify(specName)}}</h2>`);
34
+ }
35
+ for (const [tag, endpoints] of byTag) {
36
+ const heading = multipleSpecs ? "h3" : "h2";
37
+ lines.push("", `<${heading}>{${JSON.stringify(tag)}}</${heading}>`, "", "<Columns cols={2}>");
38
+ for (const endpoint of endpoints) {
39
+ const method = endpoint.method.toUpperCase();
40
+ const title = endpoint.summary ?? `${method} ${endpoint.path}`;
41
+ const description = firstLine(endpoint.description) ||
42
+ `View the ${method} ${endpoint.path} endpoint.`;
43
+ const badgeColor = endpoint.method === "get"
44
+ ? "info"
45
+ : endpoint.method === "post"
46
+ ? "success"
47
+ : endpoint.method === "put" || endpoint.method === "patch"
48
+ ? "warning"
49
+ : endpoint.method === "delete"
50
+ ? "error"
51
+ : "gray";
52
+ lines.push("", `<Card title={${JSON.stringify(title)}} href={${JSON.stringify(`/${endpoint.slug}`)}}>`, ` <Badge color=${JSON.stringify(badgeColor)} size="sm">{${JSON.stringify(method)}}</Badge>`, ` <code>{${JSON.stringify(endpoint.path)}}</code>`, ` <p>{${JSON.stringify(description)}}</p>`, "</Card>");
53
+ }
54
+ lines.push("", "</Columns>");
55
+ }
56
+ }
57
+ return lines.join("\n");
58
+ }
59
+ /** Minimal markdown body for an endpoint, used by the llms.txt aggregation. */
60
+ export function buildEndpointBody(title, methodUpper, pathKey, opRaw) {
61
+ const lines = [`# ${title}`, "", `\`${methodUpper} ${pathKey}\``];
62
+ if (opRaw.description && typeof opRaw.description === "string") {
63
+ lines.push("", opRaw.description);
64
+ }
65
+ else if (opRaw.summary && opRaw.summary !== title) {
66
+ lines.push("", opRaw.summary);
67
+ }
68
+ return lines.join("\n");
69
+ }
70
+ /** Human-readable type label for a (dereferenced) JSON schema. */
71
+ function docSchemaType(schema) {
72
+ if (!schema || typeof schema !== "object")
73
+ return "any";
74
+ if (Array.isArray(schema.type))
75
+ return schema.type.join(" | ");
76
+ if (schema.type === "array")
77
+ return `array of ${docSchemaType(schema.items)}`;
78
+ if (typeof schema.type === "string") {
79
+ return schema.format ? `${schema.type} (${schema.format})` : schema.type;
80
+ }
81
+ if (schema.properties)
82
+ return "object";
83
+ if (Array.isArray(schema.enum))
84
+ return "enum";
85
+ return "any";
86
+ }
87
+ /** Collapses a description to a single inline line safe inside JSX children. */
88
+ function inlineText(text) {
89
+ if (typeof text !== "string")
90
+ return "";
91
+ return text.replace(/\s+/g, " ").trim();
92
+ }
93
+ /** Emits untrusted prose as a JSX string expression, never as executable MDX. */
94
+ function jsxText(text) {
95
+ return `{${JSON.stringify(text)}}`;
96
+ }
97
+ function jsonCode(value) {
98
+ const serialized = JSON.stringify(value, null, 2) ?? "null";
99
+ return `<Code language="json" code=${jsxText(serialized)} />`;
100
+ }
101
+ /** The object schema whose `properties` we can document (unwraps arrays). */
102
+ function objectShape(schema) {
103
+ if (!schema || typeof schema !== "object")
104
+ return null;
105
+ if (schema.type === "array")
106
+ return objectShape(schema.items);
107
+ if (schema.properties && typeof schema.properties === "object")
108
+ return schema;
109
+ return null;
110
+ }
111
+ /**
112
+ * Renders one parameter/property as a `<Field>`, recursing into nested object
113
+ * properties up to `MAX_FIELD_DEPTH` levels. Nested fields are emitted flush so
114
+ * MDX does not treat the indentation as a code block.
115
+ */
116
+ const MAX_FIELD_DEPTH = 2;
117
+ function renderDocField(name, schema, required, description, depth) {
118
+ const type = docSchemaType(schema);
119
+ const desc = inlineText(description ?? schema?.description);
120
+ const lines = [
121
+ `<Field value={${JSON.stringify(name)}} type={${JSON.stringify(type)}}${required ? " required" : ""}>`,
122
+ ];
123
+ if (desc)
124
+ lines.push(jsxText(desc));
125
+ const shape = depth < MAX_FIELD_DEPTH ? objectShape(schema) : null;
126
+ if (shape) {
127
+ const req = Array.isArray(shape.required) ? shape.required : [];
128
+ for (const [propName, propSchema] of Object.entries(shape.properties)) {
129
+ lines.push(renderDocField(propName, propSchema, req.includes(propName), undefined, depth + 1));
130
+ }
131
+ }
132
+ lines.push(`</Field>`);
133
+ return lines.join("\n");
134
+ }
135
+ const PARAM_LOCATION_TITLES = {
136
+ path: "Path parameters",
137
+ query: "Query parameters",
138
+ header: "Header parameters",
139
+ cookie: "Cookie parameters",
140
+ };
141
+ /**
142
+ * Builds the MDX body for a generated endpoint page: the operation description,
143
+ * followed by `<Field>` documentation for the parameters and request body, and
144
+ * a schema/example code block per response. Spec-derived strings are emitted
145
+ * only through serialized JSX expressions. Rendered above the playground.
146
+ */
147
+ export function buildEndpointDoc(op) {
148
+ const out = [];
149
+ if (op.description)
150
+ out.push(jsxText(op.description));
151
+ else if (op.summary)
152
+ out.push(jsxText(op.summary));
153
+ for (const location of ["path", "query", "header", "cookie"]) {
154
+ const params = op.parameters.filter((p) => p.in === location);
155
+ if (params.length === 0)
156
+ continue;
157
+ out.push(`## ${PARAM_LOCATION_TITLES[location]}`);
158
+ for (const p of params) {
159
+ out.push(renderDocField(p.name, p.schema, p.required, p.description, 0));
160
+ }
161
+ }
162
+ const body = op.requestBody?.content.find((m) => m.contentType.includes("json")) ??
163
+ op.requestBody?.content[0];
164
+ if (body?.schema !== undefined) {
165
+ out.push("## Request body");
166
+ const shape = objectShape(body.schema);
167
+ if (shape) {
168
+ const req = Array.isArray(shape.required) ? shape.required : [];
169
+ for (const [propName, propSchema] of Object.entries(shape.properties)) {
170
+ out.push(renderDocField(propName, propSchema, req.includes(propName), undefined, 0));
171
+ }
172
+ }
173
+ else {
174
+ out.push(jsonCode(body.schema));
175
+ }
176
+ }
177
+ if (op.responses.length > 0) {
178
+ out.push("## Responses");
179
+ for (const response of op.responses) {
180
+ out.push(`<h3>{${JSON.stringify(response.status)}}</h3>`);
181
+ if (response.description) {
182
+ out.push(jsxText(inlineText(response.description)));
183
+ }
184
+ const media = response.content.find((m) => m.contentType.includes("json")) ??
185
+ response.content[0];
186
+ const payload = media?.example ?? media?.schema;
187
+ if (payload !== undefined) {
188
+ out.push(jsonCode(payload));
189
+ }
190
+ }
191
+ }
192
+ return out.join("\n\n");
193
+ }
@@ -1,4 +1,5 @@
1
1
  import type { NormalizedOpenApiSpec, PageMeta } from "./types.js";
2
+ export { buildEndpointDoc } from "./openapi-rendering.js";
2
3
  import type { AllowlistEntry, OperationDescriptor } from "./openapi-types.js";
3
4
  /** Default base route segment for the generated API reference section. */
4
5
  export declare const DEFAULT_API_BASE_SLUG = "api-reference";
@@ -50,10 +51,3 @@ export declare class OpenApiRegistry {
50
51
  private uniqueSlug;
51
52
  private addAllowlist;
52
53
  }
53
- /**
54
- * Builds the MDX body for a generated endpoint page: the operation description,
55
- * followed by `<Field>` documentation for the parameters and request body, and
56
- * a schema/example code block per response. Spec-derived strings are emitted
57
- * only through serialized JSX expressions. Rendered above the playground.
58
- */
59
- export declare function buildEndpointDoc(op: OperationDescriptor): string;