/
sourcemap.ts
175 lines (154 loc) · 4.87 KB
/
sourcemap.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import path from 'node:path'
import fsp from 'node:fs/promises'
import convertSourceMap from 'convert-source-map'
import type { ExistingRawSourceMap, SourceMap } from 'rollup'
import type { Logger } from '../logger'
import { blankReplacer, createDebugger } from '../utils'
const debug = createDebugger('vite:sourcemap', {
onlyWhenFocused: true,
})
// Virtual modules should be prefixed with a null byte to avoid a
// false positive "missing source" warning. We also check for certain
// prefixes used for special handling in esbuildDepPlugin.
const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/
interface SourceMapLike {
sources: string[]
sourcesContent?: (string | null)[]
sourceRoot?: string
}
async function computeSourceRoute(map: SourceMapLike, file: string) {
let sourceRoot: string | undefined
try {
// The source root is undefined for virtual modules and permission errors.
sourceRoot = await fsp.realpath(
path.resolve(path.dirname(file), map.sourceRoot || ''),
)
} catch {}
return sourceRoot
}
export async function injectSourcesContent(
map: SourceMapLike,
file: string,
logger: Logger,
): Promise<void> {
let sourceRootPromise: Promise<string | undefined>
const missingSources: string[] = []
const sourcesContent = map.sourcesContent || []
const sourcesContentPromises: Promise<void>[] = []
for (let index = 0; index < map.sources.length; index++) {
const sourcePath = map.sources[index]
if (
!sourcesContent[index] &&
sourcePath &&
!virtualSourceRE.test(sourcePath)
) {
sourcesContentPromises.push(
(async () => {
// inject content from source file when sourcesContent is null
sourceRootPromise ??= computeSourceRoute(map, file)
const sourceRoot = await sourceRootPromise
let resolvedSourcePath = decodeURI(sourcePath)
if (sourceRoot) {
resolvedSourcePath = path.resolve(sourceRoot, resolvedSourcePath)
}
sourcesContent[index] = await fsp
.readFile(resolvedSourcePath, 'utf-8')
.catch(() => {
missingSources.push(resolvedSourcePath)
return null
})
})(),
)
}
}
await Promise.all(sourcesContentPromises)
map.sourcesContent = sourcesContent
// Use this command…
// DEBUG="vite:sourcemap" vite build
// …to log the missing sources.
if (missingSources.length) {
logger.warnOnce(`Sourcemap for "${file}" points to missing source files`)
debug?.(`Missing sources:\n ` + missingSources.join(`\n `))
}
}
export function genSourceMapUrl(map: SourceMap | string): string {
if (typeof map !== 'string') {
map = JSON.stringify(map)
}
return `data:application/json;base64,${Buffer.from(map).toString('base64')}`
}
export function getCodeWithSourcemap(
type: 'js' | 'css',
code: string,
map: SourceMap,
): string {
if (debug) {
code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`
}
if (type === 'js') {
code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`
} else if (type === 'css') {
code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`
}
return code
}
export function applySourcemapIgnoreList(
map: ExistingRawSourceMap,
sourcemapPath: string,
sourcemapIgnoreList: (sourcePath: string, sourcemapPath: string) => boolean,
logger?: Logger,
): void {
let { x_google_ignoreList } = map
if (x_google_ignoreList === undefined) {
x_google_ignoreList = []
}
for (
let sourcesIndex = 0;
sourcesIndex < map.sources.length;
++sourcesIndex
) {
const sourcePath = map.sources[sourcesIndex]
if (!sourcePath) continue
const ignoreList = sourcemapIgnoreList(
path.isAbsolute(sourcePath)
? sourcePath
: path.resolve(path.dirname(sourcemapPath), sourcePath),
sourcemapPath,
)
if (logger && typeof ignoreList !== 'boolean') {
logger.warn('sourcemapIgnoreList function must return a boolean.')
}
if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) {
x_google_ignoreList.push(sourcesIndex)
}
}
if (x_google_ignoreList.length > 0) {
if (!map.x_google_ignoreList) map.x_google_ignoreList = x_google_ignoreList
}
}
export async function extractSourcemapFromFile(
code: string,
filePath: string,
): Promise<{ code: string; map: SourceMap } | undefined> {
const map = (
convertSourceMap.fromSource(code) ||
(await convertSourceMap.fromMapFileSource(
code,
createConvertSourceMapReadMap(filePath),
))
)?.toObject()
if (map) {
return {
code: code.replace(convertSourceMap.mapFileCommentRegex, blankReplacer),
map,
}
}
}
function createConvertSourceMapReadMap(originalFileName: string) {
return (filename: string) => {
return fsp.readFile(
path.resolve(path.dirname(originalFileName), filename),
'utf-8',
)
}
}