forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloadSourceAndMetadata.js
More file actions
513 lines (444 loc) · 18.2 KB
/
loadSourceAndMetadata.js
File metadata and controls
513 lines (444 loc) · 18.2 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
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
// Parsing source and source maps is done in a Web Worker
// because parsing is CPU intensive and should not block the UI thread.
//
// Fetching source and source map files is intentionally done on the UI thread
// so that loaded source files can reuse the browser's Network cache.
// Requests made from within an extension do not share the page's Network cache,
// but messages can be sent from the UI thread to the content script
// which can make a request from the page's context (with caching).
//
// Some overhead may be incurred sharing (serializing) the loaded data between contexts,
// but less than fetching the file to begin with,
// and in some cases we can avoid serializing the source code at all
// (e.g. when we are in an environment that supports our custom metadata format).
//
// The overall flow of this file is such:
// 1. Find the Set of source files defining the hooks and load them all.
// Then for each source file, do the following:
//
// a. Search loaded source file to see if a source map is available.
// If so, load that file and pass it to a Worker for parsing.
// The source map is used to retrieve the original source,
// which is then also parsed in the Worker to infer hook names.
// This is less ideal because parsing a full source map is slower,
// since we need to evaluate the mappings in order to map the runtime code to the original source,
// but at least the eventual source that we parse to an AST is small/fast.
//
// b. If no source map, pass the full source to a Worker for parsing.
// Use the source to infer hook names.
// This is the least optimal route as parsing the full source is very CPU intensive.
//
// In the future, we may add an additional optimization the above sequence.
// This check would come before the source map check:
//
// a. Search loaded source file to see if a custom React metadata file is available.
// If so, load that file and pass it to a Worker for parsing and extracting.
// This is the fastest option since our custom metadata file is much smaller than a full source map,
// and there is no need to convert runtime code to the original source.
import {__DEBUG__} from 'react-devtools-shared/src/constants';
import {getHookSourceLocationKey} from 'react-devtools-shared/src/hookNamesCache';
import {sourceMapIncludesSource} from '../SourceMapUtils';
import {
withAsyncPerfMeasurements,
withCallbackPerfMeasurements,
withSyncPerfMeasurements,
} from 'react-devtools-shared/src/PerformanceLoggingUtils';
import type {
HooksNode,
HookSource,
HooksTree,
} from 'react-debug-tools/src/ReactDebugHooks';
import type {MixedSourceMap} from '../SourceMapTypes';
import type {FetchFileWithCaching} from 'react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext';
// Prefer a cached albeit stale response to reduce download time.
// We wouldn't want to load/parse a newer version of the source (even if one existed).
const FETCH_OPTIONS = {cache: 'force-cache'};
const MAX_SOURCE_LENGTH = 100_000_000;
export type HookSourceAndMetadata = {
// Generated by react-debug-tools.
hookSource: HookSource,
// Compiled code (React components or custom hooks) containing primitive hook calls.
runtimeSourceCode: string | null,
// Same as hookSource.fileName but guaranteed to be non-null.
runtimeSourceURL: string,
// Raw source map JSON.
// Either decoded from an inline source map or loaded from an externa source map file.
// Sources without source maps won't have this.
sourceMapJSON: MixedSourceMap | null,
// External URL of source map.
// Sources without source maps (or with inline source maps) won't have this.
sourceMapURL: string | null,
};
export type LocationKeyToHookSourceAndMetadata = Map<
string,
HookSourceAndMetadata,
>;
export type HooksList = Array<HooksNode>;
export async function loadSourceAndMetadata(
hooksList: HooksList,
fetchFileWithCaching: FetchFileWithCaching | null,
): Promise<LocationKeyToHookSourceAndMetadata> {
return withAsyncPerfMeasurements('loadSourceAndMetadata()', async () => {
const locationKeyToHookSourceAndMetadata = withSyncPerfMeasurements(
'initializeHookSourceAndMetadata',
() => initializeHookSourceAndMetadata(hooksList),
);
await withAsyncPerfMeasurements('loadSourceFiles()', () =>
loadSourceFiles(locationKeyToHookSourceAndMetadata, fetchFileWithCaching),
);
await withAsyncPerfMeasurements('extractAndLoadSourceMapJSON()', () =>
extractAndLoadSourceMapJSON(locationKeyToHookSourceAndMetadata),
);
// At this point, we've loaded JS source (text) and source map (JSON).
// The remaining works (parsing these) is CPU intensive and should be done in a worker.
return locationKeyToHookSourceAndMetadata;
});
}
function decodeBase64String(encoded: string): Object {
if (typeof atob === 'function') {
return atob(encoded);
} else if (
typeof Buffer !== 'undefined' &&
Buffer !== null &&
typeof Buffer.from === 'function'
) {
return Buffer.from(encoded, 'base64');
} else {
throw Error('Cannot decode base64 string');
}
}
function extractAndLoadSourceMapJSON(
locationKeyToHookSourceAndMetadata: LocationKeyToHookSourceAndMetadata,
): Promise<*> {
// Deduplicate fetches, since there can be multiple location keys per source map.
const dedupedFetchPromises = new Map();
if (__DEBUG__) {
console.log(
'extractAndLoadSourceMapJSON() load',
locationKeyToHookSourceAndMetadata.size,
'source maps',
);
}
const setterPromises = [];
locationKeyToHookSourceAndMetadata.forEach(hookSourceAndMetadata => {
const sourceMapRegex = / ?sourceMappingURL=([^\s'"]+)/gm;
const runtimeSourceCode = ((hookSourceAndMetadata.runtimeSourceCode: any): string);
// TODO (named hooks) Search for our custom metadata first.
// If it's found, we should use it rather than source maps.
// TODO (named hooks) If this RegExp search is slow, we could try breaking it up
// first using an indexOf(' sourceMappingURL=') to find the start of the comment
// (probably at the end of the file) and then running the RegExp on the remaining substring.
let sourceMappingURLMatch = withSyncPerfMeasurements(
'sourceMapRegex.exec(runtimeSourceCode)',
() => sourceMapRegex.exec(runtimeSourceCode),
);
if (sourceMappingURLMatch == null) {
if (__DEBUG__) {
console.log('extractAndLoadSourceMapJSON() No source map found');
}
// Maybe file has not been transformed; we'll try to parse it as-is in parseSourceAST().
} else {
const externalSourceMapURLs = [];
while (sourceMappingURLMatch != null) {
const {runtimeSourceURL} = hookSourceAndMetadata;
const sourceMappingURL = sourceMappingURLMatch[1];
const hasInlineSourceMap = sourceMappingURL.indexOf('base64,') >= 0;
if (hasInlineSourceMap) {
try {
// TODO (named hooks) deduplicate parsing in this branch (similar to fetching in the other branch)
// since there can be multiple location keys per source map.
// Web apps like Code Sandbox embed multiple inline source maps.
// In this case, we need to loop through and find the right one.
// We may also need to trim any part of this string that isn't based64 encoded data.
const trimmed = ((sourceMappingURL.match(
/base64,([a-zA-Z0-9+\/=]+)/,
): any): Array<string>)[1];
const decoded = withSyncPerfMeasurements(
'decodeBase64String()',
() => decodeBase64String(trimmed),
);
const sourceMapJSON = withSyncPerfMeasurements(
'JSON.parse(decoded)',
() => JSON.parse(decoded),
);
if (__DEBUG__) {
console.groupCollapsed(
'extractAndLoadSourceMapJSON() Inline source map',
);
console.log(sourceMapJSON);
console.groupEnd();
}
// Hook source might be a URL like "https://4syus.csb.app/src/App.js"
// Parsed source map might be a partial path like "src/App.js"
if (sourceMapIncludesSource(sourceMapJSON, runtimeSourceURL)) {
hookSourceAndMetadata.sourceMapJSON = sourceMapJSON;
// OPTIMIZATION If we've located a source map for this source,
// we'll use it to retrieve the original source (to extract hook names).
// We only fall back to parsing the full source code is when there's no source map.
// The source is (potentially) very large,
// So we can avoid the overhead of serializing it unnecessarily.
hookSourceAndMetadata.runtimeSourceCode = null;
break;
}
} catch (error) {
// We've likely encountered a string in the source code that looks like a source map but isn't.
// Maybe the source code contains a "sourceMappingURL" comment or soething similar.
// In either case, let's skip this and keep looking.
}
} else {
externalSourceMapURLs.push(sourceMappingURL);
}
// If the first source map we found wasn't a match, check for more.
sourceMappingURLMatch = withSyncPerfMeasurements(
'sourceMapRegex.exec(runtimeSourceCode)',
() => sourceMapRegex.exec(runtimeSourceCode),
);
}
if (hookSourceAndMetadata.sourceMapJSON === null) {
externalSourceMapURLs.forEach((sourceMappingURL, index) => {
if (index !== externalSourceMapURLs.length - 1) {
// Files with external source maps should only have a single source map.
// More than one result might indicate an edge case,
// like a string in the source code that matched our "sourceMappingURL" regex.
// We should just skip over cases like this.
console.warn(
`More than one external source map detected in the source file; skipping "${sourceMappingURL}"`,
);
return;
}
const {runtimeSourceURL} = hookSourceAndMetadata;
let url = sourceMappingURL;
if (!url.startsWith('http') && !url.startsWith('/')) {
// Resolve paths relative to the location of the file name
const lastSlashIdx = runtimeSourceURL.lastIndexOf('/');
if (lastSlashIdx !== -1) {
const baseURL = runtimeSourceURL.slice(
0,
runtimeSourceURL.lastIndexOf('/'),
);
url = `${baseURL}/${url}`;
}
}
hookSourceAndMetadata.sourceMapURL = url;
const fetchPromise =
dedupedFetchPromises.get(url) ||
fetchFile(url).then(
sourceMapContents => {
const sourceMapJSON = withSyncPerfMeasurements(
'JSON.parse(sourceMapContents)',
() => JSON.parse(sourceMapContents),
);
return sourceMapJSON;
},
// In this case, we fall back to the assumption that the source has no source map.
// This might indicate an (unlikely) edge case that had no source map,
// but contained the string "sourceMappingURL".
error => null,
);
if (__DEBUG__) {
if (!dedupedFetchPromises.has(url)) {
console.log(
`extractAndLoadSourceMapJSON() External source map "${url}"`,
);
}
}
dedupedFetchPromises.set(url, fetchPromise);
setterPromises.push(
fetchPromise.then(sourceMapJSON => {
if (sourceMapJSON !== null) {
hookSourceAndMetadata.sourceMapJSON = sourceMapJSON;
// OPTIMIZATION If we've located a source map for this source,
// we'll use it to retrieve the original source (to extract hook names).
// We only fall back to parsing the full source code is when there's no source map.
// The source is (potentially) very large,
// So we can avoid the overhead of serializing it unnecessarily.
hookSourceAndMetadata.runtimeSourceCode = null;
}
}),
);
});
}
}
});
return Promise.all(setterPromises);
}
function fetchFile(
url: string,
markName?: string = 'fetchFile',
): Promise<string> {
return withCallbackPerfMeasurements(`${markName}("${url}")`, done => {
return new Promise((resolve, reject) => {
fetch(url, FETCH_OPTIONS).then(
response => {
if (response.ok) {
response
.text()
.then(text => {
done();
resolve(text);
})
.catch(error => {
if (__DEBUG__) {
console.log(
`${markName}() Could not read text for url "${url}"`,
);
}
done();
reject(null);
});
} else {
if (__DEBUG__) {
console.log(`${markName}() Got bad response for url "${url}"`);
}
done();
reject(null);
}
},
error => {
if (__DEBUG__) {
console.log(`${markName}() Could not fetch file: ${error.message}`);
}
done();
reject(null);
},
);
});
});
}
export function hasNamedHooks(hooksTree: HooksTree): boolean {
for (let i = 0; i < hooksTree.length; i++) {
const hook = hooksTree[i];
if (!isUnnamedBuiltInHook(hook)) {
return true;
}
if (hook.subHooks.length > 0) {
if (hasNamedHooks(hook.subHooks)) {
return true;
}
}
}
return false;
}
export function flattenHooksList(hooksTree: HooksTree): HooksList {
const hooksList: HooksList = [];
withSyncPerfMeasurements('flattenHooksList()', () => {
flattenHooksListImpl(hooksTree, hooksList);
});
if (__DEBUG__) {
console.log('flattenHooksList() hooksList:', hooksList);
}
return hooksList;
}
function flattenHooksListImpl(
hooksTree: HooksTree,
hooksList: Array<HooksNode>,
): void {
for (let i = 0; i < hooksTree.length; i++) {
const hook = hooksTree[i];
if (isUnnamedBuiltInHook(hook)) {
// No need to load source code or do any parsing for unnamed hooks.
if (__DEBUG__) {
console.log('flattenHooksListImpl() Skipping unnamed hook', hook);
}
continue;
}
hooksList.push(hook);
if (hook.subHooks.length > 0) {
flattenHooksListImpl(hook.subHooks, hooksList);
}
}
}
function initializeHookSourceAndMetadata(
hooksList: Array<HooksNode>,
): LocationKeyToHookSourceAndMetadata {
// Create map of unique source locations (file names plus line and column numbers) to metadata about hooks.
const locationKeyToHookSourceAndMetadata: LocationKeyToHookSourceAndMetadata = new Map();
for (let i = 0; i < hooksList.length; i++) {
const hook = hooksList[i];
const hookSource = hook.hookSource;
if (hookSource == null) {
// Older versions of react-debug-tools don't include this information.
// In this case, we can't continue.
throw Error('Hook source code location not found.');
}
const locationKey = getHookSourceLocationKey(hookSource);
if (!locationKeyToHookSourceAndMetadata.has(locationKey)) {
// Can't be null because getHookSourceLocationKey() would have thrown
const runtimeSourceURL = ((hookSource.fileName: any): string);
const hookSourceAndMetadata: HookSourceAndMetadata = {
hookSource,
runtimeSourceCode: null,
runtimeSourceURL,
sourceMapJSON: null,
sourceMapURL: null,
};
locationKeyToHookSourceAndMetadata.set(
locationKey,
hookSourceAndMetadata,
);
}
}
return locationKeyToHookSourceAndMetadata;
}
// Determines whether incoming hook is a primitive hook that gets assigned to variables.
function isUnnamedBuiltInHook(hook: HooksNode) {
return ['Effect', 'ImperativeHandle', 'LayoutEffect', 'DebugValue'].includes(
hook.name,
);
}
function loadSourceFiles(
locationKeyToHookSourceAndMetadata: LocationKeyToHookSourceAndMetadata,
fetchFileWithCaching: FetchFileWithCaching | null,
): Promise<*> {
// Deduplicate fetches, since there can be multiple location keys per file.
const dedupedFetchPromises = new Map();
const setterPromises = [];
locationKeyToHookSourceAndMetadata.forEach(hookSourceAndMetadata => {
const {runtimeSourceURL} = hookSourceAndMetadata;
let fetchFileFunction = fetchFile;
if (fetchFileWithCaching != null) {
// If a helper function has been injected to fetch with caching,
// use it to fetch the (already loaded) source file.
fetchFileFunction = url => {
return withAsyncPerfMeasurements(
`fetchFileWithCaching("${url}")`,
() => {
return ((fetchFileWithCaching: any): FetchFileWithCaching)(url);
},
);
};
}
const fetchPromise =
dedupedFetchPromises.get(runtimeSourceURL) ||
fetchFileFunction(runtimeSourceURL).then(runtimeSourceCode => {
// TODO (named hooks) Re-think this; the main case where it matters is when there's no source-maps,
// because then we need to parse the full source file as an AST.
if (runtimeSourceCode.length > MAX_SOURCE_LENGTH) {
throw Error('Source code too large to parse');
}
if (__DEBUG__) {
console.groupCollapsed(
`loadSourceFiles() runtimeSourceURL "${runtimeSourceURL}"`,
);
console.log(runtimeSourceCode);
console.groupEnd();
}
return runtimeSourceCode;
});
dedupedFetchPromises.set(runtimeSourceURL, fetchPromise);
setterPromises.push(
fetchPromise.then(runtimeSourceCode => {
hookSourceAndMetadata.runtimeSourceCode = runtimeSourceCode;
}),
);
});
return Promise.all(setterPromises);
}