71 lines
2 KiB
TypeScript
71 lines
2 KiB
TypeScript
|
|
/**
|
||
|
|
* Convertir Markdown a HTML
|
||
|
|
* Usa remark/rehype para procesar Markdown
|
||
|
|
*/
|
||
|
|
|
||
|
|
import { readFile, writeFile } from 'fs/promises';
|
||
|
|
import { join } from 'path';
|
||
|
|
import { remark } from 'remark';
|
||
|
|
import remarkGfm from 'remark-gfm';
|
||
|
|
import remarkRehype from 'remark-rehype';
|
||
|
|
import rehypeStringify from 'rehype-stringify';
|
||
|
|
import rehypeHighlight from 'rehype-highlight';
|
||
|
|
import rehypeRaw from 'rehype-raw';
|
||
|
|
import rehypeSanitize from 'rehype-sanitize';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Convertir un archivo Markdown a HTML
|
||
|
|
*/
|
||
|
|
export async function convertMarkdownToHtml(
|
||
|
|
markdownPath: string,
|
||
|
|
outputPath?: string
|
||
|
|
): Promise<string> {
|
||
|
|
try {
|
||
|
|
// Leer archivo Markdown
|
||
|
|
const markdown = await readFile(markdownPath, 'utf-8');
|
||
|
|
|
||
|
|
// Procesar Markdown → HTML
|
||
|
|
const result = await remark()
|
||
|
|
.use(remarkGfm) // GitHub Flavored Markdown
|
||
|
|
.use(remarkRehype, { allowDangerousHtml: true }) // Convertir a HTML
|
||
|
|
.use(rehypeRaw) // Permitir HTML crudo
|
||
|
|
.use(rehypeSanitize) // Sanitizar HTML
|
||
|
|
.use(rehypeHighlight) // Resaltado de código
|
||
|
|
.use(rehypeStringify) // Convertir a string
|
||
|
|
.process(markdown);
|
||
|
|
|
||
|
|
const html = result.toString();
|
||
|
|
|
||
|
|
// Guardar si se especifica outputPath
|
||
|
|
if (outputPath) {
|
||
|
|
await writeFile(outputPath, html, 'utf-8');
|
||
|
|
}
|
||
|
|
|
||
|
|
return html;
|
||
|
|
} catch (error) {
|
||
|
|
console.error(`Error convirtiendo ${markdownPath}:`, error);
|
||
|
|
throw error;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Convertir múltiples archivos Markdown
|
||
|
|
*/
|
||
|
|
export async function convertMultipleMarkdown(
|
||
|
|
markdownPaths: string[],
|
||
|
|
outputDir: string
|
||
|
|
): Promise<string[]> {
|
||
|
|
const htmlFiles: string[] = [];
|
||
|
|
|
||
|
|
for (const markdownPath of markdownPaths) {
|
||
|
|
const fileName = markdownPath.split('/').pop()?.replace('.md', '.html') || 'section.html';
|
||
|
|
const outputPath = join(outputDir, fileName);
|
||
|
|
|
||
|
|
await convertMarkdownToHtml(markdownPath, outputPath);
|
||
|
|
htmlFiles.push(outputPath);
|
||
|
|
}
|
||
|
|
|
||
|
|
return htmlFiles;
|
||
|
|
}
|
||
|
|
|