File size: 2,196 Bytes
bc20498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import path from 'node:path';

const IS_WINDOWS = process.platform === 'win32';

/**
 * @typedef {{
 *  file?: string;
 *  sources?: string[];
 *  sourceRoot?: string;
 * }} SourceMapFileRefs
 */

/**
 * convert absolute paths in sourcemap file refs to their relative equivalents to avoid leaking fs info
 *
 * map is modified in place.
 *
 * @param {SourceMapFileRefs | undefined} map sourcemap
 * @param {string} filename absolute path to file the sourcemap is for
 */
export function mapToRelative(map, filename) {
	if (!map) {
		return;
	}
	const sourceRoot = map.sourceRoot;
	const dirname = path.dirname(filename);

	/** @type {(s: string) => string} */
	const toRelative = (s) => {
		if (!s) {
			return s;
		}
		/** @type {string} */
		let sourcePath;
		if (s.startsWith('file:///')) {
			// windows has file:///C:/foo and posix has file:///foo, so we have to remove one extra on windows
			sourcePath = s.slice(IS_WINDOWS ? 8 : 7);
		} else if (sourceRoot) {
			const sep = sourceRoot[sourceRoot.length - 1] === '/' || s[0] === '/' ? '' : '/';
			sourcePath = `${sourceRoot}${sep}${s}`;
		} else {
			sourcePath = s;
		}
		return path.isAbsolute(sourcePath) ? path.relative(dirname, sourcePath) : sourcePath;
	};

	if (map.file) {
		map.file = path.basename(filename);
	}
	if (map.sources) {
		map.sources = map.sources.map(toRelative);
	}
	if (map.sourceRoot) {
		// we have prepended sourceRoot and computed relative paths from it
		// remove it here to avoid downstream processing prepending it again
		delete map.sourceRoot;
	}
}

/**
 * vitePreprocess uses an extra lang extension to tell vite about the type of preprocessor to use
 * This function removes it afterwards to get back working file refs
 *
 * map is modified in place.
 *
 * @param {SourceMapFileRefs | undefined} map the output sourcemap
 * @param {string} suffix the suffix to remove
 */
export function removeLangSuffix(map, suffix) {
	if (!map) {
		return;
	}
	/** @type {(s:string)=> string} */
	const removeSuffix = (s) => (s?.endsWith(suffix) ? s.slice(0, -1 * suffix.length) : s);
	if (map.file) {
		map.file = removeSuffix(map.file);
	}
	if (map.sources) {
		map.sources = map.sources.map(removeSuffix);
	}
}