MCPcopy Create free account
hub / github.com/btd/rollup-plugin-visualizer / getBytesPerFileUsingSourceMap

Function getBytesPerFileUsingSourceMap

plugin/sourcemap.ts:16–77  ·  view source on GitHub ↗
(
  bundleId: string,
  code: string,
  map: TraceMap,
  dir: string,
)

Source from the content-addressed store, hash-verified

14}
15
16const getBytesPerFileUsingSourceMap = (
17 bundleId: string,
18 code: string,
19 map: TraceMap,
20 dir: string,
21) => {
22 const modules: Record<string, SourceMapModuleRenderInfo> = {};
23 const modulesBySource = new Map<string, SourceMapModuleRenderInfo>();
24 const bundleDir = path.dirname(path.join(dir, bundleId));
25
26 let line = 1;
27 let lineStart = 0;
28 let lineEnd = 0;
29 let previous: GeneratedMapping | undefined;
30
31 const countSpan = (next?: GeneratedMapping): void => {
32 if (previous?.source == null) return;
33 // Columns and string offsets both use UTF-16; only the size uses UTF-8.
34 const start = Math.min(lineStart + previous.generatedColumn, lineEnd);
35 const end =
36 next?.generatedLine === previous.generatedLine
37 ? Math.min(lineStart + next.generatedColumn, lineEnd)
38 : lineEnd;
39 if (end <= start) return;
40
41 let module = modulesBySource.get(previous.source);
42 if (module == null) {
43 // Preserve the bundler's source names: literal percent escapes are part
44 // of filenames and must remain distinct from spaces or path separators.
45 const id = path.resolve(bundleDir, previous.source);
46 module = modules[id] ??= { id, renderedLength: 0 };
47 modulesBySource.set(previous.source, module);
48 }
49 module.renderedLength += Buffer.byteLength(code.slice(start, end));
50 };
51
52 // Rollup and Rolldown emit flat maps. Count spans in generated order without
53 // materializing characters or retaining the generated code for each module.
54 eachMapping(map, (mapping) => {
55 // Original positions within the same source do not affect module sizes.
56 if (previous?.generatedLine === mapping.generatedLine && previous.source === mapping.source) {
57 return;
58 }
59 countSpan(mapping);
60
61 while (line < mapping.generatedLine && lineStart < code.length) {
62 const newline = code.indexOf("\n", lineStart);
63 lineStart = newline === -1 ? code.length : newline + 1;
64 line++;
65 }
66 if (previous?.generatedLine !== mapping.generatedLine) {
67 const newline = code.indexOf("\n", lineStart);
68 // Preserve the existing policy: include a mapped line's terminating LF,
69 // but do not extend its final mapping into an unmapped following line.
70 lineEnd = newline === -1 ? code.length : newline + 1;
71 }
72 previous = mapping;
73 });

Callers 1

getSourcemapModulesFunction · 0.85

Calls 1

countSpanFunction · 0.85

Tested by

no test coverage detected