/** * 静态路由表一致性校验(`npm run check:pages`) * * 校验三件事: * 1. `PAGE_REGISTRY[].path` 必须真实存在于 `src/pages.json`(含 subPackages) * 2. `PAGE_REGISTRY[].key` 不能重复 * 3. `pages.json` 里已注册但没有登记进 `PAGE_REGISTRY` 的页面 → 告警(不阻断) * 4. 需要登录抽屉的页面是否挂了 `` → 告警(不阻断,见文末) * * 为什么需要:小程序页面必须在 `pages.json` **编译期**注册, * 一旦静态路由表与 `pages.json` 漂移,用户点入口就会跳转失败(且只在真机上才暴露)。 * * 注意:本脚本用正则从 `src/router/pages.ts` 提取条目(Node 无法直接 import .ts), * 因此 `PAGE_REGISTRY` 的条目请保持「一个字面量对象 + 单引号」的写法, * 注释掉的示例条目(整行 `//` 开头)会被自动忽略。 */ import { readFileSync, readdirSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { join } from 'node:path' const ROOT = fileURLToPath(new URL('..', import.meta.url)) const SRC_DIR = join(ROOT, 'src') const PAGES_JSON = join(ROOT, 'src/pages.json') const REGISTRY_TS = join(ROOT, 'src/router/pages.ts') /** * 去掉 JSON 里的 `//` 与块注释 * 按字符状态机处理(尊重字符串字面量),避免把 `"http://..."` 里的 `//` 当注释切掉 */ function stripJsonComments(text) { let out = '' let inString = false let inLine = false let inBlock = false for (let i = 0; i < text.length; i++) { const c = text[i] const next = text[i + 1] if (inLine) { if (c === '\n') { inLine = false out += c } continue } if (inBlock) { if (c === '*' && next === '/') { inBlock = false i++ } continue } if (inString) { out += c if (c === '\\') { out += next ?? '' i++ } else if (c === '"') { inString = false } continue } if (c === '"') { inString = true out += c } else if (c === '/' && next === '/') { inLine = true i++ } else if (c === '/' && next === '*') { inBlock = true i++ } else { out += c } } return out } /** 收集 pages.json 中所有已注册的页面物理路径 */ function collectRegisteredPaths(pagesJson) { const registered = new Set() for (const page of pagesJson.pages ?? []) { if (page?.path) registered.add(page.path) } // 分包字段官方写法是 subPackages(写成 subpackages 无效,这里只为兼容提示) const subPackages = pagesJson.subPackages ?? pagesJson.subpackages ?? [] for (const sub of subPackages) { const root = String(sub?.root ?? '').replace(/\/$/, '') for (const page of sub?.pages ?? []) { if (page?.path) registered.add(`${root}/${page.path}`) } } return registered } /** 从 src/router/pages.ts 里提取 PAGE_REGISTRY 的字面量条目 */ function collectRegistryEntries(source) { // 整行注释(含被注释掉的示例条目)先剔除,否则会被当成真条目 const code = source .split(/\r?\n/) .filter((line) => !/^\s*(\/\/|\*|\/\*)/.test(line)) .join('\n') const start = code.indexOf('PAGE_REGISTRY') if (start === -1) return null const open = code.indexOf('[', start) if (open === -1) return null // 数组以「行首的 ]」结束 const close = code.indexOf('\n]', open) const block = close === -1 ? code.slice(open) : code.slice(open, close) const entries = [] for (const match of block.matchAll(/\{([^{}]*)\}/g)) { const body = match[1] const key = /key:\s*'([^']+)'/.exec(body)?.[1] const path = /path:\s*'([^']+)'/.exec(body)?.[1] if (key && path) entries.push({ key, path }) } return entries } const errors = [] const warnings = [] // ── 读取 pages.json ── let pagesJson try { pagesJson = JSON.parse(stripJsonComments(readFileSync(PAGES_JSON, 'utf8'))) } catch (err) { console.error(`✖ 解析 src/pages.json 失败:${err.message}`) process.exit(1) } const registered = collectRegisteredPaths(pagesJson) // ── 读取 PAGE_REGISTRY ── let source try { source = readFileSync(REGISTRY_TS, 'utf8') } catch (err) { console.error(`✖ 读取 src/router/pages.ts 失败:${err.message}`) process.exit(1) } const entries = collectRegistryEntries(source) if (!entries || entries.length === 0) { console.error( '✖ 未能从 src/router/pages.ts 解析出任何 PAGE_REGISTRY 条目。\n' + ' 请确认条目仍是「字面量对象 + 单引号」写法(key: \'...\' / path: \'...\')。' ) process.exit(1) } // ── 校验 1:path 必须已在 pages.json 注册 ── for (const entry of entries) { if (!registered.has(entry.path)) { errors.push( `PAGE_REGISTRY 的 "${entry.key}" 指向 "${entry.path}",但 src/pages.json 中未注册该页面` ) } } // ── 校验 2:key 不能重复 ── const seen = new Map() for (const entry of entries) { if (seen.has(entry.key)) { errors.push(`PAGE_REGISTRY 中存在重复的 key:"${entry.key}"`) } seen.set(entry.key, entry) } // ── 校验 3:pages.json 有、但没登记进 PAGE_REGISTRY(仅告警) ── const registeredPaths = new Set(entries.map((entry) => entry.path)) for (const path of registered) { if (!registeredPaths.has(path)) { warnings.push(`src/pages.json 已注册 "${path}",但 PAGE_REGISTRY 未登记(无法被菜单映射/按 auth 渲染)`) } } // ── 校验 4:需要登录抽屉的页面必须挂载 (仅告警) ── /** * 为什么查这个:`usePageAuth.goLogin()` 是「**就地弹抽屉**」而不是跳页 —— * 它只把 store 的 `authView` 置上,真正渲染抽屉的是页面自己的 ``。 * 漏挂的症状极具迷惑性:点「去登录」毫无反应,切到别的页面反而弹出登录框。 * (2026-09-23 实测踩过:新增的 `pages/mine/user-info.vue` 漏挂) */ function collectVueFiles(dir, acc = []) { for (const entry of readdirSync(dir, { withFileTypes: true })) { const full = join(dir, entry.name) if (entry.isDirectory()) collectVueFiles(full, acc) else if (entry.isFile() && entry.name.endsWith('.vue')) acc.push(full) } return acc } /** 需要抽屉:调了就地弹抽屉的方法,或使用了包装器 ``(其内部会调 goLogin) */ const NEEDS_DRAWER_RE = /\bgoLogin\b|\brequireLogin\s*\(|\bshowAuthModal\s*\(|]/ /** 已挂载抽屉 */ const HAS_DRAWER_RE = /]/ for (const file of collectVueFiles(SRC_DIR)) { // 抽屉自身、以及 auth-gate 包装器(抽屉由使用它的页面负责挂)跳过 if (file.includes(join('components', 'auth-modal'))) continue if (file.includes(join('components', 'auth-gate'))) continue // uni-app 的 App.vue **没有模板**(只用来注册 401 处理器,里面调了 showAuthModal), // 本来就没地方挂组件 —— 抽屉一律由「当前页面」自己挂 if (file === join(SRC_DIR, 'App.vue')) continue const text = readFileSync(file, 'utf8') if (!NEEDS_DRAWER_RE.test(text)) continue if (HAS_DRAWER_RE.test(text)) continue warnings.push( `${file.slice(SRC_DIR.length + 1)} 用了 goLogin() / requireLogin() / showAuthModal() / ,` + '但没有挂载 :点「去登录」会没反应(抽屉无处渲染)' ) } // ── 输出 ── for (const warn of warnings) console.warn(`⚠ ${warn}`) for (const error of errors) console.error(`✖ ${error}`) if (errors.length > 0) { console.error(`\n✖ 静态路由表校验失败:${errors.length} 个错误,${warnings.length} 个告警`) process.exit(1) } console.log( `✔ 静态路由表校验通过:PAGE_REGISTRY ${entries.length} 条,` + `pages.json 已注册 ${registered.size} 个页面,${warnings.length} 个告警` )