-
Notifications
You must be signed in to change notification settings - Fork 418
Expand file tree
/
Copy pathget-source-map.ts
More file actions
33 lines (29 loc) · 1.1 KB
/
get-source-map.ts
File metadata and controls
33 lines (29 loc) · 1.1 KB
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
import { type RawSourceMap, SourceMapConsumer } from "source-map-js";
const INLINE_SOURCEMAP_REGEX = /^data:application\/json[^,]+base64,/;
const SOURCEMAP_REGEX =
/(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*(?:\*\/)[ \t]*$)/;
export default async function getSourceMap(
url: string,
content: string,
): Promise<SourceMapConsumer | null> {
const lines = content.split("\n");
let sourceMapUrl: string | undefined;
for (let i = lines.length - 1; i >= 0 && !sourceMapUrl; i--) {
const result = lines[i]!.match(SOURCEMAP_REGEX);
if (result) {
sourceMapUrl = result[1];
}
}
if (!sourceMapUrl) {
return null;
}
if (!(INLINE_SOURCEMAP_REGEX.test(sourceMapUrl) || sourceMapUrl.startsWith("/"))) {
// Resolve path if it's a relative access
const parsedURL = url.split("/");
parsedURL[parsedURL.length - 1] = sourceMapUrl;
sourceMapUrl = parsedURL.join("/");
}
const response = await fetch(sourceMapUrl);
const rawSourceMap: RawSourceMap = await response.json();
return new SourceMapConsumer(rawSourceMap);
}