import { createMintIgnoreMatcher, isMintIgnoredBy, processMintIgnoreString, type MintIgnoreMatcher, } from '@mintlify/common'; import { getMintIgnore } from '@mintlify/prebuild'; import { addLog, ErrorLog, SuccessLog } from '@mintlify/previewing'; import fs from 'node:fs/promises'; import path from 'node:path'; import { CMD_EXEC_PATH, terminate } from './helpers.js'; async function getGitIgnore(): Promise { try { const content = await fs.readFile(path.join(CMD_EXEC_PATH, '.gitignore'), 'utf-8'); return processMintIgnoreString(content); } catch { return []; } } async function* walk(dir: string, matcher: MintIgnoreMatcher): AsyncGenerator { const entries = await fs.readdir(dir, { withFileTypes: true }); for (const entry of entries) { const full = path.join(dir, entry.name); const relative = path.relative(CMD_EXEC_PATH, full).split(path.sep).join('/'); if (isMintIgnoredBy(relative, matcher, entry.isDirectory())) continue; if (entry.isDirectory()) { yield* walk(full, matcher); } else if (entry.name.endsWith('.mdx')) { yield full; } } } export const formatHandler = async (): Promise => { const { mdxToPm, pmToMdx, canonicalPmToMdxOptions } = await import('./vendor/converter.js'); const ignores = [...(await getGitIgnore()), ...(await getMintIgnore(CMD_EXEC_PATH))]; const matcher = createMintIgnoreMatcher(ignores); let total = 0; let changed = 0; let failed = 0; for await (const file of walk(CMD_EXEC_PATH, matcher)) { total++; const relative = path.relative(CMD_EXEC_PATH, file); try { const raw = await fs.readFile(file, 'utf-8'); let formatted = raw; let originalFrontmatterKeys = 0; for (let pass = 0; pass < 3; pass++) { const { doc, frontmatter } = mdxToPm(formatted); if (pass === 0) originalFrontmatterKeys = Object.keys(frontmatter).length; const next = `${pmToMdx(doc, { frontmatter, ...canonicalPmToMdxOptions })}\n`; if (next === formatted) break; formatted = next; } if (originalFrontmatterKeys > 0 && !formatted.startsWith('---')) { throw new Error('formatting would remove frontmatter; file left untouched'); } if (formatted !== raw) { await fs.writeFile(file, formatted); changed++; } } catch (error) { failed++; addLog( ); } } addLog( 0 ? ` (${failed} failed)` : ''}`} /> ); await terminate(failed > 0 ? 1 : 0); };