-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathindex.js
428 lines (380 loc) · 13.4 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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
* Module dependencies.
*/
var through = require('through')
, esprima = require('esprima')
, estraverse = require('estraverse')
, escodegen = require('escodegen')
, path = require('path')
, util = require('util')
, support = require('./support');
/**
* Transform AMD to CommonJS.
*
* This transform translates AMD modules into CommonJS modules. AMD modules
* are defined by calling the `define` function that is available as a free
* or global variable. The transform translates that call into traditional
* CommonJS require statements. Any value returned from the factory function
* is assigned to `module.exports`.
*
* After the transform is complete, Browserify will be able to parse and
* bundle the module as if it were a Node.js module.
*
* @param {String} file
* @return {Stream}
* @api public
*/
module.exports = function (file, options) {
var data = '';
var ext = path.extname(file);
options = options || {};
options.extensions = options.extensions || ['.js'];
var stream = through(write, end);
return stream;
function write(buf) { data += buf }
function end() {
var ast
, isAMD = false
, isUMD = false
, supportsCommonJs = false;
if (options.extensions.indexOf(ext.toLowerCase()) > -1) {
try {
ast = esprima.parse(data)
} catch (error) {
throw new Error('Error deamdifying ' + file + ': ' + error);
}
//console.log('-- ORIGINAL AST --');
//console.log(util.inspect(ast, false, null));
//console.log('------------------');
// TODO: Ensure that define is a free variable.
estraverse.replace(ast, {
enter: function(node) {
if (isCommonJsCheck(node)) {
supportsCommonJs = true;
}
else if (!supportsCommonJs && isAMDCheck(node)) {
node.test = { type: 'Literal', value: true, raw: 'true' };
node.alternate = null;
isUMD = true;
}
else if (isDefine(node) || isAMDRequire(node)) {
if (isUMD) {
isAMD = true;
return;
}
var parents = this.parents();
// Check that this module is an AMD module, as evidenced by invoking
// `define` or `require([], fn)` at the top-level. Any CommonJS or
// UMD modules are pass through unmodified.`
if (parents.length == 2 && parents[0].type == 'Program' && parents[1].type == 'ExpressionStatement') {
isAMD = true;
}
}
},
leave: function(node) {
var tnode;
if (isAMD && (isDefine(node) || isAMDRequire(node))) {
//define({})
if (node.arguments.length == 1 &&
node.arguments[0].type == 'ObjectExpression') {
// object literal
var obj = node.arguments[0];
tnode = generateCommonJsModuleForObject(obj);
this.break();
} else
//define(function(){})
if (node.arguments.length == 1 &&
node.arguments[0].type == 'FunctionExpression') {
var dependenciesIds = extractDependencyIdsFromFactory(node.arguments[0]),
factory = node.arguments[0];
tnode = generateCommonJsModuleForFactory(dependenciesIds, factory);
this.break();
} else
//define(variableName)
if (node.arguments.length == 1 &&
node.arguments[0].type == 'Identifier') {
// reference
var obj = node.arguments[0];
tnode = generateCommonJsModuleForObject(obj);
} else
//define([],function(){})
if (node.arguments.length == 2 &&
node.arguments[0].type == 'ArrayExpression' &&
(node.arguments[1].type == 'FunctionExpression' || node.arguments[1].type == 'Identifier')) {
var dependenciesIds = extractDependencyIdsFromArrayExpression(node.arguments[0], options.paths)
, factory = node.arguments[1];
tnode = generateCommonJsModuleForFactory(dependenciesIds, factory);
this.break();
} else
//define("a b c".split(' '), function(){})
if (node.arguments.length == 2 &&
node.arguments[0].type == 'CallExpression' &&
(node.arguments[1].type == 'FunctionExpression' || node.arguments[1].type == 'Identifier')) {
try {
var dependenciesCode = node.arguments[0]
, dependenciesIds = extractDependencyIdsFromCallExpression(dependenciesCode, options.paths)
, factory = node.arguments[1];
tnode = generateCommonJsModuleForFactory(dependenciesIds, factory);
this.break();
} catch(e) {
console.log("failed to evaluate dependencies:", dependenciesCode, e)
}
} else
//define('modulename',function(){})
if (node.arguments.length == 2 &&
node.arguments[0].type == 'Literal' &&
(node.arguments[1].type == 'FunctionExpression' || node.arguments[1].type == 'Identifier')) {
var dependenciesIds = extractDependencyIdsFromFactory(node.arguments[1])
, factory = node.arguments[1];
tnode = generateCommonJsModuleForFactory(dependenciesIds, factory);
this.break();
} else
//define('modulename', [], function(){})
if (node.arguments.length == 3 &&
node.arguments[0].type == 'Literal' &&
node.arguments[1].type == 'ArrayExpression' &&
(node.arguments[2].type == 'FunctionExpression' || node.arguments[2].type == 'Identifier')) {
var dependenciesIds = extractDependencyIdsFromArrayExpression(node.arguments[1], options.paths)
, factory = node.arguments[2];
tnode = generateCommonJsModuleForFactory(dependenciesIds, factory);
this.break();
} else
//define('modulename', "a b c".split(' '), function(){})
if (node.arguments.length == 3 &&
node.arguments[0].type == 'Literal' &&
node.arguments[1].type == 'CallExpression' &&
(node.arguments[2].type == 'FunctionExpression' || node.arguments[2].type == 'Identifier')) {
try {
var dependenciesCode = node.arguments[1]
, dependenciesIds = extractDependencyIdsFromCallExpression(dependenciesCode, options.paths)
, factory = node.arguments[2];
tnode = generateCommonJsModuleForFactory(dependenciesIds, factory);
this.break();
} catch(e) {
console.log("failed to evaluate dependencies:", dependenciesCode, e)
}
}
}
return tnode;
}
});
}
if (!isAMD) {
stream.queue(data);
stream.queue(null);
return;
}
//console.log('-- TRANSFORMED AST --');
//console.log(util.inspect(ast, false, null));
//console.log('---------------------');
var out = escodegen.generate(ast);
stream.queue(out);
stream.queue(null);
}
};
function generateCommonJsModuleForObject(obj) {
return { type: 'AssignmentExpression',
operator: '=',
left:
{ type: 'MemberExpression',
computed: false,
object: { type: 'Identifier', name: 'module' },
property: { type: 'Identifier', name: 'exports' } },
right: obj };
}
function extractDependencyIdsFromArrayExpression(dependencies, paths) {
return dependencies.elements.map(function(el) { return rewriteRequire(el.value, paths); });
}
function extractDependencyIdsFromCallExpression(callExpression, paths) {
var ids = eval(escodegen.generate(callExpression));
return ids.map(function(id) { return rewriteRequire(id, paths); });
}
function rewriteRequire(path, paths) {
var parts = path.split("/");
var module = parts[0];
if(paths && module in paths) {
var rest = parts.slice(1, parts.length);
var rewrittenModule = paths[module];
return [rewrittenModule].concat(rest).join("/")
} else {
return path;
}
}
function extractDependencyIdsFromFactory(factory) {
var parameters = factory.params.map(function(param){
if(param.type === 'Identifier') {
return param.name;
}
});
if(isCommonJsWrappingParameters(parameters)) {
return [];
} else {
return commonJsSpecialDependencies.slice(0, parameters.length);
}
}
function isCommonJsWrappingParameters(parameters) {
return parameters.length === commonJsSpecialDependencies.length
&& parameters[0] === commonJsSpecialDependencies[0]
&& parameters[1] === commonJsSpecialDependencies[1]
&& parameters[2] === commonJsSpecialDependencies[2];
}
function generateCommonJsModuleForFactory(dependenciesIds, factory) {
var program,
exportResult = factory.type !== 'FunctionExpression' || support.doesFactoryHaveReturn(factory);
if(dependenciesIds.length === 0 && !exportResult) {
return {
"type": "CallExpression",
"callee": factory,
"arguments": [
{ "type": "Identifier", "name": "require" },
{ "type": "Identifier", "name": "exports" },
{ "type": "Identifier", "name": "module" }
]
};
} else {
var importExpressions = [];
//build imports
var imports;
if(dependenciesIds.length > 0) {
buildDependencyExpressions(dependenciesIds).forEach(function(expressions){
importExpressions.push(expressions.importExpression);
});
}
var callFactoryWithImports = {
"type": "CallExpression",
"callee": factory,
"arguments": importExpressions
};
var body;
if(exportResult) {
//wrap with assignment
body = {
"type": "AssignmentExpression",
"operator": "=",
"left": {
"type": "MemberExpression",
"computed": false,
"object": {
"type": "Identifier",
"name": "module"
},
"property": {
"type": "Identifier",
"name": "exports"
}
},
"right": callFactoryWithImports
};
} else {
body = callFactoryWithImports;
}
return body;
}
}
//NOTE: this is the order as specified in RequireJS docs; don't changes
var commonJsSpecialDependencies = ['require', 'exports', 'module'];
function commonJsSpecialDependencyExpressionBuilder(dependencyId) {
if(commonJsSpecialDependencies.indexOf(dependencyId) !== -1) {
return {importExpression:{
"type": "Identifier",
"name": dependencyId
}
};
}
}
function defaultRequireDependencyExpressionBuilder(dependencyId) {
return {importExpression: {
"type": "CallExpression",
"callee": {
"type": "Identifier",
"name": "require"
},
"arguments": [
{
"type": "Literal",
"value": dependencyId
}
]
}};
}
function buildDependencyExpressions(dependencyIdList) {
var dependencyExpressionBuilders = [
commonJsSpecialDependencyExpressionBuilder,
defaultRequireDependencyExpressionBuilder
];
return dependencyIdList.map(function(dependencyId){
return dependencyExpressionBuilders.reduce(function(currentExpression, builder){
return currentExpression || builder(dependencyId);
}, null);
});
}
function buildVariableDeclaration(imports, loader) {
var declarations = [];
if (imports) {
declarations.push(imports);
}
declarations.push(loader);
return {
"type": "VariableDeclaration",
"declarations": declarations,
"kind": "var"
};
}
function isDefine(node) {
var callee = node.callee;
return callee
&& node.type == 'CallExpression'
&& callee.type == 'Identifier'
&& callee.name == 'define'
;
}
function isCommonJsCheck(node) {
if (typeof exports === 'object')
return node.type === 'IfStatement' &&
isTypeCheck(node.test);
function isTypeCheck(node) {
return node.type === 'BinaryExpression' &&
(node.operator === '===' || node.operator === '==') &&
isTypeof(node.left) &&
node.right.type === 'Literal' &&
node.right.value === 'object';
}
function isTypeof(node) {
return node.type === 'UnaryExpression' &&
node.operator === 'typeof' &&
node.argument.type === 'Identifier' &&
node.argument.name === 'exports';
}
}
function isAMDCheck(node) {
return node.type === 'IfStatement' &&
node.test.type === 'LogicalExpression' &&
isTypeCheck(node.test.left) &&
isAmdPropertyCheck(node.test.right);
function isTypeCheck(node) {
return node.type === 'BinaryExpression' &&
(node.operator === '===' || node.operator === '==') &&
isTypeof(node.left) &&
node.right.type === 'Literal' &&
node.right.value === 'function';
}
function isTypeof(node) {
return node.type === 'UnaryExpression' &&
node.operator === 'typeof' &&
node.argument.type === 'Identifier' &&
node.argument.name === 'define';
}
function isAmdPropertyCheck(node) {
return node.type === 'MemberExpression' &&
node.object.name === 'define' &&
node.property.name === 'amd';
}
}
function isAMDRequire(node) {
var callee = node.callee;
return callee
&& node.type == 'CallExpression'
&& callee.type == 'Identifier'
&& callee.name == 'require'
;
}