• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import module from 'module';
2
3const GET_BUILTIN = `$__get_builtin_hole_${Date.now()}`;
4
5export function getGlobalPreloadCode() {
6  return `Object.defineProperty(globalThis, ${JSON.stringify(GET_BUILTIN)}, {
7  value: (builtinName) => {
8    return getBuiltin(builtinName);
9  },
10  enumerable: false,
11  configurable: false,
12});
13`;
14}
15
16export function resolve(specifier, context, defaultResolve) {
17  const def = defaultResolve(specifier, context);
18  if (def.url.startsWith('node:')) {
19    return {
20      url: `custom-${def.url}`,
21    };
22  }
23  return def;
24}
25
26export function getSource(url, context, defaultGetSource) {
27  if (url.startsWith('custom-node:')) {
28    const urlObj = new URL(url);
29    return {
30      source: generateBuiltinModule(urlObj.pathname),
31      format: 'module',
32    };
33  }
34  return defaultGetSource(url, context);
35}
36
37export function getFormat(url, context, defaultGetFormat) {
38  if (url.startsWith('custom-node:')) {
39    return { format: 'module' };
40  }
41  return defaultGetFormat(url, context, defaultGetFormat);
42}
43
44function generateBuiltinModule(builtinName) {
45  const builtinInstance = module._load(builtinName);
46  const builtinExports = [
47    ...Object.keys(builtinInstance),
48  ];
49  return `\
50const $builtinInstance = ${GET_BUILTIN}(${JSON.stringify(builtinName)});
51
52export const __fromLoader = true;
53
54export default $builtinInstance;
55
56${
57  builtinExports
58    .map(name => `export const ${name} = $builtinInstance.${name};`)
59    .join('\n')
60}
61`;
62}
63