forked from FlyNumber/markdown_docusaurus_plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
671 lines (558 loc) · 24.1 KB
/
index.js
File metadata and controls
671 lines (558 loc) · 24.1 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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
const fs = require('fs-extra');
const path = require('path');
/**
* Docusaurus plugin to copy raw markdown files to build output
* This allows users to view markdown source by appending .md to URLs
*/
// Helper function to extract attribute value from a tag string
function extractAttribute(tagString, attrName) {
const regex = new RegExp(`${attrName}=["']([^"']*)["']`);
const match = tagString.match(regex);
return match ? match[1] : null;
}
// Convert Tabs/TabItem components to readable markdown format
// Handles both standard <Tabs> and custom tab components like <ModelDropdownTabs>
function convertTabsToMarkdown(content) {
// Match standard Tabs and any custom component ending in "Tabs"
const tabsPattern = /<(\w*Tabs)[^>]*>([\s\S]*?)<\/\1>/g;
const processTabsBlock = (fullMatch, tagName, tabsContent) => {
// Match TabItem with any attribute order by capturing the entire opening tag
const tabItemPattern = /<TabItem\s+([^>]*)>([\s\S]*?)<\/TabItem>/g;
let result = [];
let match;
while ((match = tabItemPattern.exec(tabsContent)) !== null) {
const [, attributes, itemContent] = match;
// Extract label and value from attributes (works regardless of order)
const label = extractAttribute(attributes, 'label');
const value = extractAttribute(attributes, 'value');
// Use label if available, otherwise fall back to value
const displayLabel = label || value || 'Tab';
// Preserve the content as-is (don't strip indentation - it may be meaningful for lists)
const cleanContent = itemContent.trim();
result.push(`**${displayLabel}:**\n\n${cleanContent}`);
}
return result.join('\n\n---\n\n');
};
// Process repeatedly to handle nested tabs (innermost first)
let previousContent;
let currentContent = content;
do {
previousContent = currentContent;
currentContent = currentContent.replace(tabsPattern, processTabsBlock);
} while (currentContent !== previousContent);
// Clean up any leftover TabItem or Tabs closing tags that weren't matched
currentContent = currentContent.replace(/<\/TabItem>/g, '');
currentContent = currentContent.replace(/<\/\w*Tabs>/g, '');
// Also clean up orphaned opening tags (in case content wasn't properly structured)
currentContent = currentContent.replace(/<TabItem\s+[^>]*>/g, '');
currentContent = currentContent.replace(/<\w*Tabs[^>]*>/g, '');
return currentContent;
}
// Parse JavaScript array objects into an array of key-value objects
function parseArrayObjects(arrayContent) {
const objects = [];
const objRegex = /\{([^}]+)\}/g;
let objMatch;
while ((objMatch = objRegex.exec(arrayContent)) !== null) {
const obj = {};
// Match property: 'value' or property: "value" or property: value (for booleans/numbers)
const propRegex = /(\w+)\s*:\s*(?:'([^']*)'|"([^"]*)"|([^\s,}]+))/g;
let propMatch;
while ((propMatch = propRegex.exec(objMatch[1])) !== null) {
const key = propMatch[1];
const value = propMatch[2] || propMatch[3] || propMatch[4];
// Skip internal properties like 'default: true'
if (key !== 'default') {
obj[key] = value;
}
}
if (Object.keys(obj).length > 0) objects.push(obj);
}
return objects;
}
// Find the end of an export statement starting at the given position,
// properly tracking nested {}/[] so we don't stop at inner braces.
function findExportEnd(content, startIdx) {
let i = startIdx;
let depth = 0;
let inString = false;
let stringChar = '';
while (i < content.length) {
const ch = content[i];
if (inString) {
if (ch === '\\') { i += 2; continue; }
if (ch === stringChar) inString = false;
i++;
continue;
}
if (ch === '"' || ch === "'" || ch === '`') {
inString = true;
stringChar = ch;
} else if (ch === '{' || ch === '[' || ch === '(') {
depth++;
} else if (ch === '}' || ch === ']' || ch === ')') {
depth--;
if (depth <= 0) {
i++;
if (i < content.length && content[i] === ';') i++;
return i;
}
} else if (depth === 0 && ch === ';') {
return i + 1;
}
i++;
}
return i;
}
// Convert JavaScript export const arrays to readable markdown bullet lists
// Arrays of objects are converted to lists; other exports are removed
function convertExportsToMarkdown(content) {
// First, convert array exports that contain objects to bullet lists
content = content.replace(
/export\s+const\s+(\w+)\s*=\s*\[([\s\S]*?)\]\s*;?/g,
(match, varName, arrayContent) => {
const items = parseArrayObjects(arrayContent);
if (items.length === 0) return '';
let md = `**${varName}:**\n\n`;
items.forEach(obj => {
const pairs = Object.entries(obj)
.map(([k, v]) => `**${k}:** ${v}`)
.join(', ');
md += `- ${pairs}\n`;
});
return md + '\n';
}
);
// Remove all remaining export const statements, tracking nested {}/[] depth
const exportPattern = /^export\s+const\s+\w+\s*=\s*/gm;
let match;
const regions = [];
while ((match = exportPattern.exec(content)) !== null) {
const valueStart = match.index + match[0].length;
const end = findExportEnd(content, valueStart);
regions.push([match.index, end]);
}
for (let i = regions.length - 1; i >= 0; i--) {
content = content.slice(0, regions[i][0]) + content.slice(regions[i][1]);
}
return content;
}
// Convert DynamicCode components to fenced code blocks
function convertDynamicCodeToMarkdown(content) {
// Match <DynamicCode language="sh" ...>{`...`}</DynamicCode>
// Also capture any leading whitespace so we can remove it
return content.replace(
/^[ \t]*<DynamicCode\s+language="([^"]+)"[^>]*>([\s\S]*?)<\/DynamicCode>/gim,
(match, language, code) => {
// Clean up the code content:
// 1. Remove outer { and } (JSX expression wrapper)
// 2. Remove backticks (template literal)
// 3. Normalize indentation
let cleanCode = code.trim();
// Remove leading { and trailing }
cleanCode = cleanCode.replace(/^\s*\{\s*/, '').replace(/\s*\}\s*$/, '');
// Remove backticks (template literal delimiters)
cleanCode = cleanCode.replace(/^`/, '').replace(/`$/, '');
// Normalize indentation: find minimum indent and remove it from all lines
const lines = cleanCode.split('\n');
const nonEmptyLines = lines.filter(line => line.trim().length > 0);
if (nonEmptyLines.length > 0) {
const minIndent = Math.min(...nonEmptyLines.map(line => {
const match = line.match(/^(\s*)/);
return match ? match[1].length : 0;
}));
if (minIndent > 0) {
cleanCode = lines.map(line => line.slice(minIndent)).join('\n');
}
}
cleanCode = cleanCode.trim();
return '```' + language + '\n' + cleanCode + '\n```';
}
);
}
// Convert ConditionalContent components to labeled markdown sections
function convertConditionalContentToMarkdown(content) {
// Match <ConditionalContent ... condition={(model) => model.includes('Value')} > ... </ConditionalContent>
const pattern = /<ConditionalContent(?:[^>{]|\{[^}]*\})*>\s*([\s\S]*?)<\/ConditionalContent>/gi;
return content.replace(pattern, (match, innerContent) => {
// Extract the condition value from the tag (e.g., 'Llama' from model.includes('Llama'))
const conditionMatch = match.match(/\.includes\s*\(\s*['"]([^'"]+)['"]\s*\)/);
if (conditionMatch) {
const conditionValue = conditionMatch[1];
// Clean up the inner content
const cleanContent = innerContent.trim();
return `**${conditionValue} model:**\n\n${cleanContent}\n`;
}
// If no condition found, just return the inner content
return innerContent.trim();
});
}
// Convert Requirements component to a markdown link using the url attribute
function convertRequirementsToMarkdown(content) {
// Match <Requirements ... url="..." /> (self-closing)
// Handle multiline and various attribute orders
return content.replace(
/<Requirements(?:[^>]*?)url="([^"]+)"[^>]*?\/?>/gi,
(match, url) => {
return `[Read the requirements](${url})`;
}
);
}
// Unwrap MDX components by removing their tags but preserving inner content
function unwrapMdxComponents(content) {
// List of MDX components to unwrap (keeps growing as we find more)
// Note: ConditionalContent is handled separately by convertConditionalContentToMarkdown
// Note: Requirements is handled separately by convertRequirementsToMarkdown
const components = [
'ModelSelector',
'ModelDropdownTabs',
'InstallModular'
];
for (const comp of components) {
// Remove opening tags with any attributes
// Handle JSX expressions in attributes that may contain > inside {...}
// Pattern: match <Component, then any non->{, or {...} blocks, then >
content = content.replace(new RegExp(`<${comp}(?:[^>{]|\\{[^}]*\\})*>`, 'gis'), '');
// Remove closing tags
content = content.replace(new RegExp(`</${comp}>`, 'gi'), '');
}
return content;
}
// Remove div tags while preserving their inner content
function removeDivTags(content) {
// Remove opening div tags with any attributes (including className, style, etc.)
content = content.replace(/<div[^>]*>/gi, '');
// Remove closing div tags
content = content.replace(/<\/div>/gi, '');
return content;
}
// Remove MDX/JSX comments {/* ... */}
function removeMdxComments(content) {
// Match {/* ... */} including multiline comments
return content.replace(/\{\/\*[\s\S]*?\*\/\}/g, '');
}
// Collapse multiple consecutive blank lines into a single blank line
function collapseBlankLines(content) {
// Replace 3+ consecutive newlines (2+ blank lines) with just 2 newlines (1 blank line)
return content.replace(/\n{3,}/g, '\n\n');
}
// Convert details/summary components to readable markdown format
function convertDetailsToMarkdown(content) {
const detailsPattern = /<details>\s*<summary>(<strong>)?([^<]+)(<\/strong>)?<\/summary>([\s\S]*?)<\/details>/g;
return content.replace(detailsPattern, (fullMatch, strongOpen, summaryText, strongClose, detailsContent) => {
// Clean up the details content
const cleanContent = detailsContent
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0)
.join('\n')
.trim();
return `### ${summaryText.trim()}\n\n${cleanContent}`;
});
}
// Extract title from YAML frontmatter
function extractTitleFromFrontmatter(content) {
const frontmatterMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
if (frontmatterMatch) {
const frontmatter = frontmatterMatch[1];
// Match title: value (with optional quotes)
const titleMatch = frontmatter.match(/^title:\s*["']?([^"'\n]+)["']?\s*$/m);
if (titleMatch) {
return titleMatch[1].trim();
}
}
return null;
}
// Clean markdown content for raw display - remove MDX/Docusaurus-specific syntax
function cleanMarkdownForDisplay(content, filepath, docsPath = '/docs/') {
// Get the directory path for this file (relative to docs root)
const fileDir = filepath.replace(/[^/]*$/, ''); // Remove filename, keep directory
// Extract title from frontmatter before stripping it
const title = extractTitleFromFrontmatter(content);
// 1. Strip YAML front matter (--- at start, content, then ---)
content = content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '');
// 2. Remove import statements (MDX imports)
content = content.replace(/^import\s+.*?from\s+['"].*?['"];?\s*$/gm, '');
// 3. Remove MDX/JSX comments {/* ... */}
content = removeMdxComments(content);
// 4. Convert DynamicCode components to fenced code blocks
content = convertDynamicCodeToMarkdown(content);
// 4. Convert JavaScript export arrays to readable bullet lists
content = convertExportsToMarkdown(content);
// 5. Convert ConditionalContent to labeled sections
content = convertConditionalContentToMarkdown(content);
// 6. Convert Requirements component to link
content = convertRequirementsToMarkdown(content);
// Convert Button components with DocLink to markdown links
content = content.replace(
/<Button\s+component=\{DocLink\}\s+to=['"]([^'"]+)['"]>\s*([\s\S]*?)\s*<\/Button>/g,
'[$2]($1)'
);
// 7. Unwrap MDX components (remove tags, preserve inner content)
content = unwrapMdxComponents(content);
// 7. Remove div tags (preserve inner content)
content = removeDivTags(content);
// 7. Convert HTML images to markdown
// Pattern: <p align="center"><img src={require('./path').default} alt="..." width="..." /></p>
content = content.replace(
/<p align="center">\s*\n?\s*<img src=\{require\(['"]([^'"]+)['"]\)\.default\} alt="([^"]*)"(?:\s+width="[^"]*")?\s*\/>\s*\n?\s*<\/p>/g,
(match, imagePath, alt) => {
// Clean the path: remove @site/static prefix
const cleanPath = imagePath.replace('@site/static/', '/');
return ``;
}
);
// 4. Convert YouTube iframes to text links
content = content.replace(
/<iframe[^>]*src="https:\/\/www\.youtube\.com\/embed\/([a-zA-Z0-9_-]+)[^"]*"[^>]*title="([^"]*)"[^>]*>[\s\S]*?<\/iframe>/g,
'Watch the video: [$2](https://www.youtube.com/watch?v=$1)'
);
// 5. Clean HTML5 video tags - keep HTML but add fallback text
content = content.replace(
/<video[^>]*>\s*<source src=["']([^"']+)["'][^>]*>\s*<\/video>/g,
'<video controls>\n <source src="$1" type="video/mp4" />\n <p>Video demonstration: $1</p>\n</video>'
);
// 6. Remove <Head> components with structured data (SEO metadata not needed in raw markdown)
content = content.replace(/<Head>[\s\S]*?<\/Head>/g, '');
// 7. Convert Tabs/TabItem components to readable markdown (preserve content)
content = convertTabsToMarkdown(content);
// 8. Convert details/summary components to readable markdown (preserve content)
content = convertDetailsToMarkdown(content);
// 9. Remove custom React/MDX components (FAQStructuredData, etc.)
// Matches both self-closing and paired tags: <Component ... /> or <Component ...>...</Component>
// This runs AFTER Tabs/details conversion to preserve their content
content = content.replace(/<[A-Z][a-zA-Z]*[\s\S]*?(?:\/>|<\/[A-Z][a-zA-Z]*>)/g, '');
// 10. Convert relative image paths to absolute paths from docs root
// Matches:  or 
content = content.replace(
/!\[([^\]]*)\]\((\.\/)?img\/([^)]+)\)/g,
(match, alt, relPrefix, filename) => {
// Convert to absolute path using configurable docsPath
// Ensure docsPath ends with / for proper path joining
const normalizedDocsPath = docsPath.endsWith('/') ? docsPath : docsPath + '/';
return ``;
}
);
// 11. Remove any leading blank lines
content = content.replace(/^\s*\n/, '');
// 12. Prepend title from frontmatter as H1 heading
if (title) {
content = `# ${title}\n\n${content}`;
}
// 13. Collapse multiple consecutive blank lines into single blank line
content = collapseBlankLines(content);
return content;
}
// Resolve a URL href to a fully-qualified .md URL.
// Handles relative paths (./foo, ../bar), site-root-absolute paths (/docs/foo),
// fragments (#section), and already-qualified URLs (https://...).
// docsPrefix is the URL path prefix where docs are served (e.g. '/docs' or ''),
// used to map site-root-absolute links back to file-space paths.
function resolveLink(href, pageUrlDir, siteUrl, docsPrefix) {
if (!href
|| href.startsWith('http://')
|| href.startsWith('https://')
|| href.startsWith('mailto:')
|| href.startsWith('#')) {
return null;
}
const hashIdx = href.indexOf('#');
let pathPart = hashIdx >= 0 ? href.slice(0, hashIdx) : href;
const fragment = hashIdx >= 0 ? href.slice(hashIdx) : '';
if (!pathPart) return null;
if (pathPart.startsWith('/')) {
// Site-root-absolute — strip docsPrefix to map from URL space to file space
if (docsPrefix && !pathPart.startsWith(docsPrefix + '/') && pathPart !== docsPrefix) {
return null;
}
if (docsPrefix) {
pathPart = pathPart.slice(docsPrefix.length) || '/';
}
} else {
// Relative — resolve against the current file's directory
pathPart = path.posix.join(pageUrlDir, pathPart);
}
pathPart = path.posix.normalize(pathPart);
if (pathPart.endsWith('/') && pathPart.length > 1) {
pathPart = pathPart.slice(0, -1);
}
const ext = path.posix.extname(pathPart);
if (ext === '.mdx') {
pathPart = pathPart.slice(0, -4) + '.md';
} else if (!ext) {
pathPart += '.md';
}
return siteUrl + pathPart + fragment;
}
// Rewrite internal markdown links to fully-qualified .md URLs.
// Matches inline links [text](url) (but not images )
// and reference-style definitions [ref]: url.
function convertLinksToAbsoluteUrls(content, pageUrlDir, siteUrl, docsPrefix) {
// Inline links: [text](url) — negative lookbehind excludes images.
// Note: links with titles [text](url "title") or nested parentheses in URLs
// are not supported and will be left as-is or may be corrupted. These patterns
// are extremely rare in documentation markdown.
content = content.replace(
/(?<!!)\[([^\]]*)\]\(([^)]*)\)/g,
(match, text, href) => {
const resolved = resolveLink(href.trim(), pageUrlDir, siteUrl, docsPrefix);
return resolved ? `[${text}](${resolved})` : match;
}
);
// Collect labels used by image references (![alt][label]) so we skip them
const imageRefLabels = new Set();
const imageRefPattern = /!\[[^\]]*\]\[([^\]]+)\]/g;
let imgMatch;
while ((imgMatch = imageRefPattern.exec(content)) !== null) {
imageRefLabels.add(imgMatch[1].toLowerCase());
}
// Reference-style link definitions: [ref]: url (skip image labels)
content = content.replace(
/^\[([^\]]+)\]:\s+(\S+)$/gm,
(match, ref, href) => {
if (imageRefLabels.has(ref.toLowerCase())) return match;
const resolved = resolveLink(href.trim(), pageUrlDir, siteUrl, docsPrefix);
return resolved ? `[${ref}]: ${resolved}` : match;
}
);
return content;
}
// Recursively find all markdown files in a directory (both .md and .mdx)
function findMarkdownFiles(dir, fileList = [], baseDir = dir) {
const files = fs.readdirSync(dir);
files.forEach((file) => {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
findMarkdownFiles(filePath, fileList, baseDir);
} else if (file.endsWith('.md') || file.endsWith('.mdx')) {
// Store relative path from base directory
const relativePath = path.relative(baseDir, filePath);
fileList.push(relativePath);
}
});
return fileList;
}
// Copy image directories from docs to build
async function copyImageDirectories(docsDir, buildDir) {
const imageDirs = [];
// Recursively find all 'img' directories in docs
function findImgDirs(dir, baseDir = dir) {
const files = fs.readdirSync(dir);
files.forEach((file) => {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
if (file === 'img') {
// Found an img directory, store its relative path
const relativePath = path.relative(baseDir, dir);
imageDirs.push({ source: filePath, relativePath });
} else {
// Continue searching in subdirectories
findImgDirs(filePath, baseDir);
}
}
});
}
// Find all img directories
findImgDirs(docsDir);
// Copy each img directory to build
let copiedCount = 0;
for (const { source, relativePath } of imageDirs) {
const destination = path.join(buildDir, relativePath, 'img');
try {
await fs.copy(source, destination);
const imageCount = fs.readdirSync(source).length;
console.log(` ✓ Copied: ${relativePath}/img/ (${imageCount} images)`);
copiedCount++;
} catch (error) {
console.error(` ✗ Failed to copy ${relativePath}/img/:`, error.message);
}
}
return copiedCount;
}
module.exports = function markdownSourcePlugin(context, options = {}) {
// Configurable options with defaults for backwards compatibility
const docsPath = options.docsPath || '/docs/';
const docsDirName = options.docsDir || 'docs';
// Widget type: 'button' (simple copy button) or 'dropdown' (with multiple actions)
const widgetType = options.widgetType || 'button';
// CSS selector for where to inject the widget
const containerSelector = options.containerSelector || 'article .markdown header';
// Configurable button text
const copyButtonText = options.copyButtonText || 'Copy page';
const copiedButtonText = options.copiedButtonText || 'Copied';
const supportDirectoryIndex = options.supportDirectoryIndex || false;
const fullyQualifiedLinks = options.fullyQualifiedLinks || false;
const directive = options.directive || null;
return {
name: 'markdown-source-plugin',
// Provide theme components from the plugin (eliminates need for manual copying)
getThemePath() {
return path.resolve(__dirname, './theme');
},
// Expose config to client-side via globalData
async contentLoaded({ actions }) {
const { setGlobalData } = actions;
setGlobalData({ docsPath, widgetType, containerSelector, copyButtonText, copiedButtonText, supportDirectoryIndex, directive });
},
async postBuild({ outDir }) {
const docsDir = path.join(context.siteDir, docsDirName);
const buildDir = outDir;
const siteUrl = fullyQualifiedLinks
? (options.siteUrl || (context.siteConfig.url + (context.siteConfig.baseUrl || '/'))).replace(/\/$/, '')
: '';
// docsPath prefix without trailing slash, used to strip the routing
// prefix from site-root-absolute links (e.g. '/docs' from '/docs/foo')
const docsPrefix = fullyQualifiedLinks
? docsPath.replace(/\/+$/, '')
: '';
console.log('[markdown-source-plugin] Copying markdown source files...');
// Find all markdown files in docs directory
const mdFiles = findMarkdownFiles(docsDir);
let copiedCount = 0;
// Process each markdown file to build directory
for (const mdFile of mdFiles) {
const sourcePath = path.join(docsDir, mdFile);
// Convert .mdx to .md for the destination (URLs use .md extension)
let destFile = mdFile.replace(/\.mdx$/, '.md');
// When supportDirectoryIndex is off, rewrite index.md to parent path
// so trailing-slash URLs resolve correctly (e.g., /foo/ -> /foo.md)
if (!supportDirectoryIndex && path.basename(destFile) === 'index.md') {
const parentDir = path.dirname(destFile);
destFile = parentDir === '.' ? 'index.md' : parentDir + '.md';
}
const destPath = path.join(buildDir, destFile);
try {
// Ensure destination directory exists
await fs.ensureDir(path.dirname(destPath));
// Read the markdown file
const content = await fs.readFile(sourcePath, 'utf8');
// Clean markdown for raw display
let cleanedContent = cleanMarkdownForDisplay(content, mdFile, docsPath);
// Prepend the llms-txt-directive blockquote
if (directive) {
cleanedContent = directive + '\n\n' + cleanedContent;
}
// Rewrite internal links to fully-qualified .md URLs
if (fullyQualifiedLinks) {
const fileDir = path.posix.dirname(mdFile);
const pageUrlDir = fileDir === '.' ? '/' : '/' + fileDir + '/';
cleanedContent = convertLinksToAbsoluteUrls(cleanedContent, pageUrlDir, siteUrl, docsPrefix);
}
// Write the cleaned content
await fs.writeFile(destPath, cleanedContent, 'utf8');
copiedCount++;
console.log(` ✓ Processed: ${mdFile} -> ${destFile}`);
} catch (error) {
console.error(` ✗ Failed to process ${mdFile}:`, error.message);
}
}
console.log(`[markdown-source-plugin] Successfully copied ${copiedCount} markdown files`);
// Copy image directories
console.log('[markdown-source-plugin] Copying image directories...');
const imgDirCount = await copyImageDirectories(docsDir, buildDir);
console.log(`[markdown-source-plugin] Successfully copied ${imgDirCount} image directories`);
},
};
};