Files
image-workbench-desktop/scripts/lib/coverage-bundle.js
T

159 lines
6.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict'
// 覆盖率归因公共库(2026-10-28)
//
// 背景:项目有两条覆盖率来源 ——
// ① scripts/coverage-browser.js:探针脚本,**无断言**,测"广度"
// ② e2e(42 个 spec,有断言):测"被断言过的行为",由 tests/_pw-coverage.js 采集
// 两者都要把 V8 的**字符偏移**映射回「哪个源文件、哪些区间」,这段逻辑必须只有一份,
// 否则偏移算法一旦改动两边会静默不一致(这正是本次抽库的原因)。
const fs = require('fs')
const path = require('path')
const cp = require('child_process')
const { transformSync } = require('esbuild')
/**
* 重放 scripts/build.js 的拼接过程,得到与 dist/app.js **逐字节一致**的 bundle,
* 并记录每个源文件在 bundle 里的 [start, end) 区间。
*/
function buildBundle(root) {
const run = (cmd) => cp.execFileSync(cmd[0], cmd.slice(1), { cwd: root, encoding: 'utf8' }).trim()
const gitSha = (() => { try { return run(['git', 'rev-parse', '--short=7', 'HEAD']) } catch (e) { return 'local' } })()
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
const version = 'v' + pkg.version + '+' + gitSha
const minifyJs = (code) => transformSync(code, {
loader: 'js', minify: true, target: 'es2020', charset: 'utf8', legalComments: 'none',
}).code
// 顺序与 build.js 完全一致(顺序即加载序,别排序)
const buildJs = fs.readFileSync(path.join(root, 'scripts', 'build.js'), 'utf8')
const sourceModules = (buildJs.match(/const sourceModules\s*=\s*\[([\s\S]*?)\]/) || ['', ''])[1]
.split(',').map((s) => s.trim().replace(/^'|'$/g, '')).filter(Boolean)
const explicit = new Set(sourceModules)
const discovered = fs.readdirSync(path.join(root, 'src')).filter((f) => f.endsWith('.js') && !explicit.has(f)).sort()
const orderedModules = sourceModules.concat(discovered)
const appSource = fs.readFileSync(path.join(root, 'app.js'), 'utf8')
const appWithBuildMeta = appSource.replace(/const APP_VERSION = '[^']*'/, "const APP_VERSION = '" + version + "'")
if (appWithBuildMeta === appSource) throw new Error('APP_VERSION marker not found in app.js')
const banner = '/*! IWB ' + version + ' */\n'
let bundle = banner
const spans = [] // { file, start, end }
orderedModules.forEach((file, i) => {
if (i > 0) bundle += '\n;\n'
const code = minifyJs(fs.readFileSync(path.join(root, 'src', file), 'utf8'))
spans.push({ file: 'src/' + file, start: bundle.length, end: bundle.length + code.length })
bundle += code
})
bundle += '\n;\n'
const appCode = minifyJs(appWithBuildMeta)
spans.push({ file: 'app.js', start: bundle.length, end: bundle.length + appCode.length })
bundle += appCode
return { bundle, spans, version }
}
// ── 区间工具(半开区间 [s, e))──────────────────────────────────────────────
function mergeIntervals(list) {
const arr = list.filter(([s, e]) => e > s).sort((a, b) => a[0] - b[0])
const out = []
for (const [s, e] of arr) {
const last = out[out.length - 1]
if (last && s <= last[1]) last[1] = Math.max(last[1], e)
else out.push([s, e])
}
return out
}
function complement(merged, total) {
const out = []
let cur = 0
for (const [s, e] of merged) {
if (s > cur) out.push([cur, s])
cur = Math.max(cur, e)
}
if (cur < total) out.push([cur, total])
return out
}
/** 多个页面的「已覆盖区间」取并集(任一页面覆盖过即算覆盖) */
function unionCovered(perPageCovered, total) {
const all = []
for (const list of perPageCovered) for (const iv of list) all.push(iv)
return complement(mergeIntervals(all), total)
}
/** 把「未覆盖区间」分摊到各源文件 span 上,返回每个文件的 { total, dead } */
function attributeUncovered(spans, uncoveredMerged) {
const res = new Map()
for (const sp of spans) res.set(sp.file, { total: sp.end - sp.start, dead: 0 })
for (const [us, ue] of uncoveredMerged) {
for (const sp of spans) {
const s = Math.max(us, sp.start), e = Math.min(ue, sp.end)
if (e > s) res.get(sp.file).dead += e - s
}
}
return res
}
/**
* V8 偏移单位判定。
* ⚠️ 中文串让 char 与 byte 差异很大,必须检测;判错会让归因整体错位(覆盖率虚高/虚低)。
*/
function detectUnit(bundle, maxOffset) {
const chars = bundle.length
const bytes = Buffer.byteLength(bundle)
if (maxOffset <= chars) return 'char'
if (maxOffset <= bytes) return 'byte'
return 'unknown'
}
/** byte 偏移 → char 偏移 的映射函数 */
function makeToChar(bundle) {
const chars = bundle.length
const bytes = Buffer.byteLength(bundle)
const byteToChar = new Int32Array(bytes + 1).fill(-1)
let b = 0
for (let i = 0; i < chars; i++) { byteToChar[b] = i; b += Buffer.byteLength(bundle[i]) }
byteToChar[bytes] = chars
return (off) => {
const v = byteToChar[off]
if (v >= 0) return v
for (let k = off - 1; k >= 0; k--) if (byteToChar[k] >= 0) return byteToChar[k]
return 0
}
}
/**
* 从一页的 V8 coverage 条目算出「未覆盖区间」(char 偏移,已合并)。
* ⚠️ V8 块覆盖语义:外层函数区间 count>0 会覆盖全文,**未覆盖 = 所有 count===0 区间的并集**。
*/
function uncoveredIntervals(entry, bundle) {
let maxOff = 0
for (const fn of entry.functions || []) for (const r of fn.ranges || []) if (r.endOffset > maxOff) maxOff = r.endOffset
const unit = detectUnit(bundle, maxOff)
const toChar = unit === 'byte' ? makeToChar(bundle) : unit === 'char' ? (o) => o : () => 0
const dead = []
for (const fn of entry.functions || []) {
for (const r of fn.ranges || []) {
if (r.count === 0) dead.push([toChar(r.startOffset), toChar(r.endOffset)])
}
}
return { unit, uncovered: mergeIntervals(dead) }
}
module.exports = {
buildBundle,
mergeIntervals,
complement,
unionCovered,
attributeUncovered,
detectUnit,
makeToChar,
uncoveredIntervals,
}