/
preeval.ts
209 lines (181 loc) · 5.45 KB
/
preeval.ts
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
/**
* This file is a babel preset used to transform files inside evaluators.
* It works the same as main `babel/extract` preset, but do not evaluate lazy dependencies.
*/
import type { BabelFile, NodePath, PluginObj } from '@babel/core';
import type { Identifier } from '@babel/types';
import { createCustomDebug } from '@linaria/logger';
import type { StrictOptions } from '@linaria/utils';
import {
JSXElementsRemover,
getFileIdx,
isUnnecessaryReactCall,
nonType,
removeWithRelated,
} from '@linaria/utils';
import type { Core } from '../babel';
import type { IPluginState } from '../types';
import processTemplateExpression from '../utils/processTemplateExpression';
export type PreevalOptions = Pick<
StrictOptions,
'classNameSlug' | 'displayName' | 'evaluate'
>;
const isGlobal = (id: NodePath<Identifier>): boolean => {
if (!nonType(id)) {
return false;
}
const { scope } = id;
const { name } = id.node;
return !scope.hasBinding(name) && scope.hasGlobal(name);
};
const forbiddenGlobals = new Set([
'XMLHttpRequest',
'clearImmediate',
'clearInterval',
'clearTimeout',
'document',
'fetch',
'localStorage',
'location',
'navigator',
'sessionStorage',
'setImmediate',
'setInterval',
'setTimeout',
'window',
]);
const isBrowserGlobal = (id: NodePath<Identifier>) => {
return forbiddenGlobals.has(id.node.name) && isGlobal(id);
};
const getPropertyName = (path: NodePath): string | null => {
if (path.isIdentifier()) {
return path.node.name;
}
if (path.isStringLiteral()) {
return path.node.value;
}
return null;
};
export default function preeval(
babel: Core,
options: PreevalOptions
): PluginObj<IPluginState> {
const { types: t } = babel;
return {
name: '@linaria/babel/preeval',
pre(file: BabelFile) {
const log = createCustomDebug('preeval', getFileIdx(file.opts.filename!));
log('start', 'Looking for template literals…');
this.processors = [];
file.path.traverse({
Identifier: (p) => {
processTemplateExpression(p, file.opts, options, (processor) => {
processor.doEvaltimeReplacement();
this.processors.push(processor);
});
},
});
log('start', 'Strip all JSX and browser related stuff');
file.path.traverse(
{
// JSX can be replaced with a dummy value,
// but we have to do it after we processed template tags.
CallExpression: {
enter(p) {
if (isUnnecessaryReactCall(p)) {
JSXElementsRemover(p);
}
},
},
JSXElement: {
enter: JSXElementsRemover,
},
JSXFragment: {
enter: JSXElementsRemover,
},
MemberExpression(p, state) {
const obj = p.get('object');
const prop = p.get('property');
if (!obj.isIdentifier({ name: 'window' })) {
return;
}
const name = getPropertyName(prop);
if (!name) {
return;
}
state.windowScoped.add(name);
// eslint-disable-next-line no-param-reassign
state.globals = state.globals.filter((id) => {
if (id.node.name === name) {
removeWithRelated([id]);
return false;
}
return true;
});
},
MetaProperty(p) {
// Remove all references to `import.meta`
removeWithRelated([p]);
},
Identifier(p, state) {
if (isBrowserGlobal(p)) {
if (
p.parentPath.isUnaryExpression({ operator: 'typeof' }) ||
p.parentPath.isTSTypeQuery()
) {
// Ignore `typeof window` expressions
return;
}
removeWithRelated([p]);
return;
}
if (state.windowScoped.has(p.node.name)) {
removeWithRelated([p]);
} else if (isGlobal(p)) {
state.globals.push(p);
}
},
},
{
globals: [] as NodePath<Identifier>[],
windowScoped: new Set<string>(),
}
);
},
visitor: {},
post(file: BabelFile) {
const log = createCustomDebug('preeval', getFileIdx(file.opts.filename!));
if (this.processors.length === 0) {
log('end', "We didn't find any Linaria template literals");
// We didn't find any Linaria template literals.
return;
}
this.file.metadata.linaria = {
processors: this.processors,
replacements: [],
rules: {},
dependencies: [],
};
const expressions: Identifier[] = this.processors.flatMap((processor) =>
processor.dependencies.map((dependency) => dependency.ex)
);
const linariaPreval = file.path.scope.getData('__linariaPreval');
if (!linariaPreval) {
const linariaExport = t.expressionStatement(
t.assignmentExpression(
'=',
t.memberExpression(
t.identifier('exports'),
t.identifier('__linariaPreval')
),
t.objectExpression(
expressions.map((ex) => t.objectProperty(ex, ex, false, true))
)
)
);
file.path.pushContainer('body', linariaExport);
}
log('end', '__linariaPreval has been added');
},
};
}