Skip to content

Commit 2f75925

Browse files
committed
fix: compose Turbopack platform maps and detect DefinePlugin conflicts
Preserve incoming compile maps when rewriting platform flags, and read webpack-shaped DefinePlugin definitions so Rspack conflict checks fire.
1 parent a180410 commit 2f75925

10 files changed

Lines changed: 307 additions & 20 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@tsrx/core': patch
3+
'@tsrx/turbopack-plugin-react': patch
4+
'@tsrx/rspack-plugin-react': patch
5+
'@tsrx/rspack-plugin-preact': patch
6+
'@tsrx/rspack-plugin-solid': patch
7+
'@tsrx/rspack-plugin-vue': patch
8+
---
9+
10+
Compose incoming source maps in the Turbopack platform loader and detect webpack-shaped Rspack DefinePlugin conflicts.

‎packages/rspack-plugin-preact/src/index.js‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,31 @@ const CSS_LOADER = path.join(__dirname, 'css-loader.js');
1818
const TSRX_EXTENSION_PATTERN = /\.tsrx$/;
1919
const CSS_QUERY_PATTERN = /tsrx-css/;
2020

21+
/** @param {any} plugin @returns {Record<string, unknown> | undefined} */
22+
function get_define_plugin_definitions(plugin) {
23+
if (plugin == null || typeof plugin !== 'object') return undefined;
24+
const name = plugin.name ?? plugin.constructor?.name;
25+
if (name !== 'DefinePlugin') return undefined;
26+
27+
if (plugin.definitions && typeof plugin.definitions === 'object') {
28+
return plugin.definitions;
29+
}
30+
if (Array.isArray(plugin._args) && plugin._args[0] && typeof plugin._args[0] === 'object') {
31+
return plugin._args[0];
32+
}
33+
if (plugin.options && typeof plugin.options === 'object' && !Array.isArray(plugin.options)) {
34+
return plugin.options;
35+
}
36+
return undefined;
37+
}
38+
2139
/** @param {Compiler} compiler @param {Platform | undefined} platform */
2240
function apply_platform_definitions(compiler, platform) {
2341
if (platform === undefined) return;
2442
const compiler_with_definitions = /** @type {any} */ (compiler);
2543
for (const plugin of compiler_with_definitions.options.plugins ?? []) {
26-
if (plugin?.name !== 'DefinePlugin' || !Array.isArray(plugin._args)) continue;
27-
const definitions = plugin._args[0];
28-
if (definitions && typeof definitions === 'object') {
44+
const definitions = get_define_plugin_definitions(plugin);
45+
if (definitions) {
2946
mergePlatformDefinitions(definitions, platform, { integration: 'Rspack' });
3047
}
3148
}

‎packages/rspack-plugin-react/src/index.js‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,32 @@ const CSS_LOADER = path.join(__dirname, 'css-loader.js');
1414
const TSRX_EXTENSION_PATTERN = /\.tsrx$/;
1515
const CSS_QUERY_PATTERN = /tsrx-css/;
1616

17+
/** @param {any} plugin @returns {Record<string, unknown> | undefined} */
18+
function get_define_plugin_definitions(plugin) {
19+
if (plugin == null || typeof plugin !== 'object') return undefined;
20+
const name = plugin.name ?? plugin.constructor?.name;
21+
if (name !== 'DefinePlugin') return undefined;
22+
23+
if (plugin.definitions && typeof plugin.definitions === 'object') {
24+
return plugin.definitions;
25+
}
26+
if (Array.isArray(plugin._args) && plugin._args[0] && typeof plugin._args[0] === 'object') {
27+
return plugin._args[0];
28+
}
29+
if (plugin.options && typeof plugin.options === 'object' && !Array.isArray(plugin.options)) {
30+
return plugin.options;
31+
}
32+
return undefined;
33+
}
34+
1735
/** @param {Compiler} compiler @param {Platform | undefined} platform */
1836
function apply_platform_definitions(compiler, platform) {
1937
if (platform === undefined) return;
2038

2139
const compiler_with_definitions = /** @type {any} */ (compiler);
2240
for (const plugin of compiler_with_definitions.options.plugins ?? []) {
23-
if (plugin?.name !== 'DefinePlugin' || !Array.isArray(plugin._args)) continue;
24-
const definitions = plugin._args[0];
25-
if (definitions && typeof definitions === 'object') {
41+
const definitions = get_define_plugin_definitions(plugin);
42+
if (definitions) {
2643
mergePlatformDefinitions(definitions, platform, { integration: 'Rspack' });
2744
}
2845
}

‎packages/rspack-plugin-solid/src/index.js‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,31 @@ const SOLID_REFRESH_BABEL = require.resolve('solid-refresh/babel');
2121
const TSRX_EXTENSION_PATTERN = /\.tsrx$/;
2222
const CSS_QUERY_PATTERN = /tsrx-css/;
2323

24+
/** @param {any} plugin @returns {Record<string, unknown> | undefined} */
25+
function get_define_plugin_definitions(plugin) {
26+
if (plugin == null || typeof plugin !== 'object') return undefined;
27+
const name = plugin.name ?? plugin.constructor?.name;
28+
if (name !== 'DefinePlugin') return undefined;
29+
30+
if (plugin.definitions && typeof plugin.definitions === 'object') {
31+
return plugin.definitions;
32+
}
33+
if (Array.isArray(plugin._args) && plugin._args[0] && typeof plugin._args[0] === 'object') {
34+
return plugin._args[0];
35+
}
36+
if (plugin.options && typeof plugin.options === 'object' && !Array.isArray(plugin.options)) {
37+
return plugin.options;
38+
}
39+
return undefined;
40+
}
41+
2442
/** @param {Compiler} compiler @param {Platform | undefined} platform */
2543
function apply_platform_definitions(compiler, platform) {
2644
if (platform === undefined) return;
2745
const compiler_with_definitions = /** @type {any} */ (compiler);
2846
for (const plugin of compiler_with_definitions.options.plugins ?? []) {
29-
if (plugin?.name !== 'DefinePlugin' || !Array.isArray(plugin._args)) continue;
30-
const definitions = plugin._args[0];
31-
if (definitions && typeof definitions === 'object') {
47+
const definitions = get_define_plugin_definitions(plugin);
48+
if (definitions) {
3249
mergePlatformDefinitions(definitions, platform, { integration: 'Rspack' });
3350
}
3451
}

‎packages/rspack-plugin-vue/src/index.js‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,31 @@ const TSRX_EXTENSION_PATTERN = /\.tsrx$/;
1717
const CSS_QUERY_PATTERN = /tsrx-css/;
1818
const SOURCE_EXTENSION_PATTERN = /\.[cm]?[jt]sx?$/;
1919

20+
/** @param {any} plugin @returns {Record<string, unknown> | undefined} */
21+
function get_define_plugin_definitions(plugin) {
22+
if (plugin == null || typeof plugin !== 'object') return undefined;
23+
const name = plugin.name ?? plugin.constructor?.name;
24+
if (name !== 'DefinePlugin') return undefined;
25+
26+
if (plugin.definitions && typeof plugin.definitions === 'object') {
27+
return plugin.definitions;
28+
}
29+
if (Array.isArray(plugin._args) && plugin._args[0] && typeof plugin._args[0] === 'object') {
30+
return plugin._args[0];
31+
}
32+
if (plugin.options && typeof plugin.options === 'object' && !Array.isArray(plugin.options)) {
33+
return plugin.options;
34+
}
35+
return undefined;
36+
}
37+
2038
/** @param {Compiler} compiler @param {Platform | undefined} platform */
2139
function apply_platform_definitions(compiler, platform) {
2240
if (platform === undefined) return;
2341
const compiler_with_definitions = /** @type {any} */ (compiler);
2442
for (const plugin of compiler_with_definitions.options.plugins ?? []) {
25-
if (plugin?.name !== 'DefinePlugin' || !Array.isArray(plugin._args)) continue;
26-
const definitions = plugin._args[0];
27-
if (definitions && typeof definitions === 'object') {
43+
const definitions = get_define_plugin_definitions(plugin);
44+
if (definitions) {
2845
mergePlatformDefinitions(definitions, platform, { integration: 'Rspack' });
2946
}
3047
}

‎packages/tsrx/src/transform/platform.js‎

Lines changed: 110 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/** @import * as AST from 'estree' */
22
/** @import { CompileError, Platform, PlatformSpecializationOptions } from '../../types/index' */
33

4+
import { decode, encode } from '@jridgewell/sourcemap-codec';
45
import MagicString from 'magic-string';
56
import { DIAGNOSTIC_CODES } from '../diagnostics.js';
67
import { error } from '../errors.js';
@@ -326,23 +327,125 @@ declare global {
326327
return { ...result, code: result.code + declarations };
327328
}
328329

330+
/**
331+
* @param {unknown} map
332+
* @returns {import('source-map').RawSourceMap | undefined}
333+
*/
334+
function normalize_source_map(map) {
335+
if (map == null) return undefined;
336+
const parsed = typeof map === 'string' ? JSON.parse(map) : map;
337+
if (parsed && typeof parsed === 'object' && typeof parsed.mappings === 'string') {
338+
return /** @type {import('source-map').RawSourceMap} */ (parsed);
339+
}
340+
return undefined;
341+
}
342+
343+
/**
344+
* Chain a follow-up MagicString map through an incoming compile map so the
345+
* result still names the original file and content, not the intermediate source.
346+
*
347+
* @param {import('source-map').RawSourceMap} input_map
348+
* @param {import('source-map').RawSourceMap} output_map
349+
* @returns {import('source-map').RawSourceMap}
350+
*/
351+
function compose_source_maps(input_map, output_map) {
352+
const input_decoded = decode(input_map.mappings);
353+
const output_decoded = decode(output_map.mappings);
354+
355+
/**
356+
* @param {number} line
357+
* @param {number} column
358+
* @returns {{ source_index: number, line: number, column: number, name_index?: number } | null}
359+
*/
360+
function original_position_for(line, column) {
361+
const segments = input_decoded[line];
362+
if (!segments || segments.length === 0) return null;
363+
364+
let low = 0;
365+
let high = segments.length - 1;
366+
let found = -1;
367+
while (low <= high) {
368+
const mid = (low + high) >> 1;
369+
if (segments[mid][0] <= column) {
370+
found = mid;
371+
low = mid + 1;
372+
} else {
373+
high = mid - 1;
374+
}
375+
}
376+
if (found === -1) return null;
377+
378+
const segment = segments[found];
379+
if (segment.length < 4) return null;
380+
381+
return {
382+
source_index: segment[1],
383+
line: segment[2],
384+
column: segment[3],
385+
name_index: segment.length > 4 ? segment[4] : undefined,
386+
};
387+
}
388+
389+
/** @typedef {[number] | [number, number, number, number] | [number, number, number, number, number]} SourceMapSegment */
390+
/** @type {SourceMapSegment[][]} */
391+
const composed = [];
392+
for (const line of output_decoded) {
393+
/** @type {SourceMapSegment[]} */
394+
const next_line = [];
395+
for (const segment of line) {
396+
if (segment.length < 4) {
397+
next_line.push([segment[0]]);
398+
continue;
399+
}
400+
401+
const original = original_position_for(segment[2], segment[3]);
402+
if (!original) continue;
403+
404+
next_line.push(
405+
original.name_index === undefined
406+
? [segment[0], original.source_index, original.line, original.column]
407+
: [
408+
segment[0],
409+
original.source_index,
410+
original.line,
411+
original.column,
412+
original.name_index,
413+
],
414+
);
415+
}
416+
composed.push(next_line);
417+
}
418+
419+
return {
420+
...input_map,
421+
file: output_map.file ?? input_map.file,
422+
mappings: encode(composed),
423+
};
424+
}
425+
329426
/**
330427
* Replace exact platform flag expressions in a JavaScript/TypeScript module.
331428
* This is used by integrations without a native `define` facility. It does not
332429
* perform dead-code elimination; the downstream bundler sees literal booleans
333430
* and owns that optimization.
334431
*
432+
* When `input_map` is supplied, the returned map is composed through that map
433+
* so loader chains keep pointing at the original file instead of the
434+
* intermediate source that this pass rewrites.
435+
*
335436
* @param {string} source
336437
* @param {string} filename
337438
* @param {unknown} platform_value
439+
* @param {import('source-map').RawSourceMap | string | null} [input_map]
338440
* @returns {{ code: string, map: import('source-map').RawSourceMap }}
339441
*/
340-
export function replace_platform_flags(source, filename, platform_value) {
442+
export function replace_platform_flags(source, filename, platform_value, input_map) {
341443
const platform = validate_platform(platform_value);
342444
if (platform === undefined) {
343445
throw new TypeError('Replacing TSRX platform flags requires a configured platform.');
344446
}
345447

448+
const incoming = normalize_source_map(input_map);
346449
const ast = parse_module(source, filename);
347450
const output = new MagicString(source);
348451

@@ -358,8 +461,13 @@ export function replace_platform_flags(source, filename, platform_value) {
358461
}
359462

360463
visit(ast);
464+
if (!output.hasChanged() && incoming) {
465+
return { code: source, map: incoming };
466+
}
467+
468+
const map = output.generateMap({ source: filename, includeContent: true, hires: true });
361469
return {
362470
code: output.toString(),
363-
map: output.generateMap({ source: filename, includeContent: true, hires: true }),
471+
map: incoming ? compose_source_maps(incoming, map) : map,
364472
};
365473
}

‎packages/tsrx/tests/utils/platform.test.js‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { encode } from '@jridgewell/sourcemap-codec';
12
import { describe, expect, it } from 'vitest';
23
import {
34
createPlatformDefinitions,
@@ -61,5 +62,40 @@ describe('platform specialization', () => {
6162
expect(result.code).toContain("'import.meta.env.platform.ios'");
6263
expect(result.code).toContain('const active = true;');
6364
expect(result.map.sources).toEqual(['flags.ts']);
65+
expect(result.map.sourcesContent?.[0]).toBe(source);
66+
});
67+
68+
it('keeps an incoming compile map when no flags are rewritten', () => {
69+
const source = 'export const ready = true;';
70+
const incoming = {
71+
version: 3,
72+
sources: ['App.tsrx'],
73+
sourcesContent: ['export function App() @{ true }'],
74+
names: [],
75+
mappings: 'AAAA',
76+
};
77+
78+
const result = replacePlatformFlags(source, 'App.tsrx', 'web', incoming);
79+
80+
expect(result.code).toBe(source);
81+
expect(result.map).toBe(incoming);
82+
});
83+
84+
it('composes an incoming map instead of treating the rewritten source as the original file', () => {
85+
const intermediate = 'const active = import.meta.env.platform.android;\n';
86+
const incoming = {
87+
version: 3,
88+
file: 'App.js',
89+
sources: ['App.tsrx'],
90+
sourcesContent: ['const active = FLAG;\n'],
91+
names: [],
92+
mappings: encode([[[0, 0, 0, 0]]]),
93+
};
94+
95+
const result = replacePlatformFlags(intermediate, 'App.tsrx', 'android', incoming);
96+
97+
expect(result.code).toContain('const active = true;');
98+
expect(result.map.sources).toEqual(['App.tsrx']);
99+
expect(result.map.sourcesContent).toEqual(['const active = FLAG;\n']);
64100
});
65101
});

‎packages/tsrx/types/index.d.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2395,6 +2395,7 @@ export function replacePlatformFlags(
23952395
source: string,
23962396
filename: string,
23972397
platform: unknown,
2398+
inputMap?: import('source-map').RawSourceMap | string | null,
23982399
): { code: string; map: import('source-map').RawSourceMap };
23992400

24002401
/**

‎packages/turbopack-plugin-react/src/platform-loader.js‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,24 @@ import { replacePlatformFlags } from '@tsrx/react';
1515
* pruned exact ordinary-if guards; this pass handles flags left in runtime
1616
* expressions and ordinary JavaScript/TypeScript modules.
1717
*
18+
* Webpack-compatible loaders receive the previous loader's source map. That map
19+
* must be forwarded so this pass does not treat compiled TSX as the original
20+
* `.tsrx` file.
21+
*
1822
* @this {LoaderContext}
1923
* @param {string} source
24+
* @param {import('source-map').RawSourceMap | string | undefined} [input_map]
2025
* @returns {void}
2126
*/
22-
export default function tsrx_react_turbopack_platform_loader(source) {
27+
export default function tsrx_react_turbopack_platform_loader(source, input_map) {
2328
const callback = this.async();
2429

2530
try {
2631
const { code, map } = replacePlatformFlags(
2732
source,
2833
this.resourcePath,
2934
this.getOptions?.().platform,
35+
input_map,
3036
);
3137
callback(null, code, map);
3238
} catch (/** @type {any} */ error) {

0 commit comments

Comments
 (0)