|
| 1 | +// Copyright 2025 The Chromium Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | + |
| 5 | +import type * as SDK from '../../../core/sdk/sdk.js'; |
| 6 | +import type * as Handlers from '../handlers/handlers.js'; |
| 7 | + |
| 8 | +const RELATIVE_SIZE_THRESHOLD = 0.1; |
| 9 | +const ABSOLUTE_SIZE_THRESHOLD_BYTES = 1024 * 0.5; |
| 10 | + |
| 11 | +type GeneratedFileSizes = { |
| 12 | + errorMessage: string, |
| 13 | +}|{files: Record<string, number>, unmappedBytes: number, totalBytes: number}; |
| 14 | + |
| 15 | +/** |
| 16 | + * Using a script's contents and source map, attribute every generated byte to an authored source file. |
| 17 | + */ |
| 18 | +export function computeGeneratedFileSizes(script: Handlers.ModelHandlers.Scripts.Script): GeneratedFileSizes { |
| 19 | + if (!script.sourceMap) { |
| 20 | + throw new Error('expected source map'); |
| 21 | + } |
| 22 | + |
| 23 | + const map = script.sourceMap; |
| 24 | + const content = script.content ?? ''; |
| 25 | + const contentLength = content.length; |
| 26 | + const lines = content.split('\n'); |
| 27 | + const files: Record<string, number> = {}; |
| 28 | + const totalBytes = contentLength; |
| 29 | + let unmappedBytes = totalBytes; |
| 30 | + |
| 31 | + const lastGeneratedColumnMap = computeLastGeneratedColumnMap(script.sourceMap); |
| 32 | + |
| 33 | + for (const mapping of map.mappings()) { |
| 34 | + const source = mapping.sourceURL; |
| 35 | + const lineNum = mapping.lineNumber; |
| 36 | + const colNum = mapping.columnNumber; |
| 37 | + const lastColNum = lastGeneratedColumnMap.get(mapping); |
| 38 | + |
| 39 | + // Webpack sometimes emits null mappings. |
| 40 | + // https://github.com/mozilla/source-map/pull/303 |
| 41 | + if (!source) { |
| 42 | + continue; |
| 43 | + } |
| 44 | + |
| 45 | + // Lines and columns are zero-based indices. Visually, lines are shown as a 1-based index. |
| 46 | + |
| 47 | + const line = lines[lineNum]; |
| 48 | + if (line === null || line === undefined) { |
| 49 | + const errorMessage = `${map.url()} mapping for line out of bounds: ${lineNum + 1}`; |
| 50 | + return {errorMessage}; |
| 51 | + } |
| 52 | + |
| 53 | + if (colNum > line.length) { |
| 54 | + const errorMessage = `${map.url()} mapping for column out of bounds: ${lineNum + 1}:${colNum}`; |
| 55 | + return {errorMessage}; |
| 56 | + } |
| 57 | + |
| 58 | + let mappingLength = 0; |
| 59 | + if (lastColNum !== undefined) { |
| 60 | + if (lastColNum > line.length) { |
| 61 | + const errorMessage = `${map.url()} mapping for last column out of bounds: ${lineNum + 1}:${lastColNum}`; |
| 62 | + return {errorMessage}; |
| 63 | + } |
| 64 | + mappingLength = lastColNum - colNum; |
| 65 | + } else { |
| 66 | + // Add +1 to account for the newline. |
| 67 | + mappingLength = line.length - colNum + 1; |
| 68 | + } |
| 69 | + files[source] = (files[source] || 0) + mappingLength; |
| 70 | + unmappedBytes -= mappingLength; |
| 71 | + } |
| 72 | + |
| 73 | + return { |
| 74 | + files, |
| 75 | + unmappedBytes, |
| 76 | + totalBytes, |
| 77 | + }; |
| 78 | +} |
| 79 | + |
| 80 | +interface SourceData { |
| 81 | + source: string; |
| 82 | + resourceSize: number; |
| 83 | +} |
| 84 | + |
| 85 | +export function normalizeSource(source: string): string { |
| 86 | + // Trim trailing question mark - b/c webpack. |
| 87 | + source = source.replace(/\?$/, ''); |
| 88 | + |
| 89 | + // Normalize paths for dependencies by only keeping everything after the last `node_modules`. |
| 90 | + const lastNodeModulesIndex = source.lastIndexOf('node_modules'); |
| 91 | + if (lastNodeModulesIndex !== -1) { |
| 92 | + source = source.substring(lastNodeModulesIndex); |
| 93 | + } |
| 94 | + |
| 95 | + return source; |
| 96 | +} |
| 97 | + |
| 98 | +function shouldIgnoreSource(source: string): boolean { |
| 99 | + // Ignore bundle overhead. |
| 100 | + if (source.includes('webpack/bootstrap')) { |
| 101 | + return true; |
| 102 | + } |
| 103 | + if (source.includes('(webpack)/buildin')) { |
| 104 | + return true; |
| 105 | + } |
| 106 | + |
| 107 | + // Ignore webpack module shims, i.e. aliases of the form `module.exports = window.jQuery` |
| 108 | + if (source.includes('external ')) { |
| 109 | + return true; |
| 110 | + } |
| 111 | + |
| 112 | + return false; |
| 113 | +} |
| 114 | + |
| 115 | +/** |
| 116 | + * The key is a source map `sources` entry, but normalized via `normalizeSource`. |
| 117 | + * |
| 118 | + * The value is an array with an entry for every script that has a source map which |
| 119 | + * denotes that this source was used, along with the estimated resource size it takes |
| 120 | + * up in the script. |
| 121 | + */ |
| 122 | +export type ScriptDuplication = Map<string, Array<{scriptId: string, resourceSize: number}>>; |
| 123 | + |
| 124 | +/** |
| 125 | + * Sorts each array within @see ScriptDuplication by resource size, and drops information |
| 126 | + * on sources that are too small. |
| 127 | + */ |
| 128 | +export function normalizeDuplication(duplication: ScriptDuplication): void { |
| 129 | + for (const [key, originalSourceData] of duplication.entries()) { |
| 130 | + let sourceData = originalSourceData; |
| 131 | + |
| 132 | + // Sort by resource size. |
| 133 | + sourceData.sort((a, b) => b.resourceSize - a.resourceSize); |
| 134 | + |
| 135 | + // Remove modules smaller than a % size of largest. |
| 136 | + if (sourceData.length > 1) { |
| 137 | + const largestResourceSize = sourceData[0].resourceSize; |
| 138 | + sourceData = sourceData.filter(data => { |
| 139 | + const percentSize = data.resourceSize / largestResourceSize; |
| 140 | + return percentSize >= RELATIVE_SIZE_THRESHOLD; |
| 141 | + }); |
| 142 | + } |
| 143 | + |
| 144 | + // Remove modules smaller than an absolute threshold. |
| 145 | + sourceData = sourceData.filter(data => data.resourceSize >= ABSOLUTE_SIZE_THRESHOLD_BYTES); |
| 146 | + |
| 147 | + // Delete any that now don't have multiple source data entries. |
| 148 | + if (sourceData.length > 1) { |
| 149 | + duplication.set(key, sourceData); |
| 150 | + } else { |
| 151 | + duplication.delete(key); |
| 152 | + } |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +function computeLastGeneratedColumnMap(map: SDK.SourceMap.SourceMap): Map<SDK.SourceMap.SourceMapEntry, number> { |
| 157 | + const result = new Map<SDK.SourceMap.SourceMapEntry, number>(); |
| 158 | + |
| 159 | + const mappings = map.mappings(); |
| 160 | + for (let i = 0; i < mappings.length - 1; i++) { |
| 161 | + const mapping = mappings[i]; |
| 162 | + const nextMapping = mappings[i + 1]; |
| 163 | + if (mapping.lineNumber === nextMapping.lineNumber) { |
| 164 | + result.set(mapping, nextMapping.columnNumber); |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + // Now, all but the last mapping on each line will have 'lastColumnNumber' set to a number. |
| 169 | + return result; |
| 170 | +} |
| 171 | + |
| 172 | +/** |
| 173 | + * Returns a @see ScriptDuplication for the given collection of script contents + source maps. |
| 174 | + */ |
| 175 | +export function computeScriptDuplication(scriptsData: Handlers.ModelHandlers.Scripts.ScriptsData): ScriptDuplication { |
| 176 | + const sizesMap = new Map<Handlers.ModelHandlers.Scripts.Script, GeneratedFileSizes>(); |
| 177 | + for (const script of scriptsData.scripts.values()) { |
| 178 | + if (script.content && script.sourceMap) { |
| 179 | + sizesMap.set(script, computeGeneratedFileSizes(script)); |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + const sourceDatasMap = new Map<Handlers.ModelHandlers.Scripts.Script, SourceData[]>(); |
| 184 | + |
| 185 | + // Determine size of each `sources` entry. |
| 186 | + for (const [script, sizes] of sizesMap) { |
| 187 | + if (!script.sourceMap) { |
| 188 | + continue; |
| 189 | + } |
| 190 | + |
| 191 | + if ('errorMessage' in sizes) { |
| 192 | + console.error(sizes.errorMessage); |
| 193 | + continue; |
| 194 | + } |
| 195 | + |
| 196 | + const sourceDataArray: SourceData[] = []; |
| 197 | + sourceDatasMap.set(script, sourceDataArray); |
| 198 | + |
| 199 | + const sources = script.sourceMap.sourceURLs(); |
| 200 | + for (let i = 0; i < sources.length; i++) { |
| 201 | + if (shouldIgnoreSource(sources[i])) { |
| 202 | + continue; |
| 203 | + } |
| 204 | + |
| 205 | + const sourceSize = sizes.files[sources[i]]; |
| 206 | + sourceDataArray.push({ |
| 207 | + source: normalizeSource(sources[i]), |
| 208 | + resourceSize: sourceSize, |
| 209 | + }); |
| 210 | + } |
| 211 | + } |
| 212 | + |
| 213 | + const moduleNameToSourceData: ScriptDuplication = new Map(); |
| 214 | + for (const [script, sourceDataArray] of sourceDatasMap) { |
| 215 | + for (const sourceData of sourceDataArray) { |
| 216 | + let data = moduleNameToSourceData.get(sourceData.source); |
| 217 | + if (!data) { |
| 218 | + data = []; |
| 219 | + moduleNameToSourceData.set(sourceData.source, data); |
| 220 | + } |
| 221 | + data.push({ |
| 222 | + scriptId: script.scriptId, |
| 223 | + resourceSize: sourceData.resourceSize, |
| 224 | + }); |
| 225 | + } |
| 226 | + } |
| 227 | + |
| 228 | + normalizeDuplication(moduleNameToSourceData); |
| 229 | + return moduleNameToSourceData; |
| 230 | +} |
0 commit comments