From 1df1fd1047695c4d144de4b2b4bd4a69fc7d7440 Mon Sep 17 00:00:00 2001 From: patak Date: Sat, 2 Dec 2023 16:17:55 +0100 Subject: [PATCH] perf: skip computing sourceRoot in injectSourcesContent (#15207) --- packages/vite/src/node/server/sourcemap.ts | 64 ++++++++++++++-------- 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/packages/vite/src/node/server/sourcemap.ts b/packages/vite/src/node/server/sourcemap.ts index c8f2c8d88fdacd..eafde8c25b67d1 100644 --- a/packages/vite/src/node/server/sourcemap.ts +++ b/packages/vite/src/node/server/sourcemap.ts @@ -19,11 +19,7 @@ interface SourceMapLike { sourceRoot?: string } -export async function injectSourcesContent( - map: SourceMapLike, - file: string, - logger: Logger, -): Promise { +async function computeSourceRoute(map: SourceMapLike, file: string) { let sourceRoot: string | undefined try { // The source root is undefined for virtual modules and permission errors. @@ -31,28 +27,48 @@ export async function injectSourcesContent( path.resolve(path.dirname(file), map.sourceRoot || ''), ) } catch {} + return sourceRoot +} + +export async function injectSourcesContent( + map: SourceMapLike, + file: string, + logger: Logger, +): Promise { + let sourceRootPromise: Promise const missingSources: string[] = [] const sourcesContent = map.sourcesContent || [] - await Promise.all( - map.sources.map(async (sourcePath, index) => { - let content = null - if (sourcePath && !virtualSourceRE.test(sourcePath)) { - sourcePath = decodeURI(sourcePath) - if (sourceRoot) { - sourcePath = path.resolve(sourceRoot, sourcePath) - } - // inject content from source file when sourcesContent is null - content = - sourcesContent[index] ?? - (await fsp.readFile(sourcePath, 'utf-8').catch(() => { - missingSources.push(sourcePath) - return null - })) - } - sourcesContent[index] = content - }), - ) + const sourcesContentPromises: Promise[] = [] + for (let index = 0; index < map.sources.length; index++) { + const sourcePath = map.sources[index] + if ( + !sourcesContent[index] && + sourcePath && + !virtualSourceRE.test(sourcePath) + ) { + sourcesContentPromises.push( + (async () => { + // inject content from source file when sourcesContent is null + sourceRootPromise ??= computeSourceRoute(map, file) + const sourceRoot = await sourceRootPromise + let resolvedSourcePath = decodeURI(sourcePath) + if (sourceRoot) { + resolvedSourcePath = path.resolve(sourceRoot, resolvedSourcePath) + } + + sourcesContent[index] = await fsp + .readFile(resolvedSourcePath, 'utf-8') + .catch(() => { + missingSources.push(resolvedSourcePath) + return null + }) + })(), + ) + } + } + + await Promise.all(sourcesContentPromises) map.sourcesContent = sourcesContent