Debian Codegraph @

packages/babel-core/src/transformation/file/merge-map.ts

raw
1 type SourceMap = any;
2 import remapping from "@ampproject/remapping";
3
4 export default function mergeSourceMap(
5 inputMap: SourceMap,
6 map: SourceMap,
7 sourceFileName: string,
8 ): SourceMap {
9 // On win32 machines, the sourceFileName uses backslash paths like
10 // `C:\foo\bar.js`. But sourcemaps are always posix paths, so we need to
11 // normalize to regular slashes before we can merge (else we won't find the
12 // source associated with our input map).
13 // This mirrors code done while generating the output map at
14 // https://github.com/babel/babel/blob/5c2fcadc9ae34fd20dd72b1111d5cf50476d700d/packages/babel-generator/src/source-map.ts#L102
15 const source = sourceFileName.replace(/\\/g, "/");
16
17 // Prevent an infinite recursion if one of the input map's sources has the
18 // same resolved path as the input map. In the case, it would keep find the
19 // input map, then get it's sources which will include a path like the input
20 // map, on and on.
21 let found = false;
22 const result = remapping(rootless(map), (s, ctx) => {
23 if (s === source && !found) {
24 found = true;
25 // We empty the source location, which will prevent the sourcemap from
26 // becoming relative to the input's location. Eg, if we're transforming a
27 // file 'foo/bar.js', and it is a transformation of a `baz.js` file in the
28 // same directory, the expected output is just `baz.js`. Without this step,
29 // it would become `foo/baz.js`.
30 ctx.source = "";
31
32 return rootless(inputMap);
33 }
34
35 return null;
36 });
37
38 if (typeof inputMap.sourceRoot === "string") {
39 result.sourceRoot = inputMap.sourceRoot;
40 }
41
42 // remapping returns a SourceMap class type, but this breaks code downstream in
43 // @babel/traverse and @babel/types that relies on data being plain objects.
44 // When it encounters the sourcemap type it outputs a "don't know how to turn
45 // this value into a node" error. As a result, we are converting the merged
46 // sourcemap to a plain js object.
47 return { ...result };
48 }
49
50 function rootless(map: SourceMap): SourceMap {
51 return {
52 ...map,
53
54 // This is a bit hack. Remapping will create absolute sources in our
55 // sourcemap, but we want to maintain sources relative to the sourceRoot.
56 // We'll re-add the sourceRoot after remapping.
57 sourceRoot: null,
58 };
59 }