forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
193 lines (162 loc) · 5.5 KB
/
index.ts
File metadata and controls
193 lines (162 loc) · 5.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
/* eslint-disable import/default */
// @ts-ignore
import BabelWorker from 'worker-loader?publicPath=/&name=babel-transpiler.[hash:8].worker.js!./worker/index';
/* eslint-enable import/default */
import { isBabel7 } from '@codesandbox/common/lib/utils/is-babel-7';
import isESModule from 'sandbox/eval/utils/is-es-module';
import { measure, endMeasure } from '../../../utils/metrics';
import regexGetRequireStatements from './worker/simple-get-require-statements';
import getBabelConfig from './babel-parser';
import WorkerTranspiler from '../worker-transpiler';
import { LoaderContext } from '../../transpiled-module';
import Manager from '../../manager';
import delay from '../../../utils/delay';
import { shouldTranspile } from './check';
import { convertEsModule } from './convert-esmodule';
const global = window as any;
// Right now this is in a worker, but when we're going to allow custom plugins
// we need to move this out of the worker again, because the config needs
// to support custom plugins
class BabelTranspiler extends WorkerTranspiler {
worker: Worker;
constructor() {
super('babel-loader', BabelWorker, 3, { hasFS: true, preload: true });
}
startupWorkersInitialized = false;
async getWorker() {
while (typeof global.babelworkers === 'undefined') {
await delay(50); // eslint-disable-line
}
if (global.babelworkers.length === 0) {
return super.getWorker();
}
// We set these up in startup.js.
return global.babelworkers.pop();
}
doTranspilation(
code: string,
loaderContext: LoaderContext
): Promise<{ transpiledCode: string }> {
return new Promise((resolve, reject) => {
const { path } = loaderContext;
let newCode = code;
if (isESModule(newCode) && path.indexOf('/node_modules') > -1) {
try {
measure(`esconvert-${path}`);
newCode = convertEsModule(newCode);
endMeasure(`esconvert-${path}`, { silent: true });
} catch (e) {
console.warn(
`Error when converting '${path}' esmodule to commonjs: ${e.message}`
);
}
}
try {
// When we find a node_module that already is commonjs we will just get the
// dependencies from the file and return the same code. We get the dependencies
// with a regex since commonjs modules just have `require` and regex is MUCH
// faster than generating an AST from the code.
if (
(loaderContext.options.simpleRequire ||
path.startsWith('/node_modules')) &&
!shouldTranspile(newCode, path)
) {
regexGetRequireStatements(newCode).forEach(dependency => {
if (dependency.isGlob) {
loaderContext.addDependenciesInDirectory(dependency.path);
} else {
loaderContext.addDependency(dependency.path);
}
});
resolve({
transpiledCode: newCode,
});
return;
}
} catch (e) {
console.warn(
`Error when reading dependencies of '${path}' using quick method: '${e.message}'`
);
}
const configs = loaderContext.options.configurations;
const foundConfig = configs.babel && configs.babel.parsed;
const loaderOptions = loaderContext.options || {};
const dependencies =
(configs.package &&
configs.package.parsed &&
configs.package.parsed.dependencies) ||
{};
const devDependencies =
(configs.package &&
configs.package.parsed &&
configs.package.parsed.devDependencies) ||
{};
const isV7 =
loaderContext.options.isV7 || isBabel7(dependencies, devDependencies);
const hasMacros = Object.keys(dependencies).some(
d => d.indexOf('macro') > -1
);
const babelConfig = getBabelConfig(
foundConfig || (loaderOptions as any).config,
loaderOptions,
path,
isV7
);
this.queueTask(
{
code: newCode,
config: babelConfig,
path,
loaderOptions,
babelTranspilerOptions:
configs &&
configs.babelTranspiler &&
configs.babelTranspiler.parsed,
sandboxOptions: configs && configs.sandbox && configs.sandbox.parsed,
version: isV7 ? 7 : 6,
hasMacros,
},
loaderContext._module.getId(),
loaderContext,
(err, data) => {
if (err) {
loaderContext.emitError(err);
return reject(err);
}
return resolve(data);
}
);
});
}
async getTranspilerContext(manager: Manager): Promise<any> {
return new Promise(async resolve => {
const baseConfig = await super.getTranspilerContext(manager);
const babelTranspilerOptions =
manager.configurations &&
manager.configurations.babelTranspiler &&
manager.configurations.babelTranspiler.parsed;
this.queueTask(
{
type: 'get-babel-context',
babelTranspilerOptions,
},
'babelContext',
// @ts-ignore
{},
(err, data) => {
const { version, availablePlugins, availablePresets } = data;
resolve({
...baseConfig,
babelVersion: version,
availablePlugins,
availablePresets,
babelTranspilerOptions,
});
}
);
});
}
}
const transpiler = new BabelTranspiler();
export { BabelTranspiler };
export default transpiler;