Skip to content

Commit 4a36980

Browse files
authored
fix: keep source map source names as emitted in maps and stack frames (#1470)
1 parent 0523d65 commit 4a36980

12 files changed

Lines changed: 368 additions & 18 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
"@callstack/repack": patch
3+
"@callstack/repack-dev-server": patch
4+
---
5+
6+
Fix source map source names and development stack frames for files whose path
7+
URLs would encode.
8+
9+
- `babel-loader` and `babel-swc-loader` no longer set `sourceRoot`. Webpack, and
10+
Rspack whenever Babel produced the map, prepended it to the absolute source
11+
path, so project files were named `src/<dir>/<absolute path>` in development
12+
and release source maps.
13+
- The dev server now returns symbolicated file names exactly as the bundler
14+
emitted them. Before, `source-map` percent-encoded them, so a frame outside the
15+
project root came back as `[projectRoot%5E2]/...`, and a path with a space or
16+
non-ASCII character came back encoded. The encoded name broke opening the file
17+
from LogBox and reading its source when the map has no embedded content.
18+
- Development asset requests with an encoded directory name no longer 404.

‎packages/dev-server/src/plugins/symbolicate/Symbolicator.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ import { codeFrameColumns } from '@babel/code-frame';
33
import type { FastifyBaseLogger } from 'fastify';
44
import { SourceMapConsumer } from 'source-map';
55
import {
6+
decodeSourceName,
7+
escapeSourceName,
68
isGeneratedBundleFrame,
79
isSymbolicatableFrame,
8-
normalizeInvalidWebpackSourceUrls,
10+
prepareSourceMap,
911
} from '../../utils/symbolication.js';
1012
import type {
1113
CodeFrame,
@@ -101,7 +103,7 @@ export class Symbolicator {
101103
sourceMapLength: rawSourceMap.length,
102104
});
103105
const sourceMapConsumer = await new SourceMapConsumer(
104-
normalizeInvalidWebpackSourceUrls(rawSourceMap)
106+
prepareSourceMap(rawSourceMap)
105107
);
106108

107109
logger.debug({
@@ -201,7 +203,7 @@ export class Symbolicator {
201203
return {
202204
lineNumber: lookup.line ?? frame.lineNumber,
203205
column: lookup.column ?? frame.column,
204-
file: lookup.source,
206+
file: decodeSourceName(lookup.source),
205207
methodName: lookup.name || frame.methodName,
206208
collapse: false,
207209
};
@@ -233,7 +235,10 @@ export class Symbolicator {
233235

234236
try {
235237
const consumer = sourceMapConsumers.get(inputFrames[index]?.file);
236-
const embeddedSource = consumer?.sourceContentFor(frame.file, true);
238+
const embeddedSource = consumer?.sourceContentFor(
239+
escapeSourceName(frame.file),
240+
true
241+
);
237242
const source =
238243
embeddedSource ??
239244
(await this.delegate.getSource(frame.file)).toString();

‎packages/dev-server/src/plugins/symbolicate/__tests__/Symbolicator.test.ts‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { stripVTControlCharacters } from 'node:util';
12
import type { FastifyBaseLogger } from 'fastify';
23
import { beforeEach, describe, expect, it, vi } from 'vitest';
34
import { logSymbolicatedStackFrame } from '../logSymbolicatedStackFrame.js';
@@ -50,6 +51,20 @@ function createSourceMapWithoutContent(source: string) {
5051
});
5152
}
5253

54+
// Maps generated line N to the start of `sources[N - 1]`.
55+
function createSourceMapWithSources(
56+
sources: string[],
57+
sourcesContent?: string[]
58+
) {
59+
return JSON.stringify({
60+
version: 3,
61+
sources,
62+
sourcesContent,
63+
names: [],
64+
mappings: ['AAAA', ...sources.slice(1).map(() => 'ACAA')].join(';'),
65+
});
66+
}
67+
5368
function createDeferred<T>() {
5469
let resolve!: (value: T | PromiseLike<T>) => void;
5570
const promise = new Promise<T>((resolvePromise) => {
@@ -188,6 +203,87 @@ describe('Symbolicator', () => {
188203
});
189204
});
190205

206+
describe('source names that URLs encode', () => {
207+
const bundleUrl = 'http://localhost:8081/index.bundle?platform=ios';
208+
const sources = [
209+
'[projectRoot^2]/node_modules/react-native/Libraries/Core/ExceptionsManager.js',
210+
'[projectRoot]/src/screens/Home Screen.tsx',
211+
'[projectRoot]/src/Écran.tsx',
212+
'[projectRoot]/src/100%25 done.tsx',
213+
'/Users/me/My Projects/app/src/App.tsx',
214+
];
215+
const frameFor = (source: string) => ({
216+
file: bundleUrl,
217+
lineNumber: sources.indexOf(source) + 1,
218+
column: 0,
219+
methodName: 'frame',
220+
});
221+
222+
it.each(sources)('returns %s as emitted by the bundler', async (source) => {
223+
const symbolicator = new Symbolicator(
224+
createDelegate(async () =>
225+
createSourceMapWithSources(
226+
sources,
227+
sources.map((name) => `// content of ${name}`)
228+
)
229+
)
230+
);
231+
232+
const result = await symbolicator.process(logger, [frameFor(source)]);
233+
234+
expect(result.stack[0]?.file).toBe(source);
235+
expect(result.codeFrame?.fileName).toBe(source);
236+
expect(
237+
stripVTControlCharacters(result.codeFrame?.content ?? '')
238+
).toContain(`content of ${source}`);
239+
});
240+
241+
it.each(sources)(
242+
'reads %s from the compiler when the map has no content',
243+
async (source) => {
244+
const getSource = vi.fn(async () => 'const fromDisk = true;');
245+
const symbolicator = new Symbolicator(
246+
createDelegate(
247+
async () => createSourceMapWithSources(sources),
248+
getSource
249+
)
250+
);
251+
252+
const result = await symbolicator.process(logger, [frameFor(source)]);
253+
254+
expect(getSource).toHaveBeenCalledWith(source);
255+
expect(
256+
stripVTControlCharacters(result.codeFrame?.content ?? '')
257+
).toContain('const fromDisk = true;');
258+
}
259+
);
260+
261+
it('keeps remote source URLs encoded', async () => {
262+
// `fetchSourceMapFromBundle` rewrites remote source names to URLs.
263+
const remoteSource =
264+
'http://localhost:8082/__repack_source__/[projectRoot%5E2]/packages/remote/src/App.tsx';
265+
const symbolicator = new Symbolicator(
266+
createDelegate(async () =>
267+
createSourceMapWithSources([remoteSource], ['const remote = 1;'])
268+
)
269+
);
270+
271+
const result = await symbolicator.process(logger, [
272+
{
273+
file: 'http://localhost:8082/remote.chunk.bundle',
274+
lineNumber: 1,
275+
column: 0,
276+
methodName: 'App',
277+
},
278+
]);
279+
280+
expect(result.stack[0]?.file).toBe(remoteSource);
281+
expect(
282+
stripVTControlCharacters(result.codeFrame?.content ?? '')
283+
).toContain('const remote = 1;');
284+
});
285+
});
286+
191287
it('loads a source map once for repeated frames in one request', async () => {
192288
const bundleUrl = 'http://localhost:8082/repeated.chunk.bundle';
193289
const getSourceMap = vi.fn(async () =>
@@ -338,6 +434,41 @@ describe('logSymbolicatedStackFrame', () => {
338434
});
339435
});
340436

437+
it('strips the placeholder from a frame outside of the project root', async () => {
438+
const info = vi.fn();
439+
const runtimeLogger = { ...logger, info } as unknown as FastifyBaseLogger;
440+
const stack = [
441+
{
442+
file: 'http://localhost:8081/index.bundle?platform=ios',
443+
lineNumber: 1,
444+
column: 0,
445+
methodName: 'Shared',
446+
},
447+
{
448+
file: 'http://localhost:8081/index.bundle?platform=ios',
449+
lineNumber: 200,
450+
column: 30,
451+
methodName: 'renderWithHooks',
452+
},
453+
];
454+
const symbolicator = new Symbolicator(
455+
createDelegate(async () =>
456+
createSourceMapWithSources(
457+
['[projectRoot^2]/packages/shared/src/Shared.tsx'],
458+
['export const Shared = () => null;']
459+
)
460+
)
461+
);
462+
463+
const results = await symbolicator.process(runtimeLogger, stack);
464+
logSymbolicatedStackFrame(runtimeLogger, stack, results);
465+
466+
expect(info).toHaveBeenCalledWith({
467+
msg: 'Symbolicated stack frame: packages/shared/src/Shared.tsx:1:0',
468+
methodName: 'Shared',
469+
});
470+
});
471+
341472
it('does not log component-stack-only symbolication', () => {
342473
const info = vi.fn();
343474
const runtimeLogger = { info } as unknown as FastifyBaseLogger;

‎packages/dev-server/src/utils/symbolication.ts‎

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,28 @@ interface StackFrameLike {
55
file: string | null;
66
}
77

8-
export function normalizeInvalidWebpackSourceUrls(
9-
rawSourceMap: string | Buffer
10-
): string | RawSourceMap | RawIndexMap {
11-
const sourceMapText = rawSourceMap.toString();
12-
if (!sourceMapText.includes('webpack://')) {
13-
return sourceMapText;
14-
}
8+
// `source-map` normalises every source name through `new URL()`, which
9+
// percent-encodes characters such as spaces, non-ASCII letters and the caret
10+
// in `[projectRoot^N]`. Escaping `%` before the consumer reads the map makes
11+
// `decodeSourceName` an exact inverse, so a file name that contains `%` keeps
12+
// it instead of being decoded a second time.
13+
export function escapeSourceName(source: string) {
14+
return source.replaceAll('%', '%25');
15+
}
1516

16-
const sourceMap = JSON.parse(sourceMapText) as {
17+
export function decodeSourceName(source: string) {
18+
return decodeURIComponent(source);
19+
}
20+
21+
/**
22+
* Prepare a raw source map for `SourceMapConsumer`: replace webpack source
23+
* URLs that would make it reject the map and escape every source name, so
24+
* names returned by the consumer can be restored with `decodeSourceName`.
25+
*/
26+
export function prepareSourceMap(
27+
rawSourceMap: string | Buffer
28+
): RawSourceMap | RawIndexMap {
29+
const sourceMap = JSON.parse(rawSourceMap.toString()) as {
1730
sources?: unknown[];
1831
sections?: Array<{ map?: unknown }>;
1932
};
@@ -39,12 +52,12 @@ export function normalizeInvalidWebpackSourceUrls(
3952
'webpack://$1/'
4053
);
4154
if (!normalizedSource.startsWith('webpack://')) {
42-
return normalizedSource;
55+
return escapeSourceName(normalizedSource);
4356
}
4457

4558
try {
4659
new URL(normalizedSource);
47-
return normalizedSource;
60+
return escapeSourceName(normalizedSource);
4861
} catch {
4962
// Some generated Module Federation runtime modules use their source
5063
// text as a webpack URL. A single invalid URL makes source-map reject

‎packages/repack/src/commands/common/__tests__/parseUrl.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,34 @@ describe('parseUrl', () => {
8080
});
8181
});
8282

83+
it('should return the decoded path', () => {
84+
// Symbolicated stack frames are passed as file names, not URLs.
85+
expectParsed('[projectRoot^2]/node_modules/pkg/index.js', {
86+
resourcePath: '[projectRoot^2]/node_modules/pkg/index.js',
87+
platform: undefined,
88+
});
89+
expectParsed('[projectRoot]/src/Home Screen.tsx', {
90+
resourcePath: '[projectRoot]/src/Home Screen.tsx',
91+
platform: undefined,
92+
});
93+
expectParsed('[projectRoot]/src/Écran.ios.tsx', {
94+
resourcePath: '[projectRoot]/src/Écran.ios.tsx',
95+
platform: 'ios',
96+
});
97+
// Request URLs arrive percent-encoded.
98+
expectParsed('/assets/src/caret%5Edir/image.png?platform=ios', {
99+
resourcePath: 'assets/src/caret^dir/image.png',
100+
platform: 'ios',
101+
});
102+
});
103+
104+
it('should keep a path that is not a valid escape sequence', () => {
105+
expectParsed('assets/100%.png?platform=ios', {
106+
resourcePath: 'assets/100%.png',
107+
platform: 'ios',
108+
});
109+
});
110+
83111
it('should work with different platform lists', () => {
84112
expectParsed(
85113
'/react-native/src/index.js',

‎packages/repack/src/commands/common/__tests__/resolveProjectPath.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import path from 'node:path';
2+
import { parseUrl } from '../parseUrl.js';
23
import { resolveProjectPath } from '../resolveProjectPath.js';
34

45
describe('resolveProjectPath', () => {
@@ -47,4 +48,21 @@ describe('resolveProjectPath', () => {
4748
'/a/b/c/d/e/f'
4849
);
4950
});
51+
52+
it('should resolve paths returned by parseUrl', () => {
53+
// The dev server passes symbolicated file names through parseUrl before
54+
// resolving them, so encoded characters must not survive that step.
55+
const resolveParsed = (input: string) =>
56+
resolveProjectPath(
57+
parseUrl(input, ['ios', 'android']).resourcePath,
58+
path.resolve('/workspace/apps/app')
59+
);
60+
61+
expect(resolveParsed('[projectRoot^2]/node_modules/pkg/index.js')).toBe(
62+
path.resolve('/workspace/node_modules/pkg/index.js')
63+
);
64+
expect(resolveParsed('[projectRoot]/src/Home Screen.tsx')).toBe(
65+
path.resolve('/workspace/apps/app/src/Home Screen.tsx')
66+
);
67+
});
5068
});

‎packages/repack/src/commands/common/parseUrl.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,17 @@
1+
// `new URL()` percent-encodes characters such as spaces, non-ASCII letters
2+
// and the caret in `[projectRoot^N]`, but callers look the path up as a file.
3+
function decodePathname(pathname: string) {
4+
try {
5+
return decodeURIComponent(pathname);
6+
} catch {
7+
// a malformed escape sequence, e.g. a literal `%` in a file name
8+
return pathname;
9+
}
10+
}
11+
112
export function parseUrl(url: string, platforms: string[], base = 'file:///') {
2-
const { pathname, searchParams } = new URL(url, base);
13+
const { pathname: encodedPathname, searchParams } = new URL(url, base);
14+
const pathname = decodePathname(encodedPathname);
315

416
let path = pathname;
517
let platform = searchParams.get('platform');

‎packages/repack/src/loaders/babelLoader/babelLoader.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,6 @@ export default async function babelLoader(
138138
filename: this.resourcePath,
139139
sourceMaps: withSourceMaps,
140140
sourceFileName: this.resourcePath,
141-
sourceRoot: this.context,
142141
inputSourceMap: withSourceMaps ? inputSourceMap : undefined,
143142
...babelOverrides,
144143
},

‎packages/repack/src/loaders/babelSwcLoader/babelSwcLoader.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,6 @@ export default async function babelSwcLoader(
123123
filename: this.resourcePath,
124124
sourceMaps: withSourceMaps,
125125
sourceFileName: this.resourcePath,
126-
sourceRoot: this.context,
127126
inputSourceMap: withSourceMaps ? inputSourceMap : undefined,
128127
...options.babelOverrides,
129128
};
@@ -176,7 +175,6 @@ export default async function babelSwcLoader(
176175
? JSON.stringify(babelResult?.map)
177176
: undefined,
178177
sourceFileName: this.resourcePath,
179-
sourceRoot: this.context!,
180178
...options.swcOverrides,
181179
});
182180

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)