doccupine 0.0.133 → 0.0.134

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 (143) hide show
  1. package/README.md +40 -1
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.js +274 -19
  4. package/dist/lib/config-manager.d.ts +8 -1
  5. package/dist/lib/config-manager.js +98 -4
  6. package/dist/lib/openapi-types.d.ts +120 -0
  7. package/dist/lib/openapi-types.js +14 -0
  8. package/dist/lib/openapi.d.ts +52 -0
  9. package/dist/lib/openapi.js +603 -0
  10. package/dist/lib/structures.js +28 -2
  11. package/dist/lib/types.d.ts +22 -0
  12. package/dist/lib/utils.d.ts +8 -0
  13. package/dist/lib/utils.js +14 -0
  14. package/dist/templates/app/api/playground/route.d.ts +1 -0
  15. package/dist/templates/app/api/playground/route.js +199 -0
  16. package/dist/templates/components/Docs.d.ts +1 -1
  17. package/dist/templates/components/Docs.js +11 -2
  18. package/dist/templates/components/SideBar.d.ts +1 -1
  19. package/dist/templates/components/SideBar.js +10 -0
  20. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  21. package/dist/templates/components/layout/Accordion.js +3 -2
  22. package/dist/templates/components/layout/ActionBar.d.ts +1 -1
  23. package/dist/templates/components/layout/ActionBar.js +21 -14
  24. package/dist/templates/components/layout/ApiPlayground.d.ts +1 -0
  25. package/dist/templates/components/layout/ApiPlayground.js +1083 -0
  26. package/dist/templates/components/layout/ApiPlaygroundDemo.d.ts +1 -0
  27. package/dist/templates/components/layout/ApiPlaygroundDemo.js +81 -0
  28. package/dist/templates/components/layout/Code.d.ts +1 -1
  29. package/dist/templates/components/layout/Code.js +10 -22
  30. package/dist/templates/components/layout/CopyButton.d.ts +1 -0
  31. package/dist/templates/components/layout/CopyButton.js +68 -0
  32. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  33. package/dist/templates/components/layout/DocsComponents.js +39 -0
  34. package/dist/templates/components/layout/Mermaid.d.ts +1 -1
  35. package/dist/templates/components/layout/Mermaid.js +21 -3
  36. package/dist/templates/components/layout/SharedStyles.d.ts +1 -1
  37. package/dist/templates/components/layout/SharedStyles.js +0 -4
  38. package/dist/templates/components/layout/Steps.d.ts +1 -1
  39. package/dist/templates/components/layout/Steps.js +0 -1
  40. package/dist/templates/components/layout/Update.d.ts +1 -1
  41. package/dist/templates/components/layout/Update.js +2 -1
  42. package/dist/templates/mdx/accordion.mdx.d.ts +1 -1
  43. package/dist/templates/mdx/accordion.mdx.js +19 -1
  44. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  45. package/dist/templates/mdx/ai-assistant.mdx.js +3 -2
  46. package/dist/templates/mdx/analytics.mdx.d.ts +1 -1
  47. package/dist/templates/mdx/analytics.mdx.js +2 -2
  48. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -0
  49. package/dist/templates/mdx/api-playground.mdx.js +158 -0
  50. package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
  51. package/dist/templates/mdx/authentication.mdx.js +3 -3
  52. package/dist/templates/mdx/buttons.mdx.d.ts +1 -1
  53. package/dist/templates/mdx/buttons.mdx.js +1 -1
  54. package/dist/templates/mdx/callouts.mdx.d.ts +1 -1
  55. package/dist/templates/mdx/callouts.mdx.js +1 -1
  56. package/dist/templates/mdx/cards.mdx.d.ts +1 -1
  57. package/dist/templates/mdx/cards.mdx.js +1 -1
  58. package/dist/templates/mdx/color-swatches.mdx.d.ts +1 -1
  59. package/dist/templates/mdx/color-swatches.mdx.js +1 -1
  60. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  61. package/dist/templates/mdx/commands.mdx.js +3 -2
  62. package/dist/templates/mdx/components.mdx.d.ts +1 -1
  63. package/dist/templates/mdx/components.mdx.js +12 -9
  64. package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
  65. package/dist/templates/mdx/deployment-and-hosting.mdx.js +4 -3
  66. package/dist/templates/mdx/fields.mdx.d.ts +1 -1
  67. package/dist/templates/mdx/fields.mdx.js +1 -1
  68. package/dist/templates/mdx/fonts.mdx.d.ts +1 -1
  69. package/dist/templates/mdx/fonts.mdx.js +2 -2
  70. package/dist/templates/mdx/footer-links.mdx.d.ts +1 -1
  71. package/dist/templates/mdx/footer-links.mdx.js +1 -1
  72. package/dist/templates/mdx/frames.mdx.d.ts +1 -1
  73. package/dist/templates/mdx/frames.mdx.js +1 -1
  74. package/dist/templates/mdx/globals.mdx.d.ts +1 -1
  75. package/dist/templates/mdx/globals.mdx.js +1 -1
  76. package/dist/templates/mdx/icons.mdx.d.ts +1 -1
  77. package/dist/templates/mdx/icons.mdx.js +1 -1
  78. package/dist/templates/mdx/image-and-embeds.mdx.d.ts +1 -1
  79. package/dist/templates/mdx/image-and-embeds.mdx.js +1 -1
  80. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  81. package/dist/templates/mdx/media-and-assets.mdx.js +2 -2
  82. package/dist/templates/mdx/mermaid.mdx.d.ts +1 -1
  83. package/dist/templates/mdx/mermaid.mdx.js +1 -1
  84. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  85. package/dist/templates/mdx/model-context-protocol.mdx.js +2 -2
  86. package/dist/templates/mdx/navigation.mdx.d.ts +1 -1
  87. package/dist/templates/mdx/navigation.mdx.js +22 -11
  88. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  89. package/dist/templates/mdx/platform/ai-assistant.mdx.js +4 -3
  90. package/dist/templates/mdx/platform/analytics.mdx.d.ts +1 -1
  91. package/dist/templates/mdx/platform/analytics.mdx.js +2 -2
  92. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -0
  93. package/dist/templates/mdx/platform/api-playground.mdx.js +62 -0
  94. package/dist/templates/mdx/platform/billing.mdx.d.ts +1 -1
  95. package/dist/templates/mdx/platform/billing.mdx.js +1 -1
  96. package/dist/templates/mdx/platform/build-and-deploy.mdx.d.ts +1 -1
  97. package/dist/templates/mdx/platform/build-and-deploy.mdx.js +1 -1
  98. package/dist/templates/mdx/platform/creating-a-project.mdx.d.ts +1 -1
  99. package/dist/templates/mdx/platform/creating-a-project.mdx.js +12 -2
  100. package/dist/templates/mdx/platform/custom-domains.mdx.d.ts +1 -1
  101. package/dist/templates/mdx/platform/custom-domains.mdx.js +1 -1
  102. package/dist/templates/mdx/platform/fonts-settings.mdx.d.ts +1 -1
  103. package/dist/templates/mdx/platform/fonts-settings.mdx.js +1 -1
  104. package/dist/templates/mdx/platform/footer-links.mdx.d.ts +1 -0
  105. package/dist/templates/mdx/platform/footer-links.mdx.js +47 -0
  106. package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -0
  107. package/dist/templates/mdx/platform/import-from-github.mdx.js +91 -0
  108. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  109. package/dist/templates/mdx/platform/mcp.mdx.js +3 -3
  110. package/dist/templates/mdx/platform/project-settings.mdx.d.ts +1 -1
  111. package/dist/templates/mdx/platform/project-settings.mdx.js +1 -1
  112. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -0
  113. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +113 -0
  114. package/dist/templates/mdx/platform/team-members.mdx.d.ts +1 -1
  115. package/dist/templates/mdx/platform/team-members.mdx.js +1 -1
  116. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  117. package/dist/templates/mdx/sections.mdx.js +1 -1
  118. package/dist/templates/mdx/steps.mdx.d.ts +1 -1
  119. package/dist/templates/mdx/steps.mdx.js +1 -1
  120. package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
  121. package/dist/templates/mdx/tabs.mdx.js +1 -1
  122. package/dist/templates/mdx/theme.mdx.d.ts +1 -1
  123. package/dist/templates/mdx/theme.mdx.js +1 -1
  124. package/dist/templates/mdx/update.mdx.d.ts +1 -1
  125. package/dist/templates/mdx/update.mdx.js +1 -1
  126. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  127. package/dist/templates/mdx/what-is-doccupine.mdx.js +1 -1
  128. package/dist/templates/package.js +6 -6
  129. package/dist/templates/services/openapi/playgroundAllowlistStub.d.ts +1 -0
  130. package/dist/templates/services/openapi/playgroundAllowlistStub.js +4 -0
  131. package/dist/templates/types/openapi.d.ts +1 -0
  132. package/dist/templates/types/openapi.js +93 -0
  133. package/dist/templates/utils/apiAnchors.d.ts +1 -0
  134. package/dist/templates/utils/apiAnchors.js +39 -0
  135. package/dist/templates/utils/apiSnippets.d.ts +1 -0
  136. package/dist/templates/utils/apiSnippets.js +94 -0
  137. package/dist/templates/utils/orderNavItems.d.ts +1 -1
  138. package/dist/templates/utils/orderNavItems.js +3 -0
  139. package/dist/templates/utils/playgroundAllowlist.d.ts +1 -0
  140. package/dist/templates/utils/playgroundAllowlist.js +70 -0
  141. package/dist/templates/utils/ssrfGuard.d.ts +1 -0
  142. package/dist/templates/utils/ssrfGuard.js +217 -0
  143. package/package.json +3 -2
@@ -0,0 +1,603 @@
1
+ import path from "path";
2
+ import chalk from "chalk";
3
+ import { dereference } from "@readme/openapi-parser";
4
+ /* eslint-disable @typescript-eslint/no-explicit-any */
5
+ /** Default base route segment for the generated API reference section. */
6
+ export const DEFAULT_API_BASE_SLUG = "api-reference";
7
+ const HTTP_METHODS = [
8
+ "get",
9
+ "put",
10
+ "post",
11
+ "delete",
12
+ "options",
13
+ "head",
14
+ "patch",
15
+ "trace",
16
+ ];
17
+ const MAX_SERIALIZE_DEPTH = 20;
18
+ /**
19
+ * Slugifies a single route/anchor segment: lowercase, collapse any run of
20
+ * non-alphanumerics to a single dash, trim edge dashes. Never returns "" and
21
+ * never contains a slash, so each segment is exactly one path/anchor part.
22
+ * (Distinct from `generateSlug`, which preserves "/" for nested MDX routes.)
23
+ */
24
+ export function slugifySegment(input) {
25
+ const slug = String(input)
26
+ .toLowerCase()
27
+ .replace(/[^a-z0-9]+/g, "-")
28
+ .replace(/^-+|-+$/g, "");
29
+ return slug || "item";
30
+ }
31
+ /**
32
+ * Deterministic anchor id for a parameter, shared verbatim with the runtime
33
+ * component so deep links resolve. Top-level: `param-{in}-{name}`; nested schema
34
+ * properties append their parent path: `param-body-user-address-city`.
35
+ */
36
+ export function buildParamAnchor(name, location, parentPath = []) {
37
+ return ["param", location, ...parentPath, name].map(slugifySegment).join("-");
38
+ }
39
+ /**
40
+ * Returns a deeply-cloned, JSON-serializable copy of `value`. A dereferenced
41
+ * OpenAPI tree contains live circular references for recursive schemas, so a
42
+ * naive `JSON.stringify` would throw. Cycles (an object still on the current
43
+ * descent path) and over-deep nesting collapse to an `{ "x-circular": true }`
44
+ * placeholder. Sibling/shared (acyclic) references are fully expanded.
45
+ */
46
+ function toSerializable(value, seen = new WeakSet(), depth = 0) {
47
+ if (value === null || typeof value !== "object")
48
+ return value;
49
+ if (depth > MAX_SERIALIZE_DEPTH)
50
+ return { "x-circular": true };
51
+ if (seen.has(value))
52
+ return { "x-circular": true };
53
+ seen.add(value);
54
+ let result;
55
+ if (Array.isArray(value)) {
56
+ result = value.map((item) => toSerializable(item, seen, depth + 1));
57
+ }
58
+ else {
59
+ result = {};
60
+ for (const [key, item] of Object.entries(value)) {
61
+ result[key] = toSerializable(item, seen, depth + 1);
62
+ }
63
+ }
64
+ seen.delete(value);
65
+ return result;
66
+ }
67
+ /** Picks `example`, else the first of `examples` (OpenAPI example object). */
68
+ function pickExample(source) {
69
+ if (source == null)
70
+ return undefined;
71
+ if (source.example !== undefined)
72
+ return toSerializable(source.example);
73
+ const examples = source.examples;
74
+ if (examples && typeof examples === "object") {
75
+ const first = Object.values(examples)[0];
76
+ if (first && typeof first === "object" && "value" in first) {
77
+ return toSerializable(first.value);
78
+ }
79
+ if (first !== undefined)
80
+ return toSerializable(first);
81
+ }
82
+ return undefined;
83
+ }
84
+ /** Maps an OpenAPI `content` map to an array of media-type descriptors. */
85
+ function mapContent(content) {
86
+ if (!content || typeof content !== "object")
87
+ return [];
88
+ return Object.entries(content).map(([contentType, mt]) => {
89
+ const media = mt;
90
+ const descriptor = { contentType };
91
+ if (media?.schema !== undefined)
92
+ descriptor.schema = toSerializable(media.schema);
93
+ const example = pickExample(media);
94
+ if (example !== undefined)
95
+ descriptor.example = example;
96
+ return descriptor;
97
+ });
98
+ }
99
+ /** Maps an OpenAPI `servers` array to serializable server descriptors. */
100
+ function mapServers(servers) {
101
+ if (!Array.isArray(servers))
102
+ return [];
103
+ return servers
104
+ .filter((s) => s && typeof s.url === "string")
105
+ .map((s) => {
106
+ const descriptor = { url: s.url };
107
+ if (s.description)
108
+ descriptor.description = s.description;
109
+ if (s.variables && typeof s.variables === "object") {
110
+ descriptor.variables = toSerializable(s.variables);
111
+ }
112
+ return descriptor;
113
+ });
114
+ }
115
+ /** Substitutes `{var}` placeholders in a server URL with variable defaults. */
116
+ function resolveServerUrl(server) {
117
+ let url = server.url;
118
+ if (server.variables) {
119
+ for (const [name, variable] of Object.entries(server.variables)) {
120
+ url = url.replaceAll(`{${name}}`, variable?.default ?? "");
121
+ }
122
+ }
123
+ return url;
124
+ }
125
+ /**
126
+ * True when a host literal is loopback/private/link-local/CGNAT (or localhost).
127
+ * Used ONLY at build time to mark an allowlist entry `allowPrivate` when the
128
+ * spec's own declared server is a local-dev host. The runtime SSRF guard still
129
+ * enforces the range checks; this just records the operator's explicit intent.
130
+ */
131
+ function isLocalOrPrivateHost(host) {
132
+ if (host === "localhost" || host.endsWith(".localhost"))
133
+ return true;
134
+ if (host === "::1")
135
+ return true;
136
+ // IPv6 link-local (fe80::/10) and unique-local (fc00::/7 -> fc../fd..).
137
+ if (host.startsWith("fe80:") ||
138
+ host.startsWith("fc") ||
139
+ host.startsWith("fd")) {
140
+ return true;
141
+ }
142
+ const m = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.\d{1,3}$/);
143
+ if (m) {
144
+ const a = Number(m[1]);
145
+ const b = Number(m[2]);
146
+ if (a === 0 || a === 127 || a === 10)
147
+ return true;
148
+ if (a === 169 && b === 254)
149
+ return true;
150
+ if (a === 172 && b >= 16 && b <= 31)
151
+ return true;
152
+ if (a === 192 && b === 168)
153
+ return true;
154
+ if (a === 100 && b >= 64 && b <= 127)
155
+ return true;
156
+ }
157
+ return false;
158
+ }
159
+ /** Derives an allowlist entry from a server, or null for relative/non-http. */
160
+ function serverToAllowlistEntry(server) {
161
+ let url;
162
+ try {
163
+ url = new URL(resolveServerUrl(server));
164
+ }
165
+ catch {
166
+ return null; // relative server URL — no cross-origin host to allow
167
+ }
168
+ if (url.protocol !== "http:" && url.protocol !== "https:")
169
+ return null;
170
+ const host = url.hostname.toLowerCase().replace(/\.$/, "");
171
+ const entry = {
172
+ scheme: url.protocol === "https:" ? "https" : "http",
173
+ host,
174
+ port: url.port ? Number(url.port) : null,
175
+ };
176
+ if (url.pathname && url.pathname !== "/") {
177
+ entry.basePath = url.pathname.replace(/\/+$/, "");
178
+ }
179
+ if (isLocalOrPrivateHost(host))
180
+ entry.allowPrivate = true;
181
+ return entry;
182
+ }
183
+ /** Merges path-level and operation-level parameters; op overrides by name+in. */
184
+ function mergeParameters(pathParams, opParams) {
185
+ const byKey = new Map();
186
+ const add = (list) => {
187
+ if (!Array.isArray(list))
188
+ return;
189
+ for (const p of list) {
190
+ if (p && typeof p.name === "string" && typeof p.in === "string") {
191
+ byKey.set(`${p.in}:${p.name}`, p);
192
+ }
193
+ }
194
+ };
195
+ add(pathParams);
196
+ add(opParams); // operation wins on collision
197
+ return [...byKey.values()];
198
+ }
199
+ /** Resolves security requirements to a deduped list with schemes attached. */
200
+ function resolveSecurity(requirements, schemes) {
201
+ if (!Array.isArray(requirements))
202
+ return [];
203
+ const byName = new Map();
204
+ for (const requirement of requirements) {
205
+ if (!requirement || typeof requirement !== "object")
206
+ continue;
207
+ for (const [schemeName, scopes] of Object.entries(requirement)) {
208
+ const existing = byName.get(schemeName);
209
+ const scopeList = Array.isArray(scopes) ? scopes : [];
210
+ if (existing) {
211
+ existing.scopes = [...new Set([...existing.scopes, ...scopeList])];
212
+ continue;
213
+ }
214
+ const rawScheme = schemes?.[schemeName];
215
+ const descriptor = {
216
+ schemeName,
217
+ scopes: scopeList,
218
+ };
219
+ if (rawScheme && typeof rawScheme === "object") {
220
+ descriptor.scheme = toSerializable(rawScheme);
221
+ }
222
+ byName.set(schemeName, descriptor);
223
+ }
224
+ }
225
+ return [...byName.values()];
226
+ }
227
+ function firstLine(text) {
228
+ if (typeof text !== "string")
229
+ return "";
230
+ return text.split("\n")[0]?.trim() ?? "";
231
+ }
232
+ /**
233
+ * Parses one or more OpenAPI specs and exposes everything the generator needs:
234
+ * the operation descriptors, lookup indices for the MDX frontmatter path,
235
+ * synthetic sidebar/sitemap `PageMeta` objects, per-endpoint markdown bodies
236
+ * (for llms output), and the request-execution allowlist.
237
+ *
238
+ * `load()` never throws: a spec that fails to parse is logged and skipped so one
239
+ * malformed file cannot abort a build or crash a watcher.
240
+ */
241
+ export class OpenApiRegistry {
242
+ operations = [];
243
+ byOperationId = new Map();
244
+ byMethodPath = new Map();
245
+ pages = [];
246
+ bodies = new Map();
247
+ allowlistEntries = [];
248
+ get all() {
249
+ return this.operations;
250
+ }
251
+ get isEmpty() {
252
+ return this.operations.length === 0;
253
+ }
254
+ async load(specs, rootDir, apiBaseSlug = DEFAULT_API_BASE_SLUG) {
255
+ this.operations = [];
256
+ this.byOperationId.clear();
257
+ this.byMethodPath.clear();
258
+ this.pages = [];
259
+ this.bodies.clear();
260
+ this.allowlistEntries = [];
261
+ const multi = specs.length > 1;
262
+ const usedSlugs = new Set();
263
+ const allowlistKeys = new Set();
264
+ for (const spec of specs) {
265
+ const absolute = path.resolve(rootDir, spec.file);
266
+ let doc;
267
+ try {
268
+ doc = await dereference(absolute);
269
+ }
270
+ catch (error) {
271
+ console.error(chalk.red(`❌ Failed to parse OpenAPI spec "${spec.file}":`), error instanceof Error ? error.message : error);
272
+ continue;
273
+ }
274
+ try {
275
+ this.ingest(doc, spec, multi, apiBaseSlug, usedSlugs, allowlistKeys);
276
+ }
277
+ catch (error) {
278
+ console.error(chalk.red(`❌ Failed to process OpenAPI spec "${spec.file}":`), error instanceof Error ? error.message : error);
279
+ }
280
+ }
281
+ }
282
+ /** Fresh copies of the synthetic pages (caller may mutate/spread safely). */
283
+ syntheticPages() {
284
+ return this.pages.map((page) => ({ ...page }));
285
+ }
286
+ bodyForSlug(slug) {
287
+ return this.bodies.get(slug);
288
+ }
289
+ allowlist() {
290
+ return this.allowlistEntries.map((entry) => ({ ...entry }));
291
+ }
292
+ /** Looks up an operation by `operationId` or by `"METHOD /path"`. */
293
+ lookup(ref) {
294
+ const trimmed = ref.trim();
295
+ if (/\s/.test(trimmed)) {
296
+ const parts = trimmed.split(/\s+/);
297
+ const method = parts.shift() ?? "";
298
+ return this.byMethodPath.get(`${method.toUpperCase()} ${parts.join(" ")}`);
299
+ }
300
+ return this.byOperationId.get(trimmed);
301
+ }
302
+ ingest(doc, spec, multi, apiBaseSlug, usedSlugs, allowlistKeys) {
303
+ const base = multi
304
+ ? `${apiBaseSlug}/${slugifySegment(spec.name)}`
305
+ : apiBaseSlug;
306
+ const rootServers = mapServers(doc.servers);
307
+ this.addAllowlist(rootServers, allowlistKeys);
308
+ const schemes = doc.components?.securitySchemes ?? {};
309
+ // Category ordering: honour the spec's top-level `tags` order; unknown tags
310
+ // are appended in first-appearance order.
311
+ const tagOrder = new Map();
312
+ let nextTagOrder = 0;
313
+ if (Array.isArray(doc.tags)) {
314
+ doc.tags.forEach((tag) => {
315
+ if (tag && typeof tag.name === "string" && !tagOrder.has(tag.name)) {
316
+ tagOrder.set(tag.name, nextTagOrder++);
317
+ }
318
+ });
319
+ }
320
+ const withinTag = new Map();
321
+ const paths = doc.paths ?? {};
322
+ for (const [pathKey, pathItemRaw] of Object.entries(paths)) {
323
+ const pathItem = pathItemRaw;
324
+ if (!pathItem || typeof pathItem !== "object")
325
+ continue;
326
+ const pathServers = mapServers(pathItem.servers);
327
+ this.addAllowlist(pathServers, allowlistKeys);
328
+ const pathParams = pathItem.parameters;
329
+ for (const method of HTTP_METHODS) {
330
+ const opRaw = pathItem[method];
331
+ if (!opRaw || typeof opRaw !== "object")
332
+ continue;
333
+ const opServers = mapServers(opRaw.servers);
334
+ this.addAllowlist(opServers, allowlistKeys);
335
+ const effectiveServers = opServers.length
336
+ ? opServers
337
+ : pathServers.length
338
+ ? pathServers
339
+ : rootServers;
340
+ const parameters = mergeParameters(pathParams, opRaw.parameters).map((p) => {
341
+ const descriptor = {
342
+ name: p.name,
343
+ in: p.in,
344
+ required: p.in === "path" ? true : Boolean(p.required),
345
+ anchorId: buildParamAnchor(p.name, p.in),
346
+ };
347
+ if (p.deprecated)
348
+ descriptor.deprecated = true;
349
+ if (p.description)
350
+ descriptor.description = p.description;
351
+ const schema = p.schema ?? (p.type ? { type: p.type } : undefined);
352
+ if (schema !== undefined)
353
+ descriptor.schema = toSerializable(schema);
354
+ const example = pickExample(p);
355
+ if (example !== undefined)
356
+ descriptor.example = example;
357
+ return descriptor;
358
+ });
359
+ let requestBody;
360
+ if (opRaw.requestBody?.content) {
361
+ requestBody = {
362
+ required: Boolean(opRaw.requestBody.required),
363
+ content: mapContent(opRaw.requestBody.content),
364
+ };
365
+ if (opRaw.requestBody.description) {
366
+ requestBody.description = opRaw.requestBody.description;
367
+ }
368
+ }
369
+ const responses = Object.entries(opRaw.responses ?? {}).map(([status, r]) => {
370
+ const raw = r;
371
+ const response = {
372
+ status,
373
+ content: raw?.content ? mapContent(raw.content) : [],
374
+ headers: raw?.headers
375
+ ? Object.entries(raw.headers).map(([name, h]) => {
376
+ const rawHeader = h;
377
+ const header = {
378
+ name,
379
+ };
380
+ if (rawHeader?.description)
381
+ header.description = rawHeader.description;
382
+ if (rawHeader?.schema !== undefined) {
383
+ header.schema = toSerializable(rawHeader.schema);
384
+ }
385
+ return header;
386
+ })
387
+ : [],
388
+ };
389
+ if (raw?.description)
390
+ response.description = raw.description;
391
+ return response;
392
+ });
393
+ const tags = Array.isArray(opRaw.tags)
394
+ ? opRaw.tags.filter((t) => typeof t === "string")
395
+ : [];
396
+ const primaryTag = tags[0] ?? "Endpoints";
397
+ const opSlug = opRaw.operationId
398
+ ? slugifySegment(String(opRaw.operationId))
399
+ : slugifySegment(`${method}-${pathKey}`);
400
+ const slug = this.uniqueSlug(`${base}/${slugifySegment(primaryTag)}/${opSlug}`, usedSlugs);
401
+ const methodUpper = method.toUpperCase();
402
+ const descriptor = {
403
+ specName: spec.name,
404
+ method,
405
+ path: pathKey,
406
+ tags,
407
+ parameters,
408
+ responses,
409
+ servers: effectiveServers,
410
+ security: resolveSecurity(opRaw.security ?? doc.security, schemes),
411
+ slug,
412
+ endpointAnchor: `endpoint-${slugifySegment(method)}-${slugifySegment(pathKey)}`,
413
+ };
414
+ if (opRaw.operationId)
415
+ descriptor.operationId = String(opRaw.operationId);
416
+ if (opRaw.summary)
417
+ descriptor.summary = opRaw.summary;
418
+ if (opRaw.description)
419
+ descriptor.description = opRaw.description;
420
+ if (opRaw.deprecated)
421
+ descriptor.deprecated = true;
422
+ if (requestBody)
423
+ descriptor.requestBody = requestBody;
424
+ this.operations.push(descriptor);
425
+ if (descriptor.operationId) {
426
+ this.byOperationId.set(descriptor.operationId, descriptor);
427
+ }
428
+ this.byMethodPath.set(`${methodUpper} ${pathKey}`, descriptor);
429
+ if (!tagOrder.has(primaryTag))
430
+ tagOrder.set(primaryTag, nextTagOrder++);
431
+ const order = withinTag.get(primaryTag) ?? 0;
432
+ withinTag.set(primaryTag, order + 1);
433
+ const title = opRaw.summary || `${methodUpper} ${pathKey}`;
434
+ this.pages.push({
435
+ slug,
436
+ title,
437
+ description: opRaw.summary ||
438
+ firstLine(opRaw.description) ||
439
+ `${methodUpper} ${pathKey}`,
440
+ date: null,
441
+ category: primaryTag,
442
+ path: `@openapi/${spec.name}/${method}${pathKey}`,
443
+ categoryOrder: tagOrder.get(primaryTag) ?? 0,
444
+ order,
445
+ section: apiBaseSlug,
446
+ httpMethod: methodUpper,
447
+ });
448
+ this.bodies.set(slug, buildEndpointBody(title, methodUpper, pathKey, opRaw));
449
+ }
450
+ }
451
+ }
452
+ uniqueSlug(candidate, used) {
453
+ if (!used.has(candidate)) {
454
+ used.add(candidate);
455
+ return candidate;
456
+ }
457
+ let n = 2;
458
+ let slug = `${candidate}-${n}`;
459
+ while (used.has(slug))
460
+ slug = `${candidate}-${++n}`;
461
+ used.add(slug);
462
+ console.warn(chalk.yellow(`⚠️ Duplicate API route slug "${candidate}"; using "${slug}"`));
463
+ return slug;
464
+ }
465
+ addAllowlist(servers, keys) {
466
+ for (const server of servers) {
467
+ const entry = serverToAllowlistEntry(server);
468
+ if (!entry)
469
+ continue;
470
+ const key = `${entry.scheme}://${entry.host}:${entry.port ?? ""}${entry.basePath ?? ""}`;
471
+ if (keys.has(key))
472
+ continue;
473
+ keys.add(key);
474
+ this.allowlistEntries.push(entry);
475
+ }
476
+ }
477
+ }
478
+ /** Minimal markdown body for an endpoint, used by the llms.txt aggregation. */
479
+ function buildEndpointBody(title, methodUpper, pathKey, opRaw) {
480
+ const lines = [`# ${title}`, "", `\`${methodUpper} ${pathKey}\``];
481
+ if (opRaw.description && typeof opRaw.description === "string") {
482
+ lines.push("", opRaw.description);
483
+ }
484
+ else if (opRaw.summary && opRaw.summary !== title) {
485
+ lines.push("", opRaw.summary);
486
+ }
487
+ return lines.join("\n");
488
+ }
489
+ /** Human-readable type label for a (dereferenced) JSON schema. */
490
+ function docSchemaType(schema) {
491
+ if (!schema || typeof schema !== "object")
492
+ return "any";
493
+ if (Array.isArray(schema.type))
494
+ return schema.type.join(" | ");
495
+ if (schema.type === "array")
496
+ return `array of ${docSchemaType(schema.items)}`;
497
+ if (typeof schema.type === "string") {
498
+ return schema.format ? `${schema.type} (${schema.format})` : schema.type;
499
+ }
500
+ if (schema.properties)
501
+ return "object";
502
+ if (Array.isArray(schema.enum))
503
+ return "enum";
504
+ return "any";
505
+ }
506
+ /** Collapses a description to a single inline line safe inside JSX children. */
507
+ function inlineText(text) {
508
+ if (typeof text !== "string")
509
+ return "";
510
+ return text.replace(/\s+/g, " ").trim();
511
+ }
512
+ /** The object schema whose `properties` we can document (unwraps arrays). */
513
+ function objectShape(schema) {
514
+ if (!schema || typeof schema !== "object")
515
+ return null;
516
+ if (schema.type === "array")
517
+ return objectShape(schema.items);
518
+ if (schema.properties && typeof schema.properties === "object")
519
+ return schema;
520
+ return null;
521
+ }
522
+ /**
523
+ * Renders one parameter/property as a `<Field>`, recursing into nested object
524
+ * properties up to `MAX_FIELD_DEPTH` levels. Nested fields are emitted flush so
525
+ * MDX does not treat the indentation as a code block.
526
+ */
527
+ const MAX_FIELD_DEPTH = 2;
528
+ function renderDocField(name, schema, required, description, depth) {
529
+ const type = docSchemaType(schema);
530
+ const desc = inlineText(description ?? schema?.description);
531
+ const lines = [
532
+ `<Field value="${name}" type="${type}"${required ? " required" : ""}>`,
533
+ ];
534
+ if (desc)
535
+ lines.push(desc);
536
+ const shape = depth < MAX_FIELD_DEPTH ? objectShape(schema) : null;
537
+ if (shape) {
538
+ const req = Array.isArray(shape.required) ? shape.required : [];
539
+ for (const [propName, propSchema] of Object.entries(shape.properties)) {
540
+ lines.push(renderDocField(propName, propSchema, req.includes(propName), undefined, depth + 1));
541
+ }
542
+ }
543
+ lines.push(`</Field>`);
544
+ return lines.join("\n");
545
+ }
546
+ const PARAM_LOCATION_TITLES = {
547
+ path: "Path parameters",
548
+ query: "Query parameters",
549
+ header: "Header parameters",
550
+ cookie: "Cookie parameters",
551
+ };
552
+ /**
553
+ * Builds the MDX body for a generated endpoint page: the operation description,
554
+ * followed by `<Field>` documentation for the parameters and request body, and
555
+ * a schema/example code block per response. Rendered above the playground.
556
+ */
557
+ export function buildEndpointDoc(op) {
558
+ const out = [];
559
+ if (op.description)
560
+ out.push(op.description);
561
+ else if (op.summary)
562
+ out.push(op.summary);
563
+ for (const location of ["path", "query", "header", "cookie"]) {
564
+ const params = op.parameters.filter((p) => p.in === location);
565
+ if (params.length === 0)
566
+ continue;
567
+ out.push(`## ${PARAM_LOCATION_TITLES[location]}`);
568
+ for (const p of params) {
569
+ out.push(renderDocField(p.name, p.schema, p.required, p.description, 0));
570
+ }
571
+ }
572
+ const body = op.requestBody?.content.find((m) => m.contentType.includes("json")) ??
573
+ op.requestBody?.content[0];
574
+ if (body?.schema !== undefined) {
575
+ out.push("## Request body");
576
+ const shape = objectShape(body.schema);
577
+ if (shape) {
578
+ const req = Array.isArray(shape.required) ? shape.required : [];
579
+ for (const [propName, propSchema] of Object.entries(shape.properties)) {
580
+ out.push(renderDocField(propName, propSchema, req.includes(propName), undefined, 0));
581
+ }
582
+ }
583
+ else {
584
+ out.push("```json\n" + JSON.stringify(body.schema, null, 2) + "\n```");
585
+ }
586
+ }
587
+ if (op.responses.length > 0) {
588
+ out.push("## Responses");
589
+ for (const response of op.responses) {
590
+ out.push(`### ${response.status}`);
591
+ if (response.description) {
592
+ out.push(inlineText(response.description));
593
+ }
594
+ const media = response.content.find((m) => m.contentType.includes("json")) ??
595
+ response.content[0];
596
+ const payload = media?.example ?? media?.schema;
597
+ if (payload !== undefined) {
598
+ out.push("```json\n" + JSON.stringify(payload, null, 2) + "\n```");
599
+ }
600
+ }
601
+ }
602
+ return out.join("\n\n");
603
+ }