-
Notifications
You must be signed in to change notification settings - Fork 37
/
index.js
378 lines (308 loc) · 9.65 KB
/
index.js
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
var os = require('os');
var falafel = require('falafel');
var jsx = require('acorn-jsx');
var acorn = require('acorn');
var beautify = require('js-beautify').js_beautify;
module.exports = convert;
var JSXParser = acorn.Parser.extend(jsx());
/**
* Converts some code from AMD to ES6
* @param {string} source
* @param {object} [options]
* @returns {string}
*/
function convert (source, options) {
options = options || {};
var dependenciesMap = {};
var syncRequires = [];
var requiresWithSideEffects = [];
var mainCallExpression = null;
var result = falafel(source, {
parser: {
parse: JSXParser.parse.bind(JSXParser)
},
ecmaVersion: 9
}, function (node) {
if (isNamedDefine(node)) {
throw new Error('Found a named define - this is not supported.');
}
if (isDefineUsingIdentifier(node)) {
throw new Error('Found a define using a variable as the callback - this is not supported.');
}
if (isModuleDefinition(node)) {
if (mainCallExpression) {
throw new Error('Found multiple module definitions in one file.');
}
mainCallExpression = node;
}
else if (isSyncRequire(node)) {
syncRequires.push(node);
}
else if (isRequireWithNoCallback(node)) {
requiresWithSideEffects.push(node);
}
else if (isRequireWithDynamicModuleName(node)) {
throw new Error('Dynamic module names are not supported.');
}
if (isUseStrict(node)) {
node.parent.update('');
}
});
// no module definition found - return source untouched
if (!mainCallExpression) {
return source;
}
var moduleDeps = mainCallExpression.arguments.length > 1 ? mainCallExpression.arguments[0] : null;
var moduleFunc = mainCallExpression.arguments[mainCallExpression.arguments.length > 1 ? 1 : 0];
var hasDeps = moduleDeps && moduleDeps.elements.length > 0;
if (hasDeps) {
var modulePaths = moduleDeps.elements.map(function (node) {
return node.raw;
});
var importNames = moduleFunc.params.map(function (param) {
if (param.type === 'ObjectPattern') {
return source.slice(param.start, param.end);
}
return param.name;
});
extend(dependenciesMap, modulePaths.reduce(function (obj, path, index) {
obj[path] = importNames[index] || null;
return obj;
}, {}));
}
syncRequires.forEach(function (node) {
var moduleName = node.arguments[0].raw;
// if no import name assigned then create one
if (!dependenciesMap[moduleName]) {
dependenciesMap[moduleName] = makeImportName(node.arguments[0].value);
}
// replace with the import name
node.update(dependenciesMap[moduleName]);
});
requiresWithSideEffects.forEach(function (node) {
// get the module names
var moduleNames = node.arguments[0].elements.map(function (node) {
return node.value;
});
// make sure these modules are imported
moduleNames.forEach(function (moduleName) {
if (!dependenciesMap.hasOwnProperty(moduleName)) {
dependenciesMap[moduleName] = null;
}
});
// remove node
node.parent.update('');
});
// start with import statements
var moduleCode = getImportStatements(dependenciesMap);
// add modules code
moduleCode += getModuleCode(moduleFunc);
// fix indentation
if (options.beautify) {
moduleCode = beautify(moduleCode, { indent_size: options.indent });
// jsbeautify doesn't understand es6 module syntax yet
moduleCode = moduleCode.replace(/export[\s\S]default[\s\S]/, 'export default ');
}
// update the node with the new es6 code
mainCallExpression.parent.update(moduleCode);
return result.toString();
}
/**
* Takes an object where the keys are module paths and the values are
* the import names and returns the import statements as a string.
* @param {object} dependencies
* @returns {string}
*/
function getImportStatements (dependencies) {
var statements = [];
for (var key in dependencies) {
if (!dependencies[key]) {
statements.push('import ' + key + ';');
}
else {
statements.push('import ' + dependencies[key] + ' from ' + key + ';');
}
}
return statements.join(os.EOL);
}
/**
* Updates the return statement of a FunctionExpression to be an 'export default'.
* @param {object} functionExpression
*/
function updateReturnStatement (functionExpression) {
functionExpression.body.body.forEach(function (node) {
if (node.type === 'ReturnStatement') {
node.update(node.source().replace(/\breturn\b/, 'export default'));
}
});
}
/**
*
* @param {object} moduleFuncNode
* @returns {string}
*/
function getModuleCode (moduleFuncNode) {
updateReturnStatement(moduleFuncNode);
var moduleCode = moduleFuncNode.body.source();
// strip '{' and '}' from beginning and end
moduleCode = moduleCode.substring(1);
moduleCode = moduleCode.substring(0, moduleCode.length - 1);
return moduleCode;
}
/**
* Takes a CallExpression node and returns a array that contains the types of each argument.
* @param {object} callExpression
* @returns {array}
*/
function getArgumentsTypes (callExpression) {
return callExpression.arguments.map(function (arg) {
return arg.type;
});
}
/**
* Returns true if the node is a require() or define() CallExpression.
* @param {object} node
* @returns {boolean}
*/
function isRequireOrDefine (node) {
return isRequire(node) || isDefine(node);
}
/**
* Returns true if this node represents a require() call.
* @param {object} node
* @returns {boolean}
*/
function isRequire (node) {
return node.type === 'CallExpression' && node.callee.name === 'require';
}
/**
* Returns true if this node represents a define() call.
* @param {object} node
* @returns {boolean}
*/
function isDefine (node) {
return node.type === 'CallExpression' && node.callee.name === 'define';
}
/**
* Returns true if arr1 is the same as arr2.
* @param {array} arr1
* @param {array} arr2
* @returns {boolean}
*/
function arrayEquals (arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
/**
* Returns true if node is a require() call where the module name is a literal.
* @param {object} node
* @returns {boolean}
*/
function isSyncRequire (node) {
return isRequire(node) &&
arrayEquals(getArgumentsTypes(node), ['Literal']);
}
/**
* Returns true if node is a require() call where the module name is not a literal.
* @param {object} node
* @returns {boolean}
*/
function isRequireWithDynamicModuleName(node) {
if (!isRequire(node)) {
return false;
}
var argTypes = getArgumentsTypes(node);
return argTypes.length === 1 && argTypes[argTypes.length - 1] !== 'Identifier';
}
/**
* Adds all properties in source to target.
* @param {object} target
* @param {object} source
*/
function extend (target, source) {
for (var key in source) {
target[key] = source[key];
}
}
/**
* Returns true if this node represents a module definition using either a require or define.
* @param {object} node
* @returns {boolean}
*/
function isModuleDefinition (node) {
if (!isRequireOrDefine(node)) {
return false;
}
var argTypes = getArgumentsTypes(node);
// eg. require(['a', 'b'])
if (arrayEquals(argTypes, ['ArrayExpression'])) {
return true;
}
// eg. require(['a', 'b'], function () {})
if (arrayEquals(argTypes, ['ArrayExpression', 'FunctionExpression'])) {
return true;
}
// eg. require(['a', 'b'], () => {})
if (arrayEquals(argTypes, ['ArrayExpression', 'ArrowFunctionExpression'])) {
return true;
}
// eg. require(function () {}) or define(function () {})
if (arrayEquals(argTypes, ['FunctionExpression'])) {
return true;
}
// eg. require(() => {}) or define(() => {})
if (arrayEquals(argTypes, ['ArrowFunctionExpression'])) {
return true;
}
}
/**
* Returns true if this node represents a call like require(['a', 'b']);
* @param {object} node
* @returns {boolean}
*/
function isRequireWithNoCallback (node) {
return isRequire(node) && arrayEquals(getArgumentsTypes(node), ['ArrayExpression']);
}
/**
* Returns true if node represents a named define eg. define('my-module', function () {})
* @param {object} node
* @returns {boolean}
*/
function isNamedDefine (node) {
return isDefine(node) && getArgumentsTypes(node)[0] === 'Literal';
}
/**
* Returns true if node represents a define call where the callback is an identifier eg. define(factoryFn);
* @param {object} node
* @returns {boolean}
*/
function isDefineUsingIdentifier(node) {
if (!isDefine(node)) {
return false;
}
var argTypes = getArgumentsTypes(node);
return argTypes[argTypes.length - 1] === 'Identifier';
}
/**
* Makes a new import name derived from the name of the module path.
* @param {string} moduleName
* @returns {string}
*/
function makeImportName (moduleName) {
return '$__' + moduleName.replace(/[^a-zA-Z]/g, '_');
}
/**
* Returns true if node represents a 'use strict'-statement
* @param {object} node
* @returns {boolean}
*/
function isUseStrict (node) {
return node.type === 'Literal' && node.value === 'use strict';
}