index.js
2.71 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
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _helperPluginUtils = require("@babel/helper-plugin-utils");
var _core = require("@babel/core");
var _helperAnnotateAsPure = _interopRequireDefault(require("@babel/helper-annotate-as-pure"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = (0, _helperPluginUtils.declare)((api, options) => {
api.assertVersion(7);
const {
allowMutablePropsOnTags
} = options;
if (allowMutablePropsOnTags != null && !Array.isArray(allowMutablePropsOnTags)) {
throw new Error(".allowMutablePropsOnTags must be an array, null, or undefined.");
}
const HOISTED = new WeakSet();
const immutabilityVisitor = {
enter(path, state) {
const stop = () => {
state.isImmutable = false;
path.stop();
};
if (path.isJSXClosingElement()) {
path.skip();
return;
}
if (path.isJSXIdentifier({
name: "ref"
}) && path.parentPath.isJSXAttribute({
name: path.node
})) {
return stop();
}
if (path.isJSXIdentifier() || path.isIdentifier() || path.isJSXMemberExpression()) {
return;
}
if (!path.isImmutable()) {
if (path.isPure()) {
const expressionResult = path.evaluate();
if (expressionResult.confident) {
const {
value
} = expressionResult;
const isMutable = !state.mutablePropsAllowed && value && typeof value === "object" || typeof value === "function";
if (!isMutable) {
path.skip();
return;
}
} else if (_core.types.isIdentifier(expressionResult.deopt)) {
return;
}
}
stop();
}
}
};
return {
name: "transform-react-constant-elements",
visitor: {
JSXElement(path) {
if (HOISTED.has(path.node)) return;
HOISTED.add(path.node);
const state = {
isImmutable: true
};
if (allowMutablePropsOnTags != null) {
let namePath = path.get("openingElement.name");
while (namePath.isJSXMemberExpression()) {
namePath = namePath.get("property");
}
const elementName = namePath.node.name;
state.mutablePropsAllowed = allowMutablePropsOnTags.indexOf(elementName) > -1;
}
path.traverse(immutabilityVisitor, state);
if (state.isImmutable) {
const hoisted = path.hoist();
if (hoisted) {
(0, _helperAnnotateAsPure.default)(hoisted);
}
}
}
}
};
});
exports.default = _default;