UNPKG

1.41 kBJavaScriptView Raw
1var traceur = require("traceur");
2var anonCnt = 0;
3
4module.exports = function(load) {
5 load.address = load.address || "anon" + (++anonCnt);
6
7 var Parser = traceur.syntax.Parser;
8 var SourceFile = traceur.syntax.SourceFile;
9
10 var parser = new Parser(new SourceFile(load.address, load.source));
11 var body = parser.parseModule();
12
13 return getImports(body);
14};
15
16// given a syntax tree, return the import list
17function getImports(moduleTree) {
18 var imports = [];
19
20 function addImport(name) {
21 if ([].indexOf.call(imports, name) == -1) {
22 imports.push(name);
23 }
24 }
25
26 traverse(moduleTree, function(node) {
27 // import {} from 'foo';
28 // export * from 'foo';
29 // export { ... } from 'foo';
30 if (node.type == "EXPORT_DECLARATION") {
31 if (node.declaration.moduleSpecifier) {
32 addImport(node.declaration.moduleSpecifier.token.processedValue);
33 }
34 }
35 else if (node.type == "IMPORT_DECLARATION") {
36 addImport(node.moduleSpecifier.token.processedValue);
37 }
38 });
39
40 return imports;
41}
42
43function traverse(object, iterator, parent, parentProperty) {
44 var key, child;
45
46 if (iterator(object, parent, parentProperty) === false) {
47 return;
48 }
49
50 for (key in object) {
51 if (!object.hasOwnProperty(key)) {
52 continue;
53 }
54 if (key == "location" || key == "type") {
55 continue;
56 }
57 child = object[key];
58 if (typeof child == "object" && child !== null) {
59 traverse(child, iterator, object, key);
60 }
61 }
62}
63