Repository navigation
Expand file tree
/
Copy pathjavascript-transformer-worker.ts
More file actions
281 lines (248 loc) · 9.04 KB
/
Copy pathjavascript-transformer-worker.ts
File metadata and controls
281 lines (248 loc) · 9.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type { DecodedSourceMap, EncodedSourceMap } from '@ampproject/remapping';
import type { PluginItem } from '@babel/core';
import { createRequire } from 'node:module';
import { workerData } from 'node:worker_threads';
import Piscina from 'piscina';
import { useBabelLinker } from '../../utils/environment-options.js';
import {
findTrailingSourceMapComment,
isTrailingSourceMapComment,
loadInputSourceMap,
loadInputSourceMapFromUrl,
removeSourceMappingURL,
} from '../../utils/source-map';
import type { JavaScriptTransformerOptions } from './javascript-transformer';
interface JavaScriptTransformRequest {
filename: string;
data: string | Uint8Array;
skipLinker?: boolean;
sideEffects?: boolean;
instrumentForCoverage?: boolean;
}
interface TransformOptions extends Omit<JavaScriptTransformRequest, 'filename' | 'data'> {
inputSourceMap?: EncodedSourceMap;
isAlreadyStripped?: boolean;
}
const {
sourcemap = false,
thirdPartySourcemaps = false,
advancedOptimizations = false,
jit = false,
} = (workerData || {}) as Partial<JavaScriptTransformerOptions>;
let babelLinkerDeps:
| Promise<
[
typeof import('@angular/compiler-cli/linker/babel'),
typeof import('@angular/compiler-cli'),
typeof import('@babel/core'),
]
>
| undefined;
let remapping: typeof import('@ampproject/remapping').default | undefined;
let oxcTransform: typeof import('../oxc/oxc-transform.js').transform | undefined;
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
async function instrumentCoverage(
filename: string,
data: string,
useInputSourcemap: boolean,
): Promise<{ code: string; map?: EncodedSourceMap }> {
try {
let resolvedPath = 'istanbul-lib-instrument';
try {
const requireFn = createRequire(filename);
resolvedPath = requireFn.resolve('istanbul-lib-instrument');
} catch {
// Fallback to pool worker import traversal
}
const { createInstrumenter } = (await import(
resolvedPath
)) as typeof import('istanbul-lib-instrument');
const instrumenter = createInstrumenter({
produceSourceMap: useInputSourcemap,
esModules: true,
});
const inputSourceMap = useInputSourcemap ? loadInputSourceMap(filename, data) : undefined;
const instrumentedCode = instrumenter.instrumentSync(
data,
filename,
inputSourceMap as Parameters<typeof instrumenter.instrumentSync>[2],
);
const lastMap = useInputSourcemap
? (instrumenter.lastSourceMap() as EncodedSourceMap)
: undefined;
return {
code: instrumentedCode,
map: lastMap ?? undefined,
};
} catch (error) {
throw new Error(
`The 'istanbul-lib-instrument' package is required for code coverage but was not found. Please install the package.`,
{ cause: error },
);
}
}
export default async function transformJavaScript(
request: JavaScriptTransformRequest,
): Promise<unknown> {
const { filename, data, ...options } = request;
const useInputSourcemap =
sourcemap && (!!thirdPartySourcemaps || !/[\\/]node_modules[\\/]/.test(filename));
let textData: string;
let inputSourceMap: EncodedSourceMap | undefined;
let isAlreadyStripped = false;
if (typeof data !== 'string') {
const trailing = findTrailingSourceMapComment(data);
if (trailing === null) {
// 0 comments: fast path, no sourcemap to load or strip
textData = textDecoder.decode(data);
isAlreadyStripped = true;
} else if (trailing !== undefined) {
if (useInputSourcemap) {
inputSourceMap = loadInputSourceMapFromUrl(filename, trailing.urlLine);
if (inputSourceMap !== undefined) {
// Valid trailing sourcemap comment confirmed: safe to slice code buffer for transformation passes.
// Note: If no passes modify the code, the untouched original `data` buffer is returned below.
textData = textDecoder.decode(trailing.code);
isAlreadyStripped = true;
} else {
// Not a valid trailing sourcemap (e.g. inside template literal): fallback to full decode
textData = textDecoder.decode(data);
}
} else if (isTrailingSourceMapComment(trailing.urlLine)) {
// Valid trailing sourcemap comment confirmed: safe to slice code buffer
textData = textDecoder.decode(trailing.code);
isAlreadyStripped = true;
} else {
// Fallback to full decode and state-machine stripping
textData = textDecoder.decode(data);
}
} else {
// Multiple comments or comment not at line start: fall back to full decode and string parser
textData = textDecoder.decode(data);
}
} else {
textData = data;
}
const transformedData = await transformJavaScriptImpl(filename, textData, {
...options,
inputSourceMap,
isAlreadyStripped,
});
// If no transformations modified the code, return the original untouched data buffer via `move`.
// This preserves any original trailing sourcemap comment and avoids re-encoding.
if (transformedData === textData && typeof data !== 'string') {
return Piscina.move(data);
}
return Piscina.move(textEncoder.encode(transformedData));
}
async function transformJavaScriptImpl(
filename: string,
data: string,
options: TransformOptions,
): Promise<string> {
const shouldLink = !options.skipLinker;
const useInputSourcemap =
sourcemap && (!!thirdPartySourcemaps || !/[\\/]node_modules[\\/]/.test(filename));
let code = data;
const maps: (DecodedSourceMap | EncodedSourceMap)[] = [];
let coverageMap: EncodedSourceMap | undefined;
if (options.instrumentForCoverage) {
const result = await instrumentCoverage(filename, code, useInputSourcemap);
code = result.code;
coverageMap = result.map;
}
let oxcLink = shouldLink && !useBabelLinker;
const shouldRunOxc = oxcLink || (!process.versions.webcontainer && advancedOptimizations);
if (shouldRunOxc) {
try {
oxcTransform ??= (await import('../oxc/oxc-transform.js')).transform;
} catch {
oxcLink = false;
}
}
if (shouldLink && (useBabelLinker || !oxcLink)) {
babelLinkerDeps ??= Promise.all([
import('@angular/compiler-cli/linker/babel'),
import('@angular/compiler-cli'),
import('@babel/core'),
]);
const [{ createEs2015LinkerPlugin }, { ConsoleLogger, LogLevel }, { transformAsync }] =
await babelLinkerDeps;
const result = await transformAsync(code, {
filename,
inputSourceMap: false,
sourceMaps: !!useInputSourcemap,
compact: false,
configFile: false,
babelrc: false,
browserslistConfigFile: false,
plugins: [
createEs2015LinkerPlugin({
fileSystem: {
exists: () => false,
readFile: () => '',
resolve: (...paths: string[]) => paths.join('/'),
dirname: (path: string) => path.split('/').slice(0, -1).join('/'),
relative: (_from: string, to: string) => to,
} as never,
logger: new ConsoleLogger(LogLevel.info),
linkerJitMode: jit,
// This is a workaround until https://github.com/angular/angular/issues/42769 is fixed.
sourceMapping: false,
}) as PluginItem,
],
});
code = result?.code ?? code;
if (result?.map) {
maps.push(result.map as EncodedSourceMap);
}
}
// Run Oxc linking and/or advanced optimizations in a single unified AST traversal pass
if (oxcTransform && (oxcLink || advancedOptimizations)) {
const sideEffectFree = options.sideEffects === false;
const safeAngularPackage =
sideEffectFree && /[\\/]node_modules[\\/]@angular[\\/]/.test(filename);
const topLevelSafeMode = !safeAngularPackage;
const result = oxcTransform(filename, code, {
link: oxcLink,
jit,
advancedOptimizations,
sourcemap: useInputSourcemap,
sideEffects: options.sideEffects,
topLevelSafeMode,
});
code = result.code;
if (result.map) {
maps.push(result.map);
}
}
if (useInputSourcemap) {
const baseMap = coverageMap ?? options.inputSourceMap ?? loadInputSourceMap(filename, data);
if (maps.length > 0 || coverageMap) {
if (!options.isAlreadyStripped) {
code = removeSourceMappingURL(code);
}
const remappingChain: (DecodedSourceMap | EncodedSourceMap)[] = maps.reverse();
if (baseMap) {
remappingChain.push(baseMap);
}
if (remappingChain.length > 0) {
remapping ??= (await import('@ampproject/remapping')).default;
const finalMap = remapping(remappingChain, () => null).toString();
const base64Map = Buffer.from(finalMap).toString('base64');
code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`;
}
}
return code;
}
// Strip sourcemaps if they should not be used
return options.isAlreadyStripped ? code : removeSourceMappingURL(code);
}