Skip to content

Commit 57f3bb3

Browse files
fix(unplugin): emit column-accurate sourcemaps
Bare generateMap() collapses every mapping to column 0, so V8 coverage drops modules that use auto-imports. Pass hires: 'boundary' and source.
1 parent a86212a commit 57f3bb3

2 files changed

Lines changed: 57 additions & 1 deletion

File tree

‎src/unplugin.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ export default createUnplugin<Partial<UnimportPluginOptions>>((options = {}) =>
6161

6262
return {
6363
code: s.toString(),
64-
map: s.generateMap(),
64+
map: s.generateMap({ hires: 'boundary', source: id }),
6565
}
6666
},
6767
async buildStart() {

‎test/unplugin.test.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { describe, expect, it } from 'vitest'
2+
import Unimport from '../src/unplugin'
3+
4+
const id = '/src/a.ts'
5+
const code = [
6+
'export function classify(n) {',
7+
' const h = helper();',
8+
' if (n > 10) return h.big;',
9+
' if (n > 0) return h.small;',
10+
' return h.zero;',
11+
'}',
12+
'',
13+
].join('\n')
14+
15+
function createPlugin() {
16+
return Unimport.raw(
17+
{
18+
imports: [{ name: 'helper', from: 'my-lib' }],
19+
},
20+
{ framework: 'vite', versions: {} },
21+
)
22+
}
23+
24+
async function transform(input: string, fileId = id) {
25+
const hook = createPlugin().transform
26+
const handler = typeof hook === 'function' ? hook : hook!.handler
27+
return handler.call(
28+
{} as never,
29+
input,
30+
fileId,
31+
) as Promise<{ code: string, map: { mappings: string, sources: string[] } } | undefined>
32+
}
33+
34+
/**
35+
* Sourcemap `mappings` are grouped by generated line (`;`), then by segment
36+
* (`,`). A line-only map has one segment per line, all at column 0.
37+
*/
38+
function segmentsPerLine(mappings: string) {
39+
return mappings.split(';').map(line => (line === '' ? 0 : line.split(',').length))
40+
}
41+
42+
describe('unplugin', () => {
43+
it('injects auto-imports and emits a column-accurate sourcemap', async () => {
44+
const result = await transform(code)
45+
46+
expect(result?.code).toContain(`import { helper } from 'my-lib';`)
47+
expect(result?.map.sources).toEqual([id])
48+
// Bare generateMap() emits one mapping per line. V8 coverage then drops
49+
// the file and reports 100% (0/0). See https://github.com/unjs/unimport/issues/562
50+
expect(Math.max(...segmentsPerLine(result!.map.mappings))).toBeGreaterThan(1)
51+
})
52+
53+
it('skips files that do not use auto-imports', async () => {
54+
expect(await transform('export const one = 1;\n')).toBeUndefined()
55+
})
56+
})

0 commit comments

Comments
 (0)