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
333 lines (298 loc) · 9.94 KB
/
index.ts
File metadata and controls
333 lines (298 loc) · 9.94 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// This code is written to be performant, that's why we opted to ignore these linting issues
/* eslint-disable no-loop-func, no-continue */
import * as meriyah from 'meriyah';
import * as astring from 'astring';
import { basename } from 'path';
import { walk } from 'estree-walker';
import { AssignmentExpression, ExpressionStatement } from 'meriyah/dist/estree';
import { Syntax as n } from './syntax';
import {
generateRequireStatement,
generateAllExportsIterator,
generateExportMemberStatement,
generateExportStatement,
generateEsModuleSpecifier,
generateInteropRequire,
generateInteropRequireExpression,
} from './utils';
import { customGenerator } from './generator';
/**
* Converts esmodule code to commonjs code, built to be as fast as possible
*/
export function convertEsModule(code: string) {
const usedVarNames = [];
const getVarName = (name: string) => {
let usedName = name.replace(/[.-]/g, '');
while (usedVarNames.includes(usedName)) {
usedName += '_';
}
usedVarNames.push(usedName);
return usedName;
};
let program = meriyah.parseModule(code, { next: true });
let i = 0;
let addedSpecifier = false;
function addEsModuleSpecifier() {
if (addedSpecifier) {
return;
}
addedSpecifier = true;
program.body.unshift(generateEsModuleSpecifier());
i++;
}
let addedDefaultInterop = false;
function addDefaultInterop() {
if (addedDefaultInterop) {
return;
}
addedDefaultInterop = true;
program.body.push(generateInteropRequire());
}
for (; i < program.body.length; i++) {
const statement = program.body[i];
if (statement.type === n.ExportAllDeclaration) {
// export * from './test';
// TO:
// const _csb = require('./test');
// Object.keys(_csb).forEach(key => {
// if (key === 'default' || key === '__esModule')
// return;
// exports[key] = _csb[key])
// }
addEsModuleSpecifier();
const { source } = statement;
if (typeof source.value !== 'string') {
continue;
}
const varName = getVarName(`$csb__${basename(source.value, '.js')}`);
program.body[i] = generateRequireStatement(varName, source.value);
i++;
program.body.splice(i, 0, generateAllExportsIterator(varName));
} else if (statement.type === n.ExportNamedDeclaration) {
// export { a } from './test';
// TO:
// const _csb = require('./test');
// exports.a = _csb.a;
addEsModuleSpecifier();
if (statement.source) {
// export { ... } from ''
const { source } = statement;
if (typeof source.value !== 'string') {
continue;
}
const varName = getVarName(`$csb__${basename(source.value, '.js')}`);
program.body[i] = generateRequireStatement(varName, source.value);
i++;
statement.specifiers
.reverse()
.forEach((specifier: meriyah.ESTree.ExportSpecifier) => {
program.body.splice(
i,
0,
generateExportMemberStatement(
varName,
specifier.exported.name,
specifier.local.name
)
);
});
} else if (statement.declaration) {
// First remove the export statement
program.body[i] = statement.declaration;
let varName: string;
if (
statement.declaration.type === n.FunctionDeclaration ||
statement.declaration.type === n.ClassDeclaration
) {
// export function test() {}
varName = statement.declaration.id.name;
} else {
// export const a = {}
const declaration = statement.declaration as meriyah.ESTree.VariableDeclaration;
const foundDeclaration = declaration.declarations.find(
d => d.id.type === n.Identifier
) as { id: meriyah.ESTree.Identifier };
if (!foundDeclaration) {
continue;
}
varName = foundDeclaration.id.name;
}
i++;
program.body.splice(i, 0, generateExportStatement(varName, varName));
}
} else if (statement.type === n.ExportDefaultDeclaration) {
addEsModuleSpecifier();
// export default function() {}
// export default class A {}
const varName = getVarName(`$csb__default`);
// First remove the export statement
if (statement.declaration) {
if (statement.declaration.type === n.FunctionDeclaration) {
// @ts-ignore
statement.declaration.type = n.FunctionExpression;
} else if (statement.declaration.type === n.ClassDeclaration) {
// @ts-ignore
statement.declaration.type = n.ClassExpression;
}
const newDeclaration = statement.declaration as meriyah.ESTree.Expression;
// Create a var with the export
if (
statement.declaration.type === n.ClassExpression ||
statement.declaration.type === n.FunctionExpression
) {
if (!statement.declaration.id) {
// If the function or class has no name, we give it to it
statement.declaration.id = {
type: n.Identifier,
name: varName,
};
}
program.body[
i
] = statement.declaration as meriyah.ESTree.DeclarationStatement;
i++;
program.body.splice(
i,
0,
generateExportStatement(statement.declaration.id.name, 'default')
);
i++;
} else {
program.body[i] = {
type: n.VariableDeclaration,
kind: 'var' as 'var',
declarations: [
{
type: n.VariableDeclarator,
id: {
type: n.Identifier,
name: varName,
},
init: newDeclaration,
},
],
};
i++;
program.body.splice(
i,
0,
generateExportStatement(varName, 'default')
);
}
if (
newDeclaration.type === n.ClassDeclaration ||
newDeclaration.type === n.FunctionExpression
) {
// @ts-ignore Different libraries with the same types
program = walk(program, {
enter(node, parent, prop, index) {
if (node.type === n.AssignmentExpression) {
const { left } = node as AssignmentExpression;
if (
left.type === n.Identifier &&
left.name === newDeclaration.id.name
) {
this.replace({
type: n.ExpressionStatement,
expression: {
type: n.AssignmentExpression,
left: {
type: n.MemberExpression,
object: {
type: n.Identifier,
name: 'exports',
},
computed: false,
property: {
type: n.Identifier,
name: 'default',
},
},
operator: '=' as '=',
right: node,
},
} as ExpressionStatement);
this.skip();
}
}
},
});
}
}
} else if (statement.type === n.ImportDeclaration) {
// @ts-ignore Wrong typing in lib?
const source: meriyah.ESTree.Literal = statement.source;
if (typeof source.value !== 'string') {
continue;
}
const varName = getVarName(`$csb__${basename(source.value, '.js')}`);
// Create require statement instead of the import
program.body[i] = generateRequireStatement(varName, source.value);
i++;
statement.specifiers.reverse().forEach(specifier => {
let localName: string;
let importName: string;
if (specifier.type === n.ImportDefaultSpecifier) {
// import Test from 'test';
// const _test = require('test');
// var Test = interopRequireDefault(_test).default;
localName = specifier.local.name;
importName = 'default';
addDefaultInterop();
program.body.splice(
i,
0,
generateInteropRequireExpression(varName, localName)
);
return;
}
if (specifier.type === n.ImportSpecifier) {
// import {Test} from 'test';
// const _test = require('test');
// var Test = _test.Test;
localName = specifier.local.name;
importName = specifier.imported.name;
} else if (specifier.type === n.ImportNamespaceSpecifier) {
// import * as Test from 'test';
// const _test = require('test');
// var Test = _test;
localName = specifier.local.name;
importName = null;
}
program.body.splice(i, 0, {
type: n.VariableDeclaration,
kind: 'var' as 'var',
declarations: [
{
type: n.VariableDeclarator,
id: {
type: n.Identifier,
name: localName,
},
init: importName
? {
type: n.MemberExpression,
computed: false,
object: {
type: n.Identifier,
name: varName,
},
property: {
type: n.Identifier,
name: importName,
},
}
: {
type: n.Identifier,
name: varName,
},
},
],
});
});
}
}
return astring.generate(program as any, {
generator: customGenerator,
});
}