Skip to content

Commit 3599eae

Browse files
authored
fix(core): handle builtin imports in linked esm loader (#1070)
1 parent 8b9417f commit 3599eae

File tree

2 files changed

+52
-2
lines changed

2 files changed

+52
-2
lines changed

packages/core/src/runtime/worker/loadEsModule.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { builtinModules } from 'node:module';
12
import { isAbsolute } from 'node:path';
23
import { fileURLToPath, pathToFileURL } from 'node:url';
34
import vm, { type ModuleLinker, type SourceTextModule } from 'node:vm';
@@ -13,6 +14,9 @@ export enum EsmMode {
1314

1415
const isRelativePath = (p: string) => /^\.\.?\//.test(p);
1516

17+
const isBuiltinSpecifier = (specifier: string) =>
18+
specifier.startsWith('node:') || builtinModules.includes(specifier);
19+
1620
const defineRstestDynamicImport =
1721
({
1822
distPath,
@@ -69,8 +73,10 @@ const defineRstestDynamicImport =
6973

7074
const resolvedPath = isAbsolute(specifier)
7175
? pathToFileURL(specifier)
72-
: // TODO: use module path instead of testPath
73-
import.meta.resolve(specifier, pathToFileURL(testPath));
76+
: isBuiltinSpecifier(specifier)
77+
? specifier
78+
: // TODO: use module path instead of testPath
79+
import.meta.resolve(specifier, pathToFileURL(testPath));
7480

7581
const modulePath =
7682
typeof resolvedPath === 'string' ? resolvedPath : resolvedPath.pathname;
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { sep } from 'node:path';
2+
import {
3+
clearModuleCache,
4+
loadModule,
5+
} from '../../src/runtime/worker/loadEsModule';
6+
7+
describe('loadEsModule', () => {
8+
afterEach(() => {
9+
clearModuleCache();
10+
});
11+
12+
it('should link nested modules that statically import builtins', async () => {
13+
const testPath = '/virtual/tests/runtime.test.ts';
14+
const distPath = '/virtual/dist/entry.mjs';
15+
const chunkPath = '/virtual/dist/chunk.mjs';
16+
17+
const mod = await loadModule({
18+
codeContent: [
19+
"import chunk, { separator } from './chunk.mjs';",
20+
'export default {',
21+
' hasReadFile: chunk,',
22+
' separator,',
23+
'};',
24+
].join('\n'),
25+
distPath,
26+
testPath,
27+
rstestContext: {},
28+
assetFiles: {
29+
[chunkPath]: [
30+
"import fs from 'node:fs';",
31+
"import path from 'node:path';",
32+
'export const separator = path.sep;',
33+
"export default typeof fs.readFile === 'function';",
34+
].join('\n'),
35+
},
36+
interopDefault: false,
37+
});
38+
39+
expect(mod.default).toEqual({
40+
hasReadFile: true,
41+
separator: sep,
42+
});
43+
});
44+
});

0 commit comments

Comments
 (0)