import fs from 'fs'; import path from 'path'; import matter from 'gray-matter'; import ts from 'typescript'; import { ApiRoute, ApiMethod } from '@/types/api'; export type WikiArticle = { slug: string; title: string; rawContent: string; updatedAt?: string; }; export type WikiPage = { title: string; path: string; } const wikiDirectory = path.join(process.cwd(), "data/wiki/pages"); export async function getWikiPageBySlug(slug: string): Promise { try { const fullPath = path.join(wikiDirectory, `${slug}.mdx`); const fileContents = fs.readFileSync(fullPath, "utf-8"); const { data, content } = matter(fileContents); return { slug, rawContent: content, title: data.title || 'Unbenannt', updatedAt: data.updatedAt || null, ...data, } as WikiArticle; } catch (error) { return null; } } /** * Liest rekursiv alle Dateien aus einem Verzeichnis aus. * @param dirPath - Der Startordner * @param extension - Optionale Dateiendung zur Filterung (z. B. ".ts" oder "ts") * @returns Array mit den Dateipfaden */ export function getAllFiles(dirPath: string, extension?: string): string[] { if (!fs.existsSync(dirPath)) return []; let results: string[] = []; // optionales führendes Dot sicherstellen (z. B. aus "ts" wird ".ts") const targetExt = extension && !extension.startsWith('.') ? `.${extension}` : extension; // withFileTypes: true spart zusätzliche fs.statSync Aufrufe const entries = fs.readdirSync(dirPath, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dirPath, entry.name); if (entry.isDirectory()) { results = results.concat(getAllFiles(fullPath, targetExt)); } else if (!targetExt || entry.name.endsWith(targetExt)) { results.push(fullPath); } } return results; } /** * Liest die Kategorie aus der Datei aus (@wikiCategory) oder ermittelt sie aus dem Ordnernamen. */ export function filterCategory( content: string, filePath: string, prefix: string = '@wikiCategory' ): string { // 1. In Kommentaren nach @wikiCategory suchen const lines = content.split('\n'); for (const line of lines) { const cleaned = line.replace(/^\/\/\s*/, '').replace(/^\/\*\*?\s*/, '').replace(/\*\/$/, '').trim(); if (cleaned.startsWith(prefix)) { let category = cleaned.slice(prefix.length).trim().replace(/^:\s*/, ''); if (category) return category; } } // 2. Fallback: Ersten Ordnernamen unter app/api/ als Kategorie nutzen const normalizedPath = filePath.replace(/\\/g, '/'); const apiMatch = normalizedPath.match(/app\/api\/([^/]+)/); if (apiMatch && apiMatch[1]) { const folderName = apiMatch[1]; // Ersten Buchstaben großschreiben (z. B. "stream" -> "Stream") return folderName.charAt(0).toUpperCase() + folderName.slice(1); } return 'Allgemein'; } /** * Parst TypeScript-Code via AST und extrahiert HTTP-Methoden sowie deren Kommentare. */ export function filterMethods( content: string, prefix: string = '@wikiDescription' ): ApiMethod[] { const sourceFile = ts.createSourceFile( 'temp.ts', content, ts.ScriptTarget.Latest, /* setParentNodes */ true ); const methods: ApiMethod[] = []; const validMethods = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']); ts.forEachChild(sourceFile, (node) => { if (ts.isFunctionDeclaration(node) && node.name) { const functionName = node.name.text; if (validMethods.has(functionName)) { let description = ''; const commentRanges = ts.getLeadingCommentRanges(content, node.pos); if (commentRanges && commentRanges.length > 0) { const lastCommentRange = commentRanges[commentRanges.length - 1]; const rawComment = content.substring( lastCommentRange.pos, lastCommentRange.end ); const cleanedComment = rawComment .replace(/^\/\/\s*/, '') .replace(/^\/\*\*?\s*/, '') .replace(/\*\/$/, '') .split('\n') .map((line) => line.replace(/^\s*\*\s?/, '').trim()) .join(' ') .trim(); if (cleanedComment.startsWith(prefix)) { let textAfterPrefix = cleanedComment.slice(prefix.length).trim(); textAfterPrefix = textAfterPrefix.replace(/^:\s*/, ''); description = textAfterPrefix; } } methods.push({ method: functionName, description: description || 'Keine Beschreibung vorhanden.', }); } } }); return methods; } /** * Liest alle API-Dateien dynamisch aus und wandelt sie in ApiRoute-Objekte um. */ export async function getAllApis(): Promise { try { const apiBasePath = path.join(process.cwd(), "app/api"); const allTsFiles = getAllFiles(apiBasePath, ".ts"); const routes: ApiRoute[] = []; allTsFiles.forEach((filePath) => { const fileContents = fs.readFileSync(filePath, "utf-8"); // 1. Methoden extrahieren const methods = filterMethods(fileContents, "@wikiDescription"); // Nur Routen hinzufügen, die auch API-Methoden exportieren if (methods.length > 0) { // 2. Kategorie ermitteln const category = filterCategory(fileContents, filePath, "@wikiCategory"); // 3. Route-Pfad automatisch aus dem Dateipfad generieren (app/api/stream/currentID/route.ts -> stream/currentID) const relativePath = path.relative(apiBasePath, filePath).replace(/\\/g, '/'); const routePath = relativePath .replace(/\/route\.ts$/, '') .replace(/\.ts$/, ''); routes.push({ route: routePath, category, methods, }); } }); return routes; } catch (error) { console.error("Fehler beim Auslesen der API-Dateien:", error); return []; } } export async function getAllWikiPages(): Promise { try { const pagesBasePath = path.join(process.cwd(), "data/wiki/pages"); const allPaths = getAllFiles(pagesBasePath, ".mdx"); const allPages: WikiPage[] = []; for (const filePath of allPaths) { // extract filename of the path (e. g. "test" at "data/wiki/pages/test.mdx") const slug = path.parse(filePath).name; const wikiPage = await getWikiPageBySlug(slug); if (wikiPage) { allPages.push({ path: slug, title: wikiPage.title, }); } } console.log(allPages); return allPages; } catch (error) { console.error("Fehler beim Auslesen der Wiki-Seiten:", error); return []; } }