8776a9bf1e
- ElMessage.error 全收进 showAdminFeedback(例外清单 CAP=0,唯一保留的裸调用是出口本体); window.confirm 24 处全部改成 await 的 openAdminConfirm(逐处核过所在函数本就 async, 不存在"点了确认不执行"的异步断层)。 - 新增 load-failure-model + LoadFailureBar:22/23 个取数页有失败态与真重试 (只有"知道了"清条不算过),例外仅登录页。 - DedupeRegistryPage / DuplicateCheckPage 补 onUnmounted,并加全树定时器/监听配对判据。 - 去重页那处"能点但后端 403":读侧认 wholeCompany、写侧只认 groupIds/userIds 的不对称 本轮没动后端(前端拿不到与写侧同集合的 groupIds,按它置灰会误伤同事名下真能改的行=静默删功能); 先修更实在的一半——403 的中文原因此前整段丢失,现在走统一文案到界面。 - 验收:node --test 1,818 例 0 红、npx vue-tsc --noEmit rc=0;5 支新判据 26 例。
200 lines
9.5 KiB
TypeScript
200 lines
9.5 KiB
TypeScript
/**
|
||
* 定时器 / 事件监听的清理配对(四面9分口径 · 后管「稳定 7.0:定时器清理配对只有 2/4」)。
|
||
*
|
||
* 评审点名:`DedupeRegistryPage.vue`(导出秒表 setInterval + 导入轮询)与 `DuplicateCheckPage.vue`
|
||
* (toast 收尾 setTimeout)**没有 `onUnmounted`**——离开页面后定时器还在跑,每秒改一个没人看的 ref,
|
||
* 而导入轮询最多还会再打 300 拍。这一支把配对关系落成判据:
|
||
* ① 有 `setInterval(` 的文件必须同时有 `clearInterval(` 和一个卸载钩子;
|
||
* ② 有 `addEventListener(` 的文件必须同时有 `removeEventListener(` 和一个卸载钩子;
|
||
* ③ 一次性 `setTimeout(` 也要有配对,除非落在下面这张例外名单里(名单只许减,锚构造名不锚行号)。
|
||
* 光有 clearInterval 不算过:只在"用户点了取消"那条路径清理,页面被路由切走时照样漏。
|
||
*/
|
||
import test from 'node:test'
|
||
import assert from 'node:assert/strict'
|
||
import { readdirSync, statSync } from 'node:fs'
|
||
import { join } from 'node:path'
|
||
import { readSource } from './helpers.ts'
|
||
|
||
/** 分母硬钉:2026-10-10 实测 setInterval 3 处、addEventListener 4 处、setTimeout 5 处。 */
|
||
const REPEATING_SITE_FLOOR = 7
|
||
/** 例外名单只许减:三条 sleep() 节拍原语。 */
|
||
const LEDGER_CAP = 3
|
||
|
||
const LEDGER: Array<{ file: string; construct: string; token: string; reason: string }> = [
|
||
{
|
||
file: 'src/pages/asin/DedupeRegistryPage.vue',
|
||
construct: 'function sleep(',
|
||
token: 'setTimeout(',
|
||
reason: 'sleep() 是导入进度轮询的一次性节拍原语,不重复自持;跨卸载的泄漏由本页 pageDisposed '
|
||
+ '闸门收口(onUnmounted 里置位,pollImport 下一拍直接抛),所以这一处不需要 clearTimeout',
|
||
},
|
||
{
|
||
file: 'src/pages/asin/QueryAsinPage.vue',
|
||
construct: 'function sleep(',
|
||
token: 'setTimeout(',
|
||
reason: '同 DedupeRegistryPage 的轮询节拍原语;本页 importProgress 轮询用完后自行走完,'
|
||
+ '未接卸载中断(本批次只登记不扩改),名单只许减',
|
||
},
|
||
{
|
||
file: 'src/pages/asin/SkipPricePage.vue',
|
||
construct: 'function sleep(',
|
||
token: 'setTimeout(',
|
||
reason: '同上:sleep() 节拍原语,卸载中断未接,登记在案等下一批收口',
|
||
},
|
||
]
|
||
|
||
const REPEATING: Array<{ token: string; mate: string; what: string }> = [
|
||
{ token: 'setInterval(', mate: 'clearInterval(', what: '重复定时器' },
|
||
{ token: 'addEventListener(', mate: 'removeEventListener(', what: '事件监听' },
|
||
{ token: 'setTimeout(', mate: 'clearTimeout(', what: '一次性定时器' },
|
||
]
|
||
|
||
function codeOf(src: string): string {
|
||
return src.split('\n').filter((line) => !/^\s*(\/\/|\*|\/\*)/.test(line)).join('\n')
|
||
}
|
||
|
||
function hasHook(code: string): boolean {
|
||
return code.includes('onUnmounted(') || code.includes('onBeforeUnmount(')
|
||
}
|
||
|
||
/** 一个文件里未配对的定时器/监听(返回缺哪几条,空 = 过)。 */
|
||
export function cleanupGaps(code: string, ledgerTokens: string[] = []): string[] {
|
||
const gaps: string[] = []
|
||
for (const { token, mate, what } of REPEATING) {
|
||
if (!code.includes(token)) continue
|
||
if (ledgerTokens.includes(token)) continue
|
||
if (!code.includes(mate)) gaps.push(`${what}:有 ${token} 却没有 ${mate}`)
|
||
if (!hasHook(code)) gaps.push(`${what}:${token} 所在文件没有 onUnmounted/onBeforeUnmount`)
|
||
}
|
||
return gaps
|
||
}
|
||
|
||
function sourceFiles(): string[] {
|
||
const out: string[] = []
|
||
const walk = (dir: string): void => {
|
||
for (const name of readdirSync(dir)) {
|
||
const abs = join(dir, name)
|
||
if (name.endsWith('.d.ts')) continue
|
||
if (statSync(abs).isDirectory()) walk(abs)
|
||
else if (name.endsWith('.vue') || name.endsWith('.ts')) out.push(abs.split(/[\\/]+/).join('/'))
|
||
}
|
||
}
|
||
walk('src')
|
||
return out
|
||
}
|
||
|
||
const FILES = sourceFiles()
|
||
/** 例外只在「登记的那个构造确实还在文件里」时生效:删掉了 sleep 也等于删掉了这条豁免。 */
|
||
const ledgerTokensFor = (rel: string, code: string): string[] =>
|
||
LEDGER.filter((e) => e.file === rel && code.includes(e.construct)).map((e) => e.token)
|
||
const offenders = FILES
|
||
.map((rel) => {
|
||
const code = codeOf(readSource(rel))
|
||
return { rel, gaps: cleanupGaps(code, ledgerTokensFor(rel, code)) }
|
||
})
|
||
.filter((x) => x.gaps.length > 0)
|
||
|
||
test('分母硬钉:重复定时器/监听的数量像被真的数到了', () => {
|
||
assert.ok(FILES.length >= 180, `只扫到 ${FILES.length} 个源文件`)
|
||
const sites = FILES.reduce((sum, rel) => {
|
||
const code = codeOf(readSource(rel))
|
||
return sum + (code.match(/setInterval\(/g) || []).length + (code.match(/addEventListener\(/g) || []).length
|
||
}, 0)
|
||
assert.ok(sites >= REPEATING_SITE_FLOOR,
|
||
`setInterval+addEventListener 只数到 ${sites} 处(阈值 ${REPEATING_SITE_FLOOR}):判据扫空了会把"漏清理"读成"没有定时器"`)
|
||
})
|
||
|
||
test('每处定时器/监听都有配对的清理 + 卸载钩子(名单外点名,名单只许减)', () => {
|
||
assert.ok(LEDGER.length <= LEDGER_CAP, `例外名单从 ${LEDGER_CAP} 涨到 ${LEDGER.length}:这条口径只许减`)
|
||
assert.deepEqual(offenders.map((x) => `${x.rel} -> ${x.gaps.join(';')}`), [],
|
||
`清理没配对的页面:\n${offenders.map((x) => `${x.rel}: ${x.gaps.join(';')}`).join('\n')}`)
|
||
// 名单里的每一条都要仍然成立:构造还在、文件确实还有裸 setTimeout。
|
||
for (const entry of LEDGER) {
|
||
const code = codeOf(readSource(entry.file))
|
||
assert.ok(code.includes(entry.construct), `${entry.file} 里已经找不到 ${entry.construct},这条登记该删`)
|
||
assert.ok(code.includes('setTimeout('), `${entry.file} 已无 setTimeout,这条登记该删`)
|
||
assert.ok(entry.reason.length >= 16, `${entry.file} 的例外理由没写清楚`)
|
||
}
|
||
})
|
||
|
||
/** 取 `onUnmounted(() => { ... })` 的钩子体(到配对的右括为止,最多 400 字符)。 */
|
||
export function unmountHookBody(code: string): string {
|
||
const at = code.search(/on(?:Before)?Unmounted\(\s*\(\s*\)\s*=>\s*\{/)
|
||
if (at < 0) return ''
|
||
const open = code.indexOf('{', at)
|
||
let depth = 0
|
||
for (let i = open; i < code.length && i - open < 400; i++) {
|
||
if (code[i] === '{') depth += 1
|
||
else if (code[i] === '}') {
|
||
depth -= 1
|
||
if (depth === 0) return code.slice(open + 1, i)
|
||
}
|
||
}
|
||
return code.slice(open + 1, open + 400)
|
||
}
|
||
|
||
/** 找到某个本地函数体的文本(够用到 clearInterval 那一层即可)。 */
|
||
function localFnBody(code: string, name: string): string {
|
||
const at = code.search(new RegExp(`function\\s+${name}\\s*\\(`))
|
||
if (at < 0) return ''
|
||
const open = code.indexOf('{', at)
|
||
let depth = 0
|
||
for (let i = open; i < code.length; i++) {
|
||
if (code[i] === '{') depth += 1
|
||
else if (code[i] === '}') {
|
||
depth -= 1
|
||
if (depth === 0) return code.slice(open + 1, i)
|
||
}
|
||
}
|
||
return ''
|
||
}
|
||
|
||
/** 卸载钩子真的把定时器收掉了?直接 clear 或调一个内部会 clear 的本地函数都算。 */
|
||
export function hookClearsTimer(code: string): boolean {
|
||
const body = unmountHookBody(code)
|
||
if (!body) return false
|
||
if (/clear(Interval|Timeout)\(/.test(body)) return true
|
||
return [...body.matchAll(/(\w+)\(\)/g)]
|
||
.some((m) => /clear(Interval|Timeout)\(/.test(localFnBody(code, m[1])))
|
||
}
|
||
|
||
test('评审点名的两个文件确实补上了卸载钩子', () => {
|
||
for (const rel of ['src/pages/asin/DedupeRegistryPage.vue', 'src/pages/tasks/DuplicateCheckPage.vue']) {
|
||
const code = codeOf(readSource(rel))
|
||
assert.ok(hasHook(code), `${rel} 仍无 onUnmounted/onBeforeUnmount`)
|
||
assert.ok(hookClearsTimer(code), `${rel} 的卸载钩子里没有真的清定时器(直接 clear 或调会 clear 的本地函数都算)`)
|
||
}
|
||
// 去重页另外半边:离开页面后导入轮询必须自己收口,不然还会再打 300 拍。
|
||
const dedupe = codeOf(readSource('src/pages/asin/DedupeRegistryPage.vue'))
|
||
assert.match(dedupe, /pageDisposed = true/)
|
||
assert.match(dedupe, /if \(pageDisposed\) throw/)
|
||
})
|
||
|
||
test('非零对照:钩子只置个标志位、没清定时器,会被判不过', () => {
|
||
const fakeHook = `function stop() { /* 这里没清 */ }\n`
|
||
+ `onUnmounted(() => { stop() })\n`
|
||
assert.equal(hookClearsTimer(fakeHook), false, '钩子调了个不清定时器的方法也算过 ⇒ 这条判据是软的')
|
||
const indirect = `function stop() { clearInterval(t) }\n`
|
||
+ `onUnmounted(() => { stop() })\n`
|
||
assert.equal(hookClearsTimer(indirect), true, '间接清理要认:不然 stopExportWait() 那种写法会被误判')
|
||
})
|
||
|
||
test('非零对照:造一个只 setInterval 不清理的文件会被点名', () => {
|
||
const leaked = `const t = setInterval(() => tick(), 1000)\n`
|
||
assert.deepEqual(cleanupGaps(leaked), [
|
||
'重复定时器:有 setInterval( 却没有 clearInterval(',
|
||
'重复定时器:setInterval( 所在文件没有 onUnmounted/onBeforeUnmount',
|
||
], '漏清理扫不出来 ⇒ 上面那条断言恒绿')
|
||
|
||
const hookless = `let t = null\nfunction go() { t = setInterval(() => tick(), 1000) }\nfunction stop() { clearInterval(t) }\n`
|
||
assert.deepEqual(cleanupGaps(hookless), ['重复定时器:setInterval( 所在文件没有 onUnmounted/onBeforeUnmount'],
|
||
'只在"点取消"那条路径清理、路由切走仍会漏,这种形态必须判不过')
|
||
|
||
const paired = `let t = null\nfunction go() { t = setInterval(() => tick(), 1000) }\n`
|
||
+ `onUnmounted(() => { clearInterval(t) })\n`
|
||
assert.deepEqual(cleanupGaps(paired), [])
|
||
|
||
const listenerLeak = `window.addEventListener('resize', onResize)\n`
|
||
assert.equal(cleanupGaps(listenerLeak).length, 2, 'addEventListener 不配对同样要被抓到')
|
||
})
|