route-generator.ts 14 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
/* eslint-disable unicorn/prefer-string-replace-all -- 此文件大量使用正则表达式,replaceAll 不支持正则 */
import type { RouteRecordRaw } from "vue-router";

import { existsSync, readdirSync, statSync } from "node:fs";
import { basename, dirname, extname, join, relative } from "node:path";

export interface RouteConfig {
	// 子路由配置
	children?: RouteConfig[];
	// 是否隐藏路由(不生成)
	hidden?: boolean;
	// 是否在菜单中隐藏
	hideInMenu?: boolean;
	// 路由元数据
	meta?: Record<string, any>;
	// 路由名称(如果不提供,将根据文件路径自动生成)
	name?: string;
	// 路由路径(如果不提供,将根据文件路径自动生成)
	path?: string;
	// 路由标题(用于 meta.title)
	title?: string;
}

export interface RouteGeneratorOptions {
	// 路由配置文件路径(可选,用于覆盖默认规则)
	configFile?: string;
	// 自定义路由生成规则
	customRules?: (filePath: string, routeConfig: RouteConfig) => null | RouteConfig;
	// 排除的文件或目录
	exclude?: (RegExp | string)[];
	// 404 组件路径(可选,默认为 "@/views/NotFound.vue")
	notFoundComponent?: string;
	// 路由前缀(所有路由都会加上这个前缀)
	routePrefix?: string;
	// views 目录路径
	viewsDir: string;
}

/**
 * 将文件路径转换为路由路径
 * @example
 * 'views/User.vue' -> '/user'
 * 'views/ManageKonw/index.vue' -> '/managekonw'
 * 'views/Assistant/addUpdate.vue' -> '/assistant/add'
 */
function pathToRoutePath(filePath: string, viewsDir: string): string {
	// 获取相对于 views 目录的路径
	const relativePath = relative(viewsDir, filePath);
	// 移除文件扩展名
	const pathWithoutExt = relativePath.replace(/\.(?:vue|tsx|jsx)$/, "");

	// 处理 index.vue 文件
	let routePath = pathWithoutExt.replace(/\/index$|\\/g, (match) => match === "\\" ? "/" : "");

	// 转换为 kebab-case
	routePath = routePath
		.split("/")
		.map((segment: string) => {
			// 将 PascalCase 或 camelCase 转换为 kebab-case
			return segment
				.replace(/([A-Z])/g, "-$1")
				.toLowerCase()
				.replace(/^-/, "");
		})
		.join("/");

	// 确保以 / 开头
	if (!routePath.startsWith("/")) {
		routePath = `/${routePath}`;
	}

	// 处理空路径(根路径)
	if (routePath === "/") {
		return "/";
	}

	return routePath;
}

/**
 * 将文件路径转换为路由名称
 * @example
 * 'views/User.vue' -> 'User'
 * 'views/ManageKonw/index.vue' -> 'ManageKonw'
 * 'views/Assistant/addUpdate.vue' -> 'AssistantAdd'
 */
function pathToRouteName(filePath: string, viewsDir: string): string {
	const relativePath = relative(viewsDir, filePath);
	const pathWithoutExt = relativePath.replace(/\.(?:vue|tsx|jsx)$/, "");

	// 移除 index
	let name = pathWithoutExt.replace(/\/index$/, "").replace(/\\/g, "/");

	// 转换为 PascalCase
	name = name
		.split("/")
		.map((segment: string) => {
			// 将 kebab-case 或 camelCase 转换为 PascalCase
			return segment
				.split("-")
				.map((word: string) => word.charAt(0).toUpperCase() + word.slice(1))
				.join("");
		})
		.join("");

	return name || "Home";
}

/**
 * 从文件路径提取标题
 * @example
 * 'views/User.vue' -> '用户管理'
 * 'views/ManageKonw/index.vue' -> '知识管理'
 */
function extractTitle(filePath: string, _viewsDir: string): string {
	const fileName = basename(filePath, extname(filePath));
	const dirName = basename(dirname(filePath));

	// 如果是 index.vue,使用目录名
	if (fileName === "index") {
		return dirName
			.replace(/([A-Z])/g, " $1")
			.trim()
			.split(" ")
			.map((word: string) => word.charAt(0).toUpperCase() + word.slice(1))
			.join("");
	}

	// 否则使用文件名
	return fileName
		.replace(/([A-Z])/g, " $1")
		.trim()
		.split(" ")
		.map((word: string) => word.charAt(0).toUpperCase() + word.slice(1))
		.join("");
}

/**
 * 根据路由路径生成权限码 (authority)
 * @example
 * '/user' -> 'user'
 * '/assistant/add' -> 'assistant:add'
 * '/manage-konw/index' -> 'manage-konw'
 */
function generateAuthority(routePath: string): string {
	// 移除开头的 / 和结尾的 /index
	let authority = routePath.replace(/^\//, "").replace(/\/index$/, "");

	// 如果路径为空,返回 'home'
	if (!authority) {
		return "home";
	}

	// 将路径中的 / 替换为 :
	authority = authority.replace(/\//g, ":");

	// 转换为小写
	return authority.toLowerCase();
}

/**
 * 判断文件是否为 index 文件
 */
function isIndexFile(filePath: string): boolean {
	const fileName = basename(filePath, extname(filePath));
	return fileName === "index";
}

/**
 * 获取文件所在目录
 */
function getFileDirectory(filePath: string, _viewsDir: string): string {
	const relativePath = relative(_viewsDir, filePath);
	return dirname(relativePath);
}

/**
 * 生成路由 ID
 * 规则:
 * - 一级目录(index 文件):id = 文件夹名小写
 * - 子菜单(非 index 文件):id = 文件夹名-子菜单文件名(都转换为小写 kebab-case)
 * @example
 * 'views/Assistant/index.vue' -> 'assistant'
 * 'views/Assistant/addUpdate.vue' -> 'assistant-add-update'
 */
function generateRouteId(filePath: string, viewsDir: string, isIndex: boolean): string {
	const relativePath = relative(viewsDir, filePath);
	const dir = dirname(relativePath);
	const fileName = basename(filePath, extname(filePath));

	// 获取目录名(最后一个目录)
	const dirParts = dir.split(/[/\\]/).filter(Boolean);
	const dirName = dirParts[dirParts.length - 1] || "";

	// 将目录名转换为小写 kebab-case
	const dirId = dirName
		.replace(/([A-Z])/g, "-$1")
		.toLowerCase()
		.replace(/^-/, "");

	if (isIndex) {
		// index 文件:只返回目录名
		return dirId || "home";
	}

	// 非 index 文件:目录名-文件名
	const fileId = fileName
		.replace(/([A-Z])/g, "-$1")
		.toLowerCase()
		.replace(/^-/, "");

	return `${dirId}-${fileId}`;
}

/**
 * 检查文件是否应该被排除
 */
function shouldExclude(filePath: string, exclude: (RegExp | string)[] = []): boolean {
	const relativePath = filePath.replace(/\\/g, "/");

	for (const pattern of exclude) {
		if (typeof pattern === "string") {
			if (relativePath.includes(pattern)) {
				return true;
			}
		} else if (pattern instanceof RegExp && pattern.test(relativePath)) {
			return true;
		}
	}

	return false;
}

/**
 * 扫描 views 目录并生成路由配置
 */
export function generateRoutes(options: RouteGeneratorOptions): RouteRecordRaw[] {
	const {
		viewsDir,
		routePrefix = "",
		exclude = [ "components", "components/", "NotFound.vue" ],
		notFoundComponent = "@/views/NotFound.vue",
		customRules,
	} = options;

	if (!existsSync(viewsDir)) {
		console.warn(`[route-generator] Views directory not found: ${viewsDir}`);
		return [];
	}

	const routes: RouteRecordRaw[] = [];

	// 用于存储目录下的文件,以便后续组织成嵌套路由
	interface FileInfo {
		directory: string;
		fullPath: string;
		isIndex: boolean;
		routeConfig: RouteConfig;
		routeName: string;
		routePath: string;
		title: string;
	}

	/**
	 * 递归扫描目录,收集所有文件信息
	 */
	function collectFiles(dir: string, parentPath: string = ""): FileInfo[] {
		const items = readdirSync(dir);
		const files: FileInfo[] = [];

		for (const item of items) {
			const fullPath = join(dir, item);
			const stat = statSync(fullPath);

			// 跳过排除的文件/目录
			if (shouldExclude(fullPath, exclude)) {
				continue;
			}

			if (stat.isDirectory()) {
				// 递归处理子目录
				const childFiles = collectFiles(fullPath, join(parentPath, item));
				files.push(...childFiles);
			} else if (stat.isFile() && /\.(?:vue|[jt]sx)$/.test(item)) {
				// 处理 Vue/React 文件
				const routePath = pathToRoutePath(fullPath, viewsDir);
				const routeName = pathToRouteName(fullPath, viewsDir);
				const title = extractTitle(fullPath, viewsDir);
				const isIndex = isIndexFile(fullPath);
				const directory = getFileDirectory(fullPath, viewsDir);

				// 构建基础路由配置
				let routeConfig: RouteConfig = {
					path: routePath,
					name: routeName,
					title,
					meta: {
						title,
					},
				};

				// 应用自定义规则
				if (customRules) {
					const customResult = customRules(fullPath, routeConfig);
					if (customResult === null) {
						// 返回 null 表示跳过此路由
						continue;
					}
					routeConfig = customResult;
				}

				// 跳过隐藏的路由
				if (routeConfig.hidden === true) {
					continue;
				}

				files.push({
					fullPath,
					routePath: routeConfig.path || routePath,
					routeName: routeConfig.name || routeName,
					title: routeConfig.title || title,
					isIndex,
					directory,
					routeConfig,
				});
			}
		}

		return files;
	}

	// 收集所有文件
	const allFiles = collectFiles(viewsDir);

	// 按目录分组,组织成嵌套路由结构
	const directoryMap = new Map<string, FileInfo[]>();

	for (const file of allFiles) {
		const dir = file.directory.replace(/\\/g, "/");
		if (!directoryMap.has(dir)) {
			directoryMap.set(dir, []);
		}
		const dirFiles = directoryMap.get(dir);
		if (dirFiles) {
			dirFiles.push(file);
		}
	}

	// 用于标记已处理过的文件
	const processedFiles = new Set<FileInfo>();

	// 首先生成所有 index 文件作为父路由
	for (const file of allFiles) {
		if (file.isIndex && !processedFiles.has(file)) {
			const dir = file.directory.replace(/\\/g, "/");
			const dirFiles = directoryMap.get(dir) || [];

			// 查找同目录下的非 index 文件作为子路由
			const nonIndexFiles = dirFiles.filter(f => !f.isIndex);
			const children: RouteRecordRaw[] = [];

			for (const childFile of nonIndexFiles) {
				// 计算子路由路径(相对于父路由)
				// 例如:父路由 /assistant,子文件 addUpdate.vue -> 子路由路径为 add-update
				const childFileName = basename(childFile.fullPath, extname(childFile.fullPath));
				const childRoutePath = childFileName
					.replace(/([A-Z])/g, "-$1")
					.toLowerCase()
					.replace(/^-/, "");

				const childAuthority = generateAuthority(childFile.routePath);
				const childId = generateRouteId(childFile.fullPath, viewsDir, false);

				// 计算组件导入路径
				const childRelativeToViews = relative(viewsDir, childFile.fullPath).replace("\\", "/");
				const childComponentPath = `@/views/${childRelativeToViews}`;

				const childRoute: RouteRecordRaw = {
					path: childRoutePath,
					component: () => import(/* @vite-ignore */ childComponentPath),
					id: childId,
					title: childFile.title,
					icon: childFile.routeConfig.meta?.icon || "",
					level: 2, // 非 index 文件默认为 2
					hidden: childFile.routeConfig.hidden ?? false,
					meta: {
						authority: childFile.routeConfig.meta?.authority || childAuthority,
						keepAlive: childFile.routeConfig.meta?.keepAlive ?? false,
						order: childFile.routeConfig.meta?.order ?? 1, // 非 index 文件默认为 1
						requiresAuth: childFile.routeConfig.meta?.requiresAuth ?? false,
						...childFile.routeConfig.meta,
					},
				} as RouteRecordRaw;

				children.push(childRoute);
				processedFiles.add(childFile);
			}

			// 计算组件导入路径
			const relativeToViews = relative(viewsDir, file.fullPath).replace("\\", "/");
			const componentPath = `@/views/${relativeToViews}`;
			const authority = generateAuthority(file.routePath);
			const routeId = generateRouteId(file.fullPath, viewsDir, true);

			// 构建父路由
			const route: RouteRecordRaw = {
				path: routePrefix + file.routePath,
				component: () => import(/* @vite-ignore */ componentPath),
				id: routeId,
				title: file.title,
				icon: file.routeConfig.meta?.icon || "",
				level: 1, // index 文件默认为 1
				hidden: file.routeConfig.hidden ?? false,
				meta: {
					authority: file.routeConfig.meta?.authority || authority,
					keepAlive: file.routeConfig.meta?.keepAlive ?? false,
					order: file.routeConfig.meta?.order,
					requiresAuth: file.routeConfig.meta?.requiresAuth ?? false,
					...file.routeConfig.meta,
				},
			} as RouteRecordRaw;

			// 如果有子路由,添加 children
			if (children.length > 0) {
				route.children = children;
			}

			routes.push(route);
			processedFiles.add(file);
		}
	}

	// 处理没有 index 父路由的非 index 文件(根目录下的独立文件)
	for (const file of allFiles) {
		if (!processedFiles.has(file)) {
			const relativeToViews = relative(viewsDir, file.fullPath).replace("\\", "/");
			const componentPath = `@/views/${relativeToViews}`;
			const authority = generateAuthority(file.routePath);
			// 对于根目录下的独立文件,目录名为空,使用文件名作为 id
			const routeId = generateRouteId(file.fullPath, viewsDir, false);

			const route: RouteRecordRaw = {
				path: routePrefix + file.routePath,
				component: () => import(/* @vite-ignore */ componentPath),
				id: routeId,
				title: file.title,
				icon: file.routeConfig.meta?.icon || "",
				level: 2, // 非 index 文件默认为 2
				hidden: file.routeConfig.hidden ?? false,
				meta: {
					authority: file.routeConfig.meta?.authority || authority,
					keepAlive: file.routeConfig.meta?.keepAlive ?? false,
					order: file.routeConfig.meta?.order ?? 1, // 非 index 文件默认为 1
					requiresAuth: file.routeConfig.meta?.requiresAuth ?? false,
					...file.routeConfig.meta,
				},
			} as RouteRecordRaw;

			routes.push(route);
			processedFiles.add(file);
		}
	}

	// 添加 404 路由
	routes.push({
		path: "/:pathMatch(.*)*",
		// @ts-ignore - 动态导入路径,TypeScript 无法在编译时验证路径别名
		component: () => import(/* @vite-ignore */ notFoundComponent),
		meta: {
			title: "404",
			hidden: true,
		},
	} as RouteRecordRaw);

	return routes;
}

/**
 * 从配置文件加载路由规则
 */
export function loadRouteConfig(configPath: string): RouteConfig[] {
	if (!existsSync(configPath)) {
		return [];
	}

	try {
		// 动态导入配置文件
		// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, unicorn/prefer-module
		const config = require(configPath);
		return config.default || config;
	} catch (error) {
		console.warn(`[route-generator] Failed to load route config: ${configPath}`, error);
		return [];
	}
}