Skip to content

Commit cfa3e20

Browse files
committed
fix(webpack): es module source mapping improvements
1 parent 2325e33 commit cfa3e20

File tree

3 files changed

+149
-40
lines changed

3 files changed

+149
-40
lines changed

packages/core/inspector_modules.ts

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ function getConsumer(mapPath: string, sourceMap: any) {
2323
c = new SourceMapConsumer(sourceMap);
2424
consumerCache.set(mapPath, c);
2525
} catch (error) {
26-
console.error(`Failed to create SourceMapConsumer for ${mapPath}:`, error);
26+
// Keep quiet in production-like console; failures just fall back to original stack
27+
console.debug && console.debug(`SourceMapConsumer failed for ${mapPath}:`, error);
2728
return null;
2829
}
2930
}
@@ -67,7 +68,7 @@ function loadAndExtractMap(mapPath: string) {
6768
mapText = binary;
6869
}
6970
} catch (error) {
70-
console.error(`Failed to load source map ${mapPath}:`, error);
71+
console.debug && console.debug(`Failed to load source map ${mapPath}:`, error);
7172
return null;
7273
}
7374
} else {
@@ -108,26 +109,44 @@ function remapFrame(file: string, line: number, column: number) {
108109
try {
109110
return consumer.originalPositionFor({ line, column });
110111
} catch (error) {
111-
console.error(`Failed to get original position for ${file}:${line}:${column}:`, error);
112+
console.debug && console.debug(`Remap failed for ${file}:${line}:${column}:`, error);
112113
return { source: null, line: 0, column: 0 };
113114
}
114115
}
115116

116117
function remapStack(raw: string): string {
117118
const lines = raw.split('\n');
118119
const out = lines.map((line) => {
119-
const m = /\((.+):(\d+):(\d+)\)/.exec(line);
120-
if (!m) return line;
120+
// 1) Parenthesized frame: at fn (file:...:L:C)
121+
let m = /\((.+):(\d+):(\d+)\)/.exec(line);
122+
if (m) {
123+
try {
124+
const [_, file, l, c] = m;
125+
const orig = remapFrame(file, +l, +c);
126+
if (!orig.source) return line;
127+
return line.replace(/\(.+\)/, `(${orig.source}:${orig.line}:${orig.column})`);
128+
} catch (error) {
129+
console.debug && console.debug('Remap failed for frame:', line, error);
130+
return line;
131+
}
132+
}
121133

122-
try {
123-
const [_, file, l, c] = m;
124-
const orig = remapFrame(file, +l, +c);
125-
if (!orig.source) return line;
126-
return line.replace(/\(.+\)/, `(${orig.source}:${orig.line}:${orig.column})`);
127-
} catch (error) {
128-
console.error('Failed to remap stack frame:', line, error);
129-
return line; // return original line if remapping fails
134+
// 2) Bare frame: at file:///app/vendor.js:L:C (no parentheses)
135+
const bare = /(\s+at\s+)([^\s()]+):(\d+):(\d+)/.exec(line);
136+
if (bare) {
137+
try {
138+
const [, prefix, file, l, c] = bare;
139+
const orig = remapFrame(file, +l, +c);
140+
if (!orig.source) return line;
141+
const replacement = `${prefix}${orig.source}:${orig.line}:${orig.column}`;
142+
return line.replace(bare[0], replacement);
143+
} catch (error) {
144+
console.debug && console.debug('Remap failed for bare frame:', line, error);
145+
return line;
146+
}
130147
}
148+
149+
return line;
131150
});
132151
return out.join('\n');
133152
}
@@ -141,7 +160,7 @@ function remapStack(raw: string): string {
141160
try {
142161
return remapStack(rawStack);
143162
} catch (error) {
144-
console.error('Failed to remap stack trace, returning original:', error);
163+
console.debug && console.debug('Remap failed, returning original:', error);
145164
return rawStack; // fallback to original stack trace
146165
}
147166
};

packages/webpack5/src/configuration/base.ts

Lines changed: 4 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { applyDotEnvPlugin } from '../helpers/dotEnv';
2424
import { env as _env, IWebpackEnv } from '../index';
2525
import { getValue } from '../helpers/config';
2626
import { getIPS } from '../helpers/host';
27+
import FixSourceMapUrlPlugin from '../plugins/FixSourceMapUrlPlugin';
2728
import {
2829
getAvailablePlatforms,
2930
getAbsoluteDistPath,
@@ -178,32 +179,9 @@ export default function (config: Config, env: IWebpackEnv = _env): Config {
178179

179180
// For ESM builds, fix the sourceMappingURL to use correct paths
180181
if (!env.commonjs && sourceMapType && sourceMapType !== 'hidden-source-map') {
181-
class FixSourceMapUrlPlugin {
182-
apply(compiler) {
183-
compiler.hooks.emit.tap('FixSourceMapUrlPlugin', (compilation) => {
184-
const leadingCharacter = process.platform === 'win32' ? '/' : '';
185-
Object.keys(compilation.assets).forEach((filename) => {
186-
if (filename.endsWith('.mjs') || filename.endsWith('.js')) {
187-
const asset = compilation.assets[filename];
188-
let source = asset.source();
189-
190-
// Replace sourceMappingURL to use file:// protocol pointing to actual location
191-
source = source.replace(
192-
/\/\/# sourceMappingURL=(.+\.map)/g,
193-
`//# sourceMappingURL=file://${leadingCharacter}${outputPath}/$1`,
194-
);
195-
196-
compilation.assets[filename] = {
197-
source: () => source,
198-
size: () => source.length,
199-
};
200-
}
201-
});
202-
});
203-
}
204-
}
205-
206-
config.plugin('FixSourceMapUrlPlugin').use(FixSourceMapUrlPlugin);
182+
config
183+
.plugin('FixSourceMapUrlPlugin')
184+
.use(FixSourceMapUrlPlugin as any, [{ outputPath }]);
207185
}
208186

209187
// when using hidden-source-map, output source maps to the `platforms/{platformName}-sourceMaps` folder
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import type { Compiler } from 'webpack';
2+
import { sources } from 'webpack';
3+
4+
export interface FixSourceMapUrlPluginOptions {
5+
outputPath: string;
6+
}
7+
8+
/**
9+
* Ensures sourceMappingURL points to the actual file:// location on device/emulator.
10+
* Handles Webpack 5 asset sources (string/Buffer/Source objects).
11+
*/
12+
export default class FixSourceMapUrlPlugin {
13+
constructor(private readonly options: FixSourceMapUrlPluginOptions) {}
14+
15+
apply(compiler: Compiler) {
16+
const wp: any = (compiler as any).webpack;
17+
const hasProcessAssets =
18+
!!wp?.Compilation?.PROCESS_ASSETS_STAGE_DEV_TOOLING &&
19+
!!(compiler as any).hooks?.thisCompilation;
20+
21+
const leadingCharacter = process.platform === 'win32' ? '/' : '';
22+
23+
const toStringContent = (content: any): string => {
24+
if (typeof content === 'string') return content;
25+
if (Buffer.isBuffer(content)) return content.toString('utf-8');
26+
if (content && typeof content.source === 'function') {
27+
const inner = content.source();
28+
if (typeof inner === 'string') return inner;
29+
if (Buffer.isBuffer(inner)) return inner.toString('utf-8');
30+
try {
31+
return String(inner);
32+
} catch {
33+
return '';
34+
}
35+
}
36+
try {
37+
return String(content);
38+
} catch {
39+
return '';
40+
}
41+
};
42+
43+
const processFile = (filename: string, compilation: any) => {
44+
if (!(filename.endsWith('.mjs') || filename.endsWith('.js'))) return;
45+
46+
// Support both legacy compilation.assets and v5 Asset API
47+
let rawSource: any;
48+
if (typeof (compilation as any).getAsset === 'function') {
49+
const assetObj = (compilation as any).getAsset(filename);
50+
if (assetObj && assetObj.source) {
51+
rawSource = (assetObj.source as any).source
52+
? (assetObj.source as any).source()
53+
: (assetObj.source as any)();
54+
}
55+
}
56+
if (
57+
rawSource === undefined &&
58+
(compilation as any).assets &&
59+
(compilation as any).assets[filename]
60+
) {
61+
const asset = (compilation as any).assets[filename];
62+
rawSource = typeof asset.source === 'function' ? asset.source() : asset;
63+
}
64+
65+
let source = toStringContent(rawSource);
66+
// Replace sourceMappingURL to use file:// protocol pointing to actual location
67+
source = source.replace(
68+
/\/\/\# sourceMappingURL=(.+\.map)/g,
69+
`//# sourceMappingURL=file://${leadingCharacter}${this.options.outputPath}/$1`,
70+
);
71+
72+
// Prefer Webpack 5 updateAsset with RawSource when available
73+
const RawSourceCtor =
74+
wp?.sources?.RawSource || (sources as any)?.RawSource;
75+
if (
76+
typeof (compilation as any).updateAsset === 'function' &&
77+
RawSourceCtor
78+
) {
79+
(compilation as any).updateAsset(filename, new RawSourceCtor(source));
80+
} else {
81+
(compilation as any).assets[filename] = {
82+
source: () => source,
83+
size: () => source.length,
84+
};
85+
}
86+
};
87+
88+
if (hasProcessAssets) {
89+
compiler.hooks.thisCompilation.tap(
90+
'FixSourceMapUrlPlugin',
91+
(compilation: any) => {
92+
const stage = wp.Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING;
93+
compilation.hooks.processAssets.tap(
94+
{ name: 'FixSourceMapUrlPlugin', stage },
95+
(assets: Record<string, any>) => {
96+
Object.keys(assets).forEach((filename) =>
97+
processFile(filename, compilation),
98+
);
99+
},
100+
);
101+
},
102+
);
103+
} else {
104+
// Fallback for older setups: use emit (may log deprecation in newer webpack)
105+
compiler.hooks.emit.tap('FixSourceMapUrlPlugin', (compilation: any) => {
106+
Object.keys((compilation as any).assets).forEach((filename) =>
107+
processFile(filename, compilation),
108+
);
109+
});
110+
}
111+
}
112+
}

0 commit comments

Comments
 (0)