a post-component library for building user-interfaces on the web.
1import astV8ToIstanbul from 'ast-v8-to-istanbul'
2import libCoverage from 'istanbul-lib-coverage'
3import libReport from 'istanbul-lib-report'
4import reports from 'istanbul-reports'
5import * as fs from 'node:fs/promises'
6import * as path from 'node:path'
7import { fileURLToPath, pathToFileURL } from 'node:url'
8import { parseSync } from 'oxc-parser'
9
10export type Coverage = import('node:inspector').Profiler.ScriptCoverage
11
12export async function handle_coverage(coverage_entries: Coverage[]): Promise<void> {
13 let coverage_map = libCoverage.createCoverageMap()
14
15 for (const coverage of coverage_entries) {
16 const path = url_to_file_path(coverage.url)
17 if (!path) continue
18
19 const code = await fs.readFile(path, 'utf8')
20
21 coverage_map.merge(
22 await astV8ToIstanbul({
23 code,
24 ast: parseSync(path, code),
25 coverage: { functions: coverage.functions, url: pathToFileURL(path).toString() },
26 }),
27 )
28 }
29
30 coverage_map.filter(key => {
31 if (key.includes('node_modules')) return false
32 if (key.includes('tests')) return false
33 return key.includes('src')
34 })
35
36 const context = libReport.createContext({ coverageMap: coverage_map })
37 reports.create('html-spa').execute(context)
38 reports.create('lcovonly').execute(context)
39 reports.create('text').execute(context)
40}
41
42function url_to_file_path(url: string) {
43 if (!URL.canParse(url)) return null
44
45 const { protocol, pathname } = new URL(url)
46 if (protocol === 'file:') return fileURLToPath(url)
47 if (protocol === 'http:' || protocol === 'https:') return path.resolve(process.cwd(), pathname.slice(1))
48
49 return null
50}