-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathmodule-source.ts
More file actions
405 lines (361 loc) · 11.5 KB
/
module-source.ts
File metadata and controls
405 lines (361 loc) · 11.5 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import { existsSync, readFileSync } from "node:fs";
import { dirname as pathDirname, join as pathJoin } from "node:path";
import { pathToFileURL } from "node:url";
import { transform, transformSync } from "esbuild";
import { initSync as initCjsLexerSync, parse as parseCjsExports } from "cjs-module-lexer";
import { init, initSync, parse } from "es-module-lexer";
const REQUIRE_TRANSFORM_MARKER = "/*__secure_exec_require_esm__*/";
const IMPORT_META_URL_HELPER = "__secureExecImportMetaUrl__";
const IMPORT_META_RESOLVE_HELPER = "__secureExecImportMetaResolve__";
const UNICODE_SET_REGEX_MARKER = "/v";
const CJS_IMPORT_DEFAULT_HELPER = "__secureExecImportedCjsModule__";
function isJavaScriptLikePath(filePath: string | undefined): boolean {
return filePath === undefined || /\.[cm]?[jt]sx?$/.test(filePath);
}
function normalizeJavaScriptSource(source: string): string {
const bomPrefix = source.charCodeAt(0) === 0xfeff ? "\uFEFF" : "";
const shebangOffset = bomPrefix.length;
if (!source.startsWith("#!", shebangOffset)) {
return source;
}
return (
bomPrefix +
"//" +
source.slice(shebangOffset + 2)
);
}
function parseSourceSyntax(source: string, filePath?: string) {
const [imports, , , hasModuleSyntax] = parse(source, filePath);
const hasDynamicImport = imports.some((specifier) => specifier.d >= 0);
const hasImportMeta = imports.some((specifier) => specifier.d === -2);
return { hasModuleSyntax, hasDynamicImport, hasImportMeta };
}
/**
* Expand `export * from '...'` re-exports into explicit named exports.
*
* The V8 isolate's module linker doesn't automatically resolve star
* re-exports, so we pre-resolve them by reading the target module and
* extracting its named exports. This runs on the host side before the
* source is sent to the isolate.
*/
function expandStarReExports(source: string, hostPath: string): string {
const starExportRegex = /export\s*\*\s*from\s*['"]([^'"]+)['"]\s*;?/g;
let result = source;
let match: RegExpExecArray | null;
// Collect names already directly exported by this module to avoid duplicates
initSync();
const [, ownExports] = parse(source, hostPath);
const ownExportNames = new Set(
ownExports
.map((e) => e.n)
.filter((n): n is string => typeof n === "string"),
);
while ((match = starExportRegex.exec(source)) !== null) {
const specifier = match[1];
const dir = pathDirname(hostPath);
const targetPath = specifier.startsWith(".")
? pathJoin(dir, specifier)
: null;
if (!targetPath || !existsSync(targetPath)) continue;
try {
const names = collectNamedExportsForStarResolution(targetPath)
.filter((n) => n !== "default" && !ownExportNames.has(n));
if (names.length > 0) {
// Track these names so subsequent export * don't duplicate
for (const n of names) ownExportNames.add(n);
result = result.replace(
match[0],
`export { ${names.join(", ")} } from '${specifier}';`,
);
} else {
result = result.replace(match[0], "");
}
} catch {
// If we can't resolve, leave the export * as-is
}
}
return result;
}
function collectNamedExportsForStarResolution(
filePath: string,
visited = new Set<string>(),
): string[] {
if (visited.has(filePath) || !existsSync(filePath)) {
return [];
}
visited.add(filePath);
const source = readFileSync(filePath, "utf-8");
const starExportRegex = /export\s*\*\s*from\s*['"]([^'"]+)['"]\s*;?/g;
const [, ownExports] = parse(source, filePath);
const names = new Set(
ownExports
.map((e) => e.n)
.filter((n): n is string => typeof n === "string"),
);
let match: RegExpExecArray | null;
while ((match = starExportRegex.exec(source)) !== null) {
const specifier = match[1];
if (!specifier.startsWith(".")) continue;
const targetPath = pathJoin(pathDirname(filePath), specifier);
for (const name of collectNamedExportsForStarResolution(targetPath, visited)) {
names.add(name);
}
}
return Array.from(names);
}
function isValidIdentifier(value: string): boolean {
return /^[$A-Z_][0-9A-Z_$]*$/i.test(value);
}
function getNearestPackageTypeSync(filePath: string): "module" | "commonjs" | null {
let currentDir = pathDirname(filePath);
while (true) {
const packageJsonPath = pathJoin(currentDir, "package.json");
if (existsSync(packageJsonPath)) {
try {
const pkgJson = JSON.parse(readFileSync(packageJsonPath, "utf8")) as {
type?: unknown;
};
return pkgJson.type === "module" || pkgJson.type === "commonjs"
? pkgJson.type
: null;
} catch {
return null;
}
}
const parentDir = pathDirname(currentDir);
if (parentDir === currentDir) {
return null;
}
currentDir = parentDir;
}
}
function isCommonJsModuleForImportSync(source: string, formatPath: string): boolean {
if (!isJavaScriptLikePath(formatPath)) {
return false;
}
if (formatPath.endsWith(".cjs")) {
return true;
}
if (formatPath.endsWith(".mjs")) {
return false;
}
if (formatPath.endsWith(".js")) {
const packageType = getNearestPackageTypeSync(formatPath);
if (formatPath.includes("balanced")) {
console.error(`[isCommonJsModuleForImportSync] path=${formatPath} packageType=${packageType}`);
}
if (packageType === "module") {
return false;
}
if (packageType === "commonjs") {
return true;
}
initSync();
const syntax = parseSourceSyntax(source, formatPath);
if (formatPath.includes("balanced")) {
console.error(`[isCommonJsModuleForImportSync] hasModuleSyntax=${syntax.hasModuleSyntax}`);
}
return !syntax.hasModuleSyntax;
}
return false;
}
function buildCommonJsImportWrapper(source: string, filePath: string): string {
initCjsLexerSync();
const { exports: cjsExports } = parseCjsExports(source);
let namedExports = Array.from(
new Set(
cjsExports.filter(
(name) =>
name !== "default" &&
name !== "__esModule" &&
isValidIdentifier(name),
),
),
);
// Node.js CJS interop: when module.exports = identifier, the identifier
// becomes a named export. Detect `module.exports = <name>` and add it.
if (namedExports.length === 0) {
const match = source.match(/module\.exports\s*=\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*;?\s*$/m);
if (match && match[1] !== "undefined" && match[1] !== "null") {
namedExports = [match[1]];
}
}
// Also extract all enumerable property names from the module at load time.
// This handles cases where module.exports is an object with properties
// that cjs-module-lexer doesn't detect.
const lines = [
`const ${CJS_IMPORT_DEFAULT_HELPER} = globalThis._requireFrom(${JSON.stringify(filePath)}, "/");`,
`export default ${CJS_IMPORT_DEFAULT_HELPER};`,
...namedExports.map(
(name) =>
`export const ${name} = ${CJS_IMPORT_DEFAULT_HELPER} == null ? undefined : ${CJS_IMPORT_DEFAULT_HELPER}[${JSON.stringify(name)}];`,
),
];
return lines.join("\n");
}
function getRequireTransformOptions(
filePath: string,
syntax: ReturnType<typeof parseSourceSyntax>,
) {
const requiresEsmWrapper =
syntax.hasModuleSyntax || syntax.hasImportMeta;
const bannerLines = requiresEsmWrapper ? [REQUIRE_TRANSFORM_MARKER] : [];
if (syntax.hasImportMeta) {
bannerLines.push(
`const ${IMPORT_META_URL_HELPER} = require("node:url").pathToFileURL(__secureExecFilename).href;`,
);
}
return {
banner: bannerLines.length > 0 ? bannerLines.join("\n") : undefined,
define: syntax.hasImportMeta
? {
"import.meta.url": IMPORT_META_URL_HELPER,
}
: undefined,
format: "cjs" as const,
loader: "js" as const,
platform: "node" as const,
sourcefile: filePath,
supported: {
"dynamic-import": false,
},
target: "node22",
};
}
function getImportTransformOptions(
filePath: string,
syntax: ReturnType<typeof parseSourceSyntax>,
) {
const bannerLines: string[] = [];
if (syntax.hasImportMeta) {
bannerLines.push(
`const ${IMPORT_META_URL_HELPER} = ${JSON.stringify(pathToFileURL(filePath).href)};`,
`const ${IMPORT_META_RESOLVE_HELPER} = (specifier) => globalThis.__importMetaResolve(specifier, ${JSON.stringify(filePath)});`,
);
}
return {
banner: bannerLines.length > 0 ? bannerLines.join("\n") : undefined,
define: syntax.hasImportMeta
? {
"import.meta.url": IMPORT_META_URL_HELPER,
"import.meta.resolve": IMPORT_META_RESOLVE_HELPER,
}
: undefined,
format: "esm" as const,
loader: "js" as const,
platform: "node" as const,
sourcefile: filePath,
target: "es2020",
};
}
export async function sourceHasModuleSyntax(
source: string,
filePath?: string,
): Promise<boolean> {
const normalizedSource = normalizeJavaScriptSource(source);
if (filePath?.endsWith(".mjs")) {
return true;
}
if (filePath?.endsWith(".cjs")) {
return false;
}
await init;
return parseSourceSyntax(normalizedSource, filePath).hasModuleSyntax;
}
export function transformSourceForRequireSync(
source: string,
filePath: string,
): string {
if (!isJavaScriptLikePath(filePath)) {
return source;
}
const normalizedSource = normalizeJavaScriptSource(source);
initSync();
const syntax = parseSourceSyntax(normalizedSource, filePath);
if (!(syntax.hasModuleSyntax || syntax.hasDynamicImport || syntax.hasImportMeta)) {
return normalizedSource;
}
try {
return transformSync(normalizedSource, getRequireTransformOptions(filePath, syntax)).code;
} catch {
return normalizedSource;
}
}
export async function transformSourceForRequire(
source: string,
filePath: string,
): Promise<string> {
if (!isJavaScriptLikePath(filePath)) {
return source;
}
const normalizedSource = normalizeJavaScriptSource(source);
await init;
const syntax = parseSourceSyntax(normalizedSource, filePath);
if (!(syntax.hasModuleSyntax || syntax.hasDynamicImport || syntax.hasImportMeta)) {
return normalizedSource;
}
try {
return (
await transform(normalizedSource, getRequireTransformOptions(filePath, syntax))
).code;
} catch {
return normalizedSource;
}
}
export async function transformSourceForImport(
source: string,
filePath: string,
): Promise<string> {
if (!isJavaScriptLikePath(filePath)) {
return source;
}
const normalizedSource = normalizeJavaScriptSource(source);
await init;
const syntax = parseSourceSyntax(normalizedSource, filePath);
const needsTransform =
normalizedSource.includes(UNICODE_SET_REGEX_MARKER) || syntax.hasImportMeta;
if (!(syntax.hasModuleSyntax || syntax.hasDynamicImport || syntax.hasImportMeta)) {
return normalizedSource;
}
if (!needsTransform) {
return normalizedSource;
}
try {
return (await transform(normalizedSource, getImportTransformOptions(filePath, syntax))).code;
} catch {
return normalizedSource;
}
}
export function transformSourceForImportSync(
source: string,
filePath: string,
formatPath: string = filePath,
): string {
if (!isJavaScriptLikePath(filePath)) {
return source;
}
const normalizedSource = normalizeJavaScriptSource(source);
if (isCommonJsModuleForImportSync(normalizedSource, formatPath)) {
return buildCommonJsImportWrapper(normalizedSource, filePath);
}
// Expand export * re-exports before V8 evaluation
let processedSource = normalizedSource;
if (/export\s*\*\s*from\s/.test(processedSource) && formatPath) {
processedSource = expandStarReExports(processedSource, formatPath);
}
initSync();
const syntax = parseSourceSyntax(processedSource, filePath);
const needsTransform =
processedSource.includes(UNICODE_SET_REGEX_MARKER) || syntax.hasImportMeta;
if (!(syntax.hasModuleSyntax || syntax.hasDynamicImport || syntax.hasImportMeta)) {
return processedSource;
}
if (!needsTransform) {
return processedSource;
}
try {
return transformSync(processedSource, getImportTransformOptions(filePath, syntax)).code;
} catch {
return processedSource;
}
}