-
Notifications
You must be signed in to change notification settings - Fork 516
Expand file tree
/
Copy pathgenerate-functional-api-docs.mjs
More file actions
538 lines (448 loc) Β· 16.9 KB
/
generate-functional-api-docs.mjs
File metadata and controls
538 lines (448 loc) Β· 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import fs from 'fs';
import { generateFiles } from 'fumadocs-openapi';
import path from 'path';
// Use relative paths to avoid path duplication issues
const OPENAPI_DIR = './openapi';
const OUTPUT_DIR = './content/api';
const TEMPLATES_API_DIR = './templates-api';
// Define the functional tag order based on user requirements
const FUNCTIONAL_TAGS = [
'Anonymous',
'API Keys',
'CLI Authentication',
'Contact Channels',
'Emails',
'Oauth', // Note: OpenAPI uses "Oauth" not "OAuth"
'OTP',
'Password',
'Payments',
'Permissions',
'Projects',
'Sessions',
'Teams',
'Users',
'Others' // For any miscellaneous endpoints
];
/**
* Create a filtered OpenAPI spec containing only endpoints with the specified tag
*/
function createTagFilteredSpec(originalSpec, targetTag) {
const filteredSpec = {
...originalSpec,
paths: {},
webhooks: {}
};
// Filter regular API paths
if (originalSpec.paths) {
for (const [path, methods] of Object.entries(originalSpec.paths)) {
const filteredMethods = {};
for (const [method, endpoint] of Object.entries(methods)) {
if (endpoint.tags && endpoint.tags.includes(targetTag)) {
filteredMethods[method] = endpoint;
}
}
// Only include the path if it has methods with the target tag
if (Object.keys(filteredMethods).length > 0) {
filteredSpec.paths[path] = filteredMethods;
}
}
}
// Filter webhooks
if (originalSpec.webhooks) {
for (const [webhookName, methods] of Object.entries(originalSpec.webhooks)) {
const filteredMethods = {};
for (const [method, endpoint] of Object.entries(methods)) {
if (endpoint.tags && endpoint.tags.includes(targetTag)) {
filteredMethods[method] = endpoint;
}
}
// Only include the webhook if it has methods with the target tag
if (Object.keys(filteredMethods).length > 0) {
filteredSpec.webhooks[webhookName] = filteredMethods;
}
}
}
return filteredSpec;
}
/**
* Get all unique tags from an OpenAPI spec
*/
function extractTags(spec) {
const tags = new Set();
// Handle regular API paths
if (spec.paths) {
for (const methods of Object.values(spec.paths)) {
for (const endpoint of Object.values(methods)) {
if (endpoint.tags) {
endpoint.tags.forEach(tag => tags.add(tag));
}
}
}
}
// Handle webhooks (different structure)
if (spec.webhooks) {
for (const webhookMethods of Object.values(spec.webhooks)) {
for (const endpoint of Object.values(webhookMethods)) {
if (endpoint.tags) {
endpoint.tags.forEach(tag => tags.add(tag));
}
}
}
}
return Array.from(tags);
}
/**
* Convert tag name to a URL-friendly slug
*/
function tagToSlug(tag) {
return tag.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^a-z0-9-]/g, '');
}
/**
* Convert tag name to a readable folder name
*/
function tagToFolderName(tag) {
// Special case mappings
const specialCases = {
'Oauth': 'oauth',
'API Keys': 'api-keys',
'CLI Authentication': 'cli-authentication',
'Contact Channels': 'contact-channels',
'OTP': 'otp'
};
return specialCases[tag] || tag.toLowerCase().replace(/\s+/g, '-');
}
/**
* Recursively find all MDX files in a directory
*/
function findMdxFiles(dir) {
const files = [];
if (!fs.existsSync(dir)) {
return files;
}
const items = fs.readdirSync(dir);
for (const item of items) {
const fullPath = path.join(dir, item);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
files.push(...findMdxFiles(fullPath));
} else if (item.endsWith('.mdx')) {
files.push(fullPath);
}
}
return files;
}
/**
* Flatten the generated file structure
*/
function flattenGeneratedFiles(functionalCategoryPath) {
// Skip flattening - fumadocs expects the directory structure to match routing
// The original nested structure from fumadocs-openapi is what we want to keep
console.log(` π Keeping original directory structure for ${functionalCategoryPath}`);
}
/**
* Update document references in MDX files to point to permanent filtered OpenAPI files
*/
function updateDocumentReferences(functionalCategoryPath, newDocumentPath) {
const mdxFiles = findMdxFiles(functionalCategoryPath);
for (const filePath of mdxFiles) {
const content = fs.readFileSync(filePath, 'utf8');
// Update the document reference in the APIPage component
// Match both old public/openapi paths and temp files
const updatedContent = content.replace(
/document=\{"(public\/openapi\/|openapi\/)[^"]+"\}/g,
`document={"${newDocumentPath}"}`
);
if (content !== updatedContent) {
fs.writeFileSync(filePath, updatedContent);
console.log(` π Updated document reference in ${path.basename(filePath)}`);
}
}
}
/**
* Replace APIPage with EnhancedAPIPage in generated MDX files
*/
function replaceAPIPageWithEnhanced(functionalCategoryPath) {
const mdxFiles = findMdxFiles(functionalCategoryPath);
for (const filePath of mdxFiles) {
const content = fs.readFileSync(filePath, 'utf8');
// Replace APIPage with EnhancedAPIPage
const updatedContent = content.replace(
/<APIPage\s+/g,
'<EnhancedAPIPage '
);
if (content !== updatedContent) {
fs.writeFileSync(filePath, updatedContent);
console.log(` π Replaced APIPage with EnhancedAPIPage in ${path.basename(filePath)}`);
}
}
}
/**
* Replace APIPage with WebhooksAPIPage in generated MDX files for webhooks
*/
function replaceAPIPageWithWebhooks(functionalCategoryPath) {
const mdxFiles = findMdxFiles(functionalCategoryPath);
for (const filePath of mdxFiles) {
const content = fs.readFileSync(filePath, 'utf8');
// Replace APIPage with WebhooksAPIPage
const updatedContent = content.replace(
/<APIPage\s+/g,
'<WebhooksAPIPage '
);
if (content !== updatedContent) {
fs.writeFileSync(filePath, updatedContent);
console.log(` π Replaced APIPage with WebhooksAPIPage in ${path.basename(filePath)}`);
}
}
}
/**
* Add description prop to EnhancedAPIPage components from frontmatter
*/
function addDescriptionToEnhancedAPIPage(functionalCategoryPath) {
const mdxFiles = findMdxFiles(functionalCategoryPath);
for (const filePath of mdxFiles) {
const content = fs.readFileSync(filePath, 'utf8');
// Extract description from frontmatter
const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
if (!frontmatterMatch) continue;
const frontmatterContent = frontmatterMatch[1];
let description = null;
// Handle multiline YAML descriptions (">-" or ">" syntax)
if (frontmatterContent.includes('description: >')) {
// Extract multiline description
const multilineMatch = frontmatterContent.match(/description:\s*>-?\s*\n((?:\s{2,}.*\n?)*)/);
if (multilineMatch) {
// Join the indented lines and clean up
description = multilineMatch[1]
.split('\n')
.map(line => line.replace(/^\s{2,}/, '')) // Remove leading indentation
.filter(line => line.trim()) // Remove empty lines
.join(' ')
.trim();
}
} else {
// Handle single-line descriptions
const singleLineMatch = frontmatterContent.match(/description:\s*['"]?([^'"]+?)['"]?\s*$/m);
if (singleLineMatch) {
description = singleLineMatch[1].trim();
}
}
if (!description) continue;
// Add description prop to EnhancedAPIPage if not already present
const updatedContent = content.replace(
/(<EnhancedAPIPage[^>]*?)(\s+\/?>)/g,
(match, componentStart, componentEnd) => {
// Check if description prop already exists
if (componentStart.includes('description=')) {
return match;
}
// Add description prop
return `${componentStart} description={"${description.replace(/"/g, '\\"')}"}${componentEnd}`;
}
);
if (content !== updatedContent) {
fs.writeFileSync(filePath, updatedContent);
console.log(` π Added description prop to EnhancedAPIPage in ${path.basename(filePath)}`);
}
}
}
/**
* Add description prop to WebhooksAPIPage components from frontmatter
*/
function addDescriptionToWebhooksAPIPage(functionalCategoryPath) {
const mdxFiles = findMdxFiles(functionalCategoryPath);
for (const filePath of mdxFiles) {
const content = fs.readFileSync(filePath, 'utf8');
// Extract description from frontmatter
const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
if (!frontmatterMatch) continue;
const frontmatterContent = frontmatterMatch[1];
let description = null;
// Handle multiline YAML descriptions (">-" or ">" syntax)
if (frontmatterContent.includes('description: >')) {
// Extract multiline description
const multilineMatch = frontmatterContent.match(/description:\s*>-?\s*\n((?:\s{2,}.*\n?)*)/);
if (multilineMatch) {
// Join the indented lines and clean up
description = multilineMatch[1]
.split('\n')
.map(line => line.replace(/^\s{2,}/, '')) // Remove leading indentation
.filter(line => line.trim()) // Remove empty lines
.join(' ')
.trim();
}
} else {
// Handle single-line descriptions
const singleLineMatch = frontmatterContent.match(/description:\s*['"]?([^'"]+?)['"]?\s*$/m);
if (singleLineMatch) {
description = singleLineMatch[1].trim();
}
}
if (!description) continue;
// Add description prop to WebhooksAPIPage if not already present
const updatedContent = content.replace(
/(<WebhooksAPIPage[^>]*?)(\s+\/?>)/g,
(match, componentStart, componentEnd) => {
// Check if description prop already exists
if (componentStart.includes('description=')) {
return match;
}
// Add description prop
return `${componentStart} description={"${description.replace(/"/g, '\\"')}"}${componentEnd}`;
}
);
if (content !== updatedContent) {
fs.writeFileSync(filePath, updatedContent);
console.log(` π Added description prop to WebhooksAPIPage in ${path.basename(filePath)}`);
}
}
}
/**
* Copy the API overview page from template
*/
function copyAPIOverviewFromTemplate() {
console.log('π Copying API overview page from template...');
const templatePath = path.join(TEMPLATES_API_DIR, 'overview.mdx');
const outputPath = path.join(OUTPUT_DIR, 'overview.mdx');
if (!fs.existsSync(templatePath)) {
console.error(`β Template file not found: ${templatePath}`);
console.log(' Please create the template file first.');
return;
}
// Ensure output directory exists
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
// Copy the template file
fs.copyFileSync(templatePath, outputPath);
console.log('β
Copied API overview page from template');
}
async function generateFunctionalAPIDocs() {
console.log('π Starting functional OpenAPI documentation generation...\n');
// Ensure the OpenAPI directory exists
if (!fs.existsSync(OPENAPI_DIR)) {
console.log('Creating OpenAPI directory...');
fs.mkdirSync(OPENAPI_DIR, { recursive: true });
}
// Process each API type in complete isolation to avoid fumadocs conflicts
const apiTypes = ['client', 'server', 'admin', 'webhooks'];
for (const apiType of apiTypes) {
await processApiTypeInIsolation(apiType);
}
// Copy API overview page from template
copyAPIOverviewFromTemplate();
// Generate main API meta.json
console.log('π Generating main API navigation...');
const mainApiMetaPath = path.join(OUTPUT_DIR, 'meta.json');
const mainApiMeta = {
pages: [
'overview',
'client',
'server',
'admin',
'webhooks'
]
};
fs.writeFileSync(mainApiMetaPath, JSON.stringify(mainApiMeta, null, 2));
console.log('β
Generated main API meta.json');
console.log('\nπ Functional OpenAPI documentation generation complete!');
console.log(`π Documentation generated in: ${path.resolve(OUTPUT_DIR)}/`);
console.log('\nπ Structure:');
console.log(' /overview.mdx');
console.log(' /client/{functional-categories}/');
console.log(' /server/{functional-categories}/');
console.log(' /admin/{functional-categories}/');
console.log(' /webhooks/');
}
/**
* Process a single API type in complete isolation
*/
async function processApiTypeInIsolation(apiType) {
const jsonFile = path.join(OPENAPI_DIR, `${apiType}.json`);
if (!fs.existsSync(jsonFile)) {
console.log(`β οΈ OpenAPI file not found: ${jsonFile}`);
console.log(` Run 'pnpm run codegen' from the root to generate OpenAPI schemas first.`);
return;
}
console.log(`π Processing ${apiType} API in isolation...`);
// Read and parse the OpenAPI spec
const originalSpec = JSON.parse(fs.readFileSync(jsonFile, 'utf8'));
// Extract all tags from this API
const availableTags = extractTags(originalSpec);
console.log(` π Found tags: ${availableTags.join(', ')}`);
// Process each functional tag for this API type
const processedTags = [];
for (const tag of FUNCTIONAL_TAGS) {
if (!availableTags.includes(tag)) {
continue; // Skip tags not present in this API
}
console.log(` π Generating docs for ${tag}...`);
// Create filtered spec for this tag
const tagFilteredSpec = createTagFilteredSpec(originalSpec, tag);
// Create temporary file for this tag's spec
const tempSpecPath = path.join(OPENAPI_DIR, `temp-${apiType}-${tagToSlug(tag)}.json`);
fs.writeFileSync(tempSpecPath, JSON.stringify(tagFilteredSpec, null, 2));
try {
// Generate docs for this tag in isolation
const outputPath = path.join(OUTPUT_DIR, apiType, tagToFolderName(tag));
// Create permanent filtered OpenAPI file
const permanentSpecPath = path.join(OPENAPI_DIR, `${apiType}-${tagToSlug(tag)}.json`);
fs.writeFileSync(permanentSpecPath, JSON.stringify(tagFilteredSpec, null, 2));
// Process this tag completely in isolation - no fumadocs state shared between calls
await generateFiles({
input: [tempSpecPath],
output: outputPath,
includeDescription: false,
frontmatter: (title, description) => ({
title,
description,
full: true, // Use full-width layout for API docs
}),
});
console.log(` β
Generated ${tag} docs for ${apiType}`);
processedTags.push(tag);
// Keep original directory structure for proper fumadocs routing
flattenGeneratedFiles(outputPath);
// Update document references in MDX files
console.log(` π Updating document references for ${tag}...`);
updateDocumentReferences(outputPath, `openapi/${apiType}-${tagToSlug(tag)}.json`);
// Replace APIPage with appropriate component based on API type
if (apiType === 'webhooks') {
console.log(` π Replacing APIPage with WebhooksAPIPage for ${tag}...`);
replaceAPIPageWithWebhooks(outputPath);
// Add description prop to WebhooksAPIPage
console.log(` π Adding description prop to WebhooksAPIPage for ${tag}...`);
addDescriptionToWebhooksAPIPage(outputPath);
} else {
console.log(` π Replacing APIPage with EnhancedAPIPage for ${tag}...`);
replaceAPIPageWithEnhanced(outputPath);
// Add description prop to EnhancedAPIPage
console.log(` π Adding description prop to EnhancedAPIPage for ${tag}...`);
addDescriptionToEnhancedAPIPage(outputPath);
}
} catch (error) {
console.error(` β Error generating ${tag} docs for ${apiType}:`, error);
} finally {
// Clean up temporary file
if (fs.existsSync(tempSpecPath)) {
fs.unlinkSync(tempSpecPath);
}
}
}
// Generate meta.json for this API type
if (processedTags.length > 0) {
console.log(` π Generating navigation meta for ${apiType}...`);
const apiMetaPath = path.join(OUTPUT_DIR, apiType, 'meta.json');
const apiMeta = {
pages: processedTags.map(tag => tagToFolderName(tag))
};
fs.mkdirSync(path.dirname(apiMetaPath), { recursive: true });
fs.writeFileSync(apiMetaPath, JSON.stringify(apiMeta, null, 2));
console.log(` β
Generated meta.json for ${apiType} API`);
}
console.log(`π― Completed ${apiType} API processing (${processedTags.length} functional categories)\n`);
}
// Run the generator
generateFunctionalAPIDocs().catch((error) => {
console.error('β Failed to generate functional API documentation:', error);
process.exit(1);
});