import { existsSync, readFileSync } from "node:fs"; import { resolve } from "node:path"; import ts from "typescript"; import type { Plugin } from "vite"; import { UTIL_LIST } from "../utils"; import { createEmptyUtilApi, type UtilApi, type UtilApiMap, type UtilMemberRow, type UtilTypeRow } from "../utils-types"; /** 虚拟模块的引用标识,业务代码与类型声明共用。 */ export const UTILS_MODULE_ID = "virtual:timi-utils"; /** Vite 内部使用的解析后标识,前置 `\0` 避免被其他插件处理。 */ const RESOLVED_ID = `\0${UTILS_MODULE_ID}`; /** 签名过长时截断的阈值。 */ const SIGNATURE_LIMIT = 90; /** 取 JSDoc 原文,保留换行;剔除代码块,避免把用法示例混进说明。 */ function getRawDoc(node: ts.Node): string { const parts: string[] = []; for (const doc of ts.getJSDocCommentsAndTags(node)) { if (ts.isJSDoc(doc) && doc.comment) { parts.push(String(doc.comment)); } } return parts.join("\n").replace(/```[\s\S]*?```/g, " "); } /** 压平单段内的空白,去掉 markdown 标记。 */ function flattenParagraph(text: string): string { return text.replace(/`/g, "").replace(/^#+\s*/, "").replace(/\s+/g, " ").trim(); } /** * 成员说明:按段保留换行。 * * 不把多段压成一行,否则「摘要 + 补充说明」会连成读不通的长句; * 交给渲染侧用 `white-space: pre-line` 呈现。 */ function getDocComment(node: ts.Node): string { return getRawDoc(node) .split(/\n\s*\n/) .map(flattenParagraph) .filter(Boolean) .join("\n"); } /** * 模块说明:只取第一段正文。 * * 类注释常带 markdown 标题与用法代码块,取第一段可避免把代码塞进描述。 */ function getModuleComment(node: ts.Node): string { const firstParagraph = getRawDoc(node).split(/\n\s*\n/)[0] ?? ""; return flattenParagraph(firstParagraph); } /** 判断顶层声明是否被导出。 */ function isExported(node: ts.Node): boolean { if (!ts.canHaveModifiers(node)) { return false; } const modifiers = ts.getModifiers(node); return modifiers?.some(item => item.kind === ts.SyntaxKind.ExportKeyword) ?? false; } /** 判断是否显式声明为 private / protected。 */ function isHiddenMember(node: ts.Node): boolean { if (!ts.canHaveModifiers(node)) { return false; } const modifiers = ts.getModifiers(node); return modifiers?.some(item => item.kind === ts.SyntaxKind.PrivateKeyword || item.kind === ts.SyntaxKind.ProtectedKeyword ) ?? false; } /** 判断成员是否为静态成员。 */ function isStaticMember(node: ts.Node): boolean { if (!ts.canHaveModifiers(node)) { return false; } const modifiers = ts.getModifiers(node); return modifiers?.some(item => item.kind === ts.SyntaxKind.StaticKeyword) ?? false; } /** 截断过长的签名。 */ function clampSignature(text: string): string { const flat = text.replace(/\s+/g, " ").trim(); return flat.length > SIGNATURE_LIMIT ? `${flat.slice(0, SIGNATURE_LIMIT)}…` : flat; } /** 按源码中的类型标注还原单个参数。 */ function printParameter(param: ts.ParameterDeclaration, sourceFile: ts.SourceFile): string { const rest = param.dotDotDotToken ? "..." : ""; const name = param.name.getText(sourceFile); const optional = param.questionToken ? "?" : ""; const type = param.type ? `: ${param.type.getText(sourceFile)}` : ""; const initializer = param.initializer?.getText(sourceFile) ?? ""; // 默认值只在简短时保留,避免把大段字面量塞进签名 const fallback = initializer && initializer.length <= 20 ? ` = ${initializer}` : ""; return `${rest}${name}${optional}${type}${fallback}`; } /** 还原函数或方法的签名。 */ function printFunctionLike( name: string, node: ts.SignatureDeclaration, sourceFile: ts.SourceFile ): string { const typeParameters = node.typeParameters?.length ? `<${node.typeParameters.map(item => item.getText(sourceFile)).join(", ")}>` : ""; const parameters = node.parameters .map(item => printParameter(item, sourceFile)) .join(", "); const returns = node.type ? `: ${node.type.getText(sourceFile)}` : ""; return `${name}${typeParameters}(${parameters})${returns}`; } /** 还原类属性或顶层常量的签名。 */ function printProperty(node: ts.PropertyDeclaration, sourceFile: ts.SourceFile): string { if (node.type) { return node.type.getText(sourceFile); } const initializer = node.initializer; if (initializer && ts.isArrowFunction(initializer)) { return printFunctionLike("", initializer, sourceFile); } if (initializer) { return initializer.getText(sourceFile); } return "-"; } /** 收集类成员。 */ function collectClassMembers( node: ts.ClassDeclaration, sourceFile: ts.SourceFile ): UtilMemberRow[] { const rows: UtilMemberRow[] = []; for (const member of node.members) { if (isHiddenMember(member)) { continue; } const prefix = isStaticMember(member) ? "static " : ""; if (ts.isMethodDeclaration(member)) { const name = member.name.getText(sourceFile); rows.push({ name, signature: clampSignature(prefix + printFunctionLike(name, member, sourceFile)), description: getDocComment(member) }); continue; } if (ts.isPropertyDeclaration(member)) { const name = member.name.getText(sourceFile); rows.push({ name, signature: clampSignature(prefix + printProperty(member, sourceFile)), description: getDocComment(member) }); } } return rows; } /** 收集导出的类型定义。 */ function collectType( node: ts.TypeAliasDeclaration | ts.InterfaceDeclaration | ts.EnumDeclaration, sourceFile: ts.SourceFile ): UtilTypeRow { const kind = ts.isTypeAliasDeclaration(node) ? "类型别名" : ts.isInterfaceDeclaration(node) ? "接口" : "枚举"; return { name: node.name.getText(sourceFile), kind, text: node.getText(sourceFile), description: getModuleComment(node) }; } /** 解析单个工具模块源码。 */ function parseUtil(name: string, filePath: string): UtilApi { const source = readFileSync(filePath, "utf-8"); const sourceFile = ts.createSourceFile( filePath, source, ts.ScriptTarget.ESNext, true, ts.ScriptKind.TS ); // `export default VDraggable;` 这类写法下,声明本身没有 export 修饰符, // 先记录默认导出的标识符,第二轮再一并纳入。 let defaultExportName: string | null = null; for (const statement of sourceFile.statements) { if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) { defaultExportName = statement.expression.getText(sourceFile); } } const api: UtilApi = { name, description: "", parsed: true, members: [], types: [] }; for (const statement of sourceFile.statements) { if (ts.isClassDeclaration(statement) && statement.name) { const declaredName = statement.name.getText(sourceFile); if (!isExported(statement) && declaredName !== defaultExportName) { continue; } api.description = getModuleComment(statement); api.members.push(...collectClassMembers(statement, sourceFile)); continue; } if (ts.isFunctionDeclaration(statement) && statement.name) { if (!isExported(statement)) { continue; } const functionName = statement.name.getText(sourceFile); api.members.push({ name: functionName, signature: clampSignature(printFunctionLike(functionName, statement, sourceFile)), description: getDocComment(statement) }); continue; } if (ts.isVariableStatement(statement)) { for (const declaration of statement.declarationList.declarations) { if (!ts.isIdentifier(declaration.name)) { continue; } const declaredName = declaration.name.getText(sourceFile); if (!isExported(statement) && declaredName !== defaultExportName) { continue; } api.members.push({ name: declaredName, signature: clampSignature(printProperty(declaration, sourceFile)), description: getDocComment(statement) || getDocComment(declaration) }); } continue; } if ( (ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement) || ts.isEnumDeclaration(statement)) && isExported(statement) ) { api.types.push(collectType(statement, sourceFile)); } } // 类没有写注释时保持为空,让文档页使用元数据里的描述; // 退而取某个成员的说明会造成「模块说明=某个方法的说明」这种误导。 return api; } /** 逐个解析工具模块,单个失败只降级为空数据。 */ function parseAll(repoRoot: string): UtilApiMap { const result: UtilApiMap = {}; for (const meta of UTIL_LIST) { const filePath = resolve(repoRoot, meta.entry); if (!existsSync(filePath)) { console.warn(`[timi-tsdocgen] 未找到模块:${meta.entry}`); result[meta.name] = createEmptyUtilApi(meta.name); continue; } try { result[meta.name] = parseUtil(meta.name, filePath); } catch (error) { console.warn(`[timi-tsdocgen] 解析 ${meta.name} 失败,已降级:`, error); result[meta.name] = createEmptyUtilApi(meta.name); } } return result; } /** * 提供 `virtual:timi-utils` 虚拟模块,内容为全部工具模块的 API 数据。 * * `vue-docgen-api` 只能解析 SFC,工具模块是 TS 文件,因此这里改用 * TypeScript 自带的解析器读 AST:签名直接从源码的类型标注还原, * 不建 TypeChecker,既不依赖各模块的外部类型能否解析,也快得多。 * * @param repoRoot 仓库根目录的绝对路径 */ export function tsdocgenPlugin(repoRoot: string): Plugin { const entryPathSet = new Set(UTIL_LIST.map(meta => resolve(repoRoot, meta.entry))); let cache: UtilApiMap | null = null; return { name: "timi-tsdocgen", resolveId(id: string) { return id === UTILS_MODULE_ID ? RESOLVED_ID : null; }, load(id: string) { if (id !== RESOLVED_ID) { return null; } if (cache === null) { cache = parseAll(repoRoot); } return `export default ${JSON.stringify(cache)};`; }, handleHotUpdate({ file, server }) { if (!entryPathSet.has(file)) { return; } cache = null; const invalidated = server.moduleGraph.getModuleById(RESOLVED_ID); if (invalidated) { server.moduleGraph.invalidateModule(invalidated); server.ws.send({ type: "full-reload" }); } } }; }