forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuiltin-named-exports-loader.mjs
59 lines (52 loc) · 1.37 KB
/
builtin-named-exports-loader.mjs
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
import module from 'node:module';
import { readFileSync } from 'node:fs';
/** @type {string} */
let GET_BUILTIN;
export function initialize(data) {
GET_BUILTIN = data.GET_BUILTIN;
}
export async function resolve(specifier, context, next) {
const def = await next(specifier, context);
if (def.url.startsWith('node:')) {
return {
shortCircuit: true,
url: `custom-${def.url}`,
importAttributes: context.importAttributes,
};
}
return def;
}
export function load(url, context, next) {
if (url.startsWith('custom-node:')) {
const urlObj = new URL(url);
return {
shortCircuit: true,
source: generateBuiltinModule(urlObj.pathname),
format: 'commonjs',
};
} else if (context.format === 'commonjs') {
return {
shortCircuit: true,
source: readFileSync(new URL(url)),
format: 'commonjs',
};
}
return next(url);
}
function generateBuiltinModule(builtinName) {
const builtinInstance = module._load(builtinName);
const builtinExports = [
...Object.keys(builtinInstance),
];
return `\
const $builtinInstance = ${GET_BUILTIN}(${JSON.stringify(builtinName)});
module.exports = $builtinInstance;
module.exports.__fromLoader = true;
// We need this for CJS-module-lexer can parse the exported names.
${
builtinExports
.map(name => `exports.${name} = $builtinInstance.${name};`)
.join('\n')
}
`;
}