microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
test-microbuild1

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/debugger/sourceMap.ts

199lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import * as url from "url";
5import * as path from "path";
6import { RawSourceMap } from "source-map";
7import { SourceMapsCombinator } from "./sourceMapsCombinator";
8
9const IS_REMOTE = /^[A-z]{2,}:\/\//; // Detection remote sources or specific protocols (like "webpack:///")
10
11interface ISourceMap extends RawSourceMap {
12 sections?: ISourceMapSection[];
13}
14interface ISourceMapSection {
15 map: ISourceMap;
16 offset: { column: number; line: number };
17}
18
19export interface IStrictUrl extends url.Url {
20 pathname: string;
21 href: string;
22}
23
24export class SourceMapUtil {
25 private static SourceMapURLGlobalRegex: RegExp =
26 /\/\/(#|@) sourceMappingURL=((?!data:)[^ ]+?)\s*$/gm;
27 private static SourceMapURLRegex: RegExp = /\/\/(#|@) sourceMappingURL=((?!data:)[^ ]+?)\s*$/m;
28 private static SourceURLRegex: RegExp = /^\/\/[#@] ?sourceURL=(.+)$/m;
29
30 /**
31 * Given a script body and URL, this method parses the body and finds the corresponding source map URL.
32 * If the source map URL is not found in the body in the expected form, null is returned.
33 */
34 public getSourceMapURL(scriptUrl: url.Url, scriptBody: string): IStrictUrl | null {
35 let result: IStrictUrl | null = null;
36
37 // scriptUrl = "http://localhost:8081/index.ios.bundle?platform=ios&dev=true"
38 const sourceMappingRelativeUrl = this.getSourceMapRelativeUrl(scriptBody); // sourceMappingRelativeUrl = "/index.ios.map?platform=ios&dev=true"
39 if (sourceMappingRelativeUrl) {
40 const sourceMappingUrl = url.parse(sourceMappingRelativeUrl);
41 sourceMappingUrl.protocol = scriptUrl.protocol;
42 sourceMappingUrl.host = scriptUrl.host;
43 // parse() repopulates all the properties of the URL
44 result = <IStrictUrl>url.parse(url.format(sourceMappingUrl));
45 }
46
47 return result;
48 }
49
50 /**
51 * Updates the contents of a source map file to be VS Code friendly:
52 * - makes source paths unix style and relative to the sources root path
53 * - updates the url of the script file
54 * - deletes the script content from the source map
55 *
56 * @parameter sourceMapBody - body of the source map as generated by the RN Packager.
57 * @parameter scriptPath - path of the script file asssociated with this source map.
58 * @parameter sourcesRootPath - root path of sources
59 *
60 */
61 public updateSourceMapFile(
62 sourceMapBody: string,
63 scriptPath: string,
64 sourcesRootPath: string,
65 packagerRemoteRoot?: string,
66 packagerLocalRoot?: string,
67 ): string {
68 try {
69 let sourceMap = <ISourceMap>JSON.parse(sourceMapBody);
70
71 if (sourceMap.sections) {
72 // TODO: there is a need to handle value.map == null, make a fake map
73 sourceMap.sections = sourceMap.sections.filter(value => value.map != null);
74
75 // eslint-disable-next-line @typescript-eslint/no-var-requires
76 sourceMap = require("flatten-source-map")(sourceMap);
77 }
78
79 const sourceMapsCombinator = new SourceMapsCombinator();
80 sourceMap = sourceMapsCombinator.convert(sourceMap);
81
82 if (sourceMap.sources) {
83 sourceMap.sources = sourceMap.sources.map(sourcePath =>
84 IS_REMOTE.test(sourcePath)
85 ? sourcePath
86 : this.updateSourceMapPath(
87 sourcePath,
88 sourcesRootPath,
89 packagerRemoteRoot,
90 packagerLocalRoot,
91 ),
92 );
93 }
94
95 delete sourceMap.sourcesContent;
96 sourceMap.sourceRoot = "";
97 sourceMap.file = scriptPath;
98 return JSON.stringify(sourceMap);
99 } catch (exception) {
100 return sourceMapBody;
101 }
102 }
103
104 public appendSourceMapPaths(scriptBody: string, sourceMappingUrl: string): string {
105 scriptBody += `//# sourceMappingURL=${sourceMappingUrl}`;
106 return scriptBody;
107 }
108
109 /**
110 * Updates source map URLs in the script body.
111 */
112 public updateScriptPaths(scriptBody: string, sourceMappingUrl: IStrictUrl): string {
113 const sourceMapMatch = this.searchSourceMapURL(scriptBody);
114 if (sourceMapMatch) {
115 // Update the body with the new location of the source map on storage.
116 return scriptBody.replace(
117 sourceMapMatch[0],
118 `//# sourceMappingURL=${path.basename(sourceMappingUrl.pathname)}`,
119 );
120 }
121 return scriptBody;
122 }
123
124 /**
125 * Removes sourceURL from the script body since RN 0.61 because it breaks sourcemaps.
126 * Example: //# sourceURL=http://localhost:8081/index.bundle?platform=android&dev=true&minify=false -> ""
127 */
128 public removeSourceURL(scriptBody: string): string {
129 return scriptBody.replace(SourceMapUtil.SourceURLRegex, "");
130 }
131
132 /**
133 * Parses the body of a script searching for a source map URL.
134 * It supports the following source map url styles:
135 *
136 * `//# sourceMappingURL=path/to/source/map`
137 *
138 * `//@ sourceMappingURL=path/to/source/map`
139 *
140 * Returns the last match if found, null otherwise.
141 */
142 public getSourceMapRelativeUrl(body: string): string | null {
143 const sourceMapMatch = this.searchSourceMapURL(body);
144 // If match is null, the body doesn't contain the source map
145 if (sourceMapMatch) {
146 // On React Native macOS 0.62 and RN Windows 0.65 sourceMappingUrl looks like:
147 // # sourceMappingURL=//localhost:8081/index.map?platform=macos&dev=true&minify=false
148 // Add 'http:' protocol to avoid errors in further processing
149 const el = sourceMapMatch[2];
150 const macOsOrWin =
151 (el.includes("platform=macos") || el.includes("platform=window")) &&
152 el.startsWith("//") &&
153 !el.includes("http:");
154
155 return macOsOrWin ? `http:${el}` : el;
156 }
157 return null;
158 }
159
160 private searchSourceMapURL(str: string): RegExpMatchArray | null {
161 const matchesList = str
162 .match(SourceMapUtil.SourceMapURLGlobalRegex)
163 ?.filter(s => !s.includes("\\n"));
164 if (matchesList && matchesList.length) {
165 return matchesList[matchesList.length - 1].match(SourceMapUtil.SourceMapURLRegex);
166 }
167
168 return null;
169 }
170
171 /**
172 * Given an absolute source path, this method does two things:
173 * 1. It changes the path from absolute to be relative to the sourcesRootPath parameter.
174 * 2. It changes the path separators to Unix style.
175 */
176 private updateSourceMapPath(
177 sourcePath: string,
178 sourcesRootPath: string,
179 packagerRemoteRoot?: string,
180 packagerLocalRoot?: string,
181 ) {
182 if (packagerRemoteRoot && packagerLocalRoot) {
183 packagerRemoteRoot = this.makeUnixStylePath(packagerRemoteRoot);
184 packagerLocalRoot = this.makeUnixStylePath(packagerLocalRoot);
185 sourcePath = sourcePath.replace(packagerRemoteRoot, packagerLocalRoot);
186 }
187 const relativeSourcePath = path.relative(sourcesRootPath, sourcePath);
188 return this.makeUnixStylePath(relativeSourcePath);
189 }
190
191 /**
192 * Visual Studio Code source mapping requires Unix style path separators.
193 * This method replaces all back-slash characters in a given string with forward-slash ones.
194 */
195 private makeUnixStylePath(p: string): string {
196 const pathArgs = p.split(path.sep);
197 return path.posix.join.apply(null, pathArgs);
198 }
199}
200