Debian Codegraph @

packages/babel-register/src/hook.js

raw symbols SCIP
1 "use strict";
2
3 const { addHook } = require("pirates");
4 const sourceMapSupport = require("source-map-support");
5
6 let piratesRevert;
7 const maps = Object.create(null);
8
9 function installSourceMapSupport() {
10 installSourceMapSupport = () => {}; // eslint-disable-line no-func-assign
11
12 sourceMapSupport.install({
13 handleUncaughtExceptions: false,
14 environment: "node",
15 retrieveSourceMap(filename) {
16 const map = maps?.[filename];
17 if (map) {
18 return { url: null, map: map };
19 } else {
20 return null;
21 }
22 },
23 });
24 }
25
26 if (!process.env.BABEL_8_BREAKING) {
27 // Babel 7 compiles files in the same thread where it hooks `require()`,
28 // so we must prevent mixing Babel plugin dependencies with the files
29 // to be compiled.
30 // All the `!process.env.BABEL_8_BREAKING` code in this file is for
31 // this purpose.
32
33 const Module = require("module");
34
35 let compiling = false;
36 const internalModuleCache = Module._cache;
37
38 // eslint-disable-next-line no-var
39 var compileBabel7 = function compileBabel7(client, code, filename) {
40 if (!client.isLocalClient) return compile(client, code, filename);
41
42 if (compiling) return code;
43
44 const globalModuleCache = Module._cache;
45 try {
46 compiling = true;
47 Module._cache = internalModuleCache;
48 return compile(client, code, filename);
49 } finally {
50 compiling = false;
51 Module._cache = globalModuleCache;
52 }
53 };
54 }
55
56 function compile(client, inputCode, filename) {
57 const result = client.transform(inputCode, filename);
58
59 if (result === null) return inputCode;
60
61 const { code, map } = result;
62 if (map) {
63 maps[filename] = map;
64 installSourceMapSupport();
65 }
66 return code;
67 }
68
69 exports.register = function register(client, opts = {}) {
70 if (piratesRevert) piratesRevert();
71
72 piratesRevert = addHook(
73 (process.env.BABEL_8_BREAKING ? compile : compileBabel7).bind(null, client),
74 {
75 exts: opts.extensions ?? client.getDefaultExtensions(),
76 ignoreNodeModules: false,
77 },
78 );
79
80 client.setOptions(opts);
81 };
82
83 exports.revert = function revert() {
84 if (piratesRevert) piratesRevert();
85 };