1 | "use strict";
|
2 |
|
3 | const { Syntax } = require("estraverse-fb");
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | function leave(node, parent, uses) {
|
14 | switch (node.type) {
|
15 | case Syntax.MemberExpression:
|
16 | case Syntax.JSXMemberExpression:
|
17 | if (hasObjectIdentifier_(node) && !hasScope_(node, this.parents())) {
|
18 | const parents = this.parents()
|
19 | .concat(node)
|
20 | .reverse();
|
21 | const path = this.path()
|
22 | .concat("object")
|
23 | .reverse();
|
24 | const use = registerIdentifier_(node.object, parents, path);
|
25 | if (use) {
|
26 | uses.push(use);
|
27 | }
|
28 | }
|
29 | break;
|
30 | default:
|
31 | break;
|
32 | }
|
33 | }
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 | function hasObjectIdentifier_(node) {
|
42 | return !node.computed && isIdentifierType_(node.object.type);
|
43 | }
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 | function isIdentifierType_(type) {
|
51 | return type === Syntax.Identifier || type === Syntax.JSXIdentifier;
|
52 | }
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 | function hasScope_(node, parents) {
|
61 | const nodeName = node.object.name;
|
62 | parents = parents.slice();
|
63 | while ((node = parents.pop())) {
|
64 | switch (node.type) {
|
65 | case Syntax.FunctionExpression:
|
66 | case Syntax.FunctionDeclaration:
|
67 | if (node.params && node.params.some(param => param.name === nodeName)) {
|
68 | return true;
|
69 | }
|
70 | break;
|
71 | case Syntax.BlockStatement:
|
72 | if (
|
73 | node.body &&
|
74 | node.body.some(
|
75 | bodyPart =>
|
76 | bodyPart.type === Syntax.VariableDeclaration &&
|
77 | bodyPart.declarations.some(
|
78 | declaration =>
|
79 | declaration.type === Syntax.VariableDeclarator && declaration.id.name === nodeName
|
80 | )
|
81 | )
|
82 | ) {
|
83 | return true;
|
84 | }
|
85 | break;
|
86 | default:
|
87 | break;
|
88 | }
|
89 | }
|
90 | return false;
|
91 | }
|
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 | function registerIdentifier_(node, parents, path) {
|
101 | const namespace = [node.name];
|
102 | for (let i = 0; i < parents.length; i++) {
|
103 | const current = parents[i];
|
104 | const parentKey = path[i];
|
105 | switch (current.type) {
|
106 | case Syntax.MemberExpression:
|
107 | case Syntax.JSXMemberExpression:
|
108 | if (!current.computed && isIdentifierType_(current.property.type)) {
|
109 | namespace.push(current.property.name);
|
110 | } else {
|
111 | return createMemberObject_(namespace, current, parentKey);
|
112 | }
|
113 | break;
|
114 | default:
|
115 | return createMemberObject_(namespace, current, parentKey);
|
116 | }
|
117 | }
|
118 | return null;
|
119 | }
|
120 |
|
121 |
|
122 |
|
123 |
|
124 |
|
125 |
|
126 |
|
127 |
|
128 | function createMemberObject_(namespace, node, parentKey) {
|
129 | return {
|
130 | name: namespace,
|
131 | node,
|
132 | key: parentKey,
|
133 | };
|
134 | }
|
135 |
|
136 | module.exports = {
|
137 | leave,
|
138 | };
|