-
Notifications
You must be signed in to change notification settings - Fork 411
Expand file tree
/
Copy pathextract.ts
More file actions
275 lines (244 loc) · 8.59 KB
/
extract.ts
File metadata and controls
275 lines (244 loc) · 8.59 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
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
/* eslint-disable no-param-reassign */
/**
* This is an entry point for styles extraction.
* On enter, It:
* - traverse the code using visitors (TaggedTemplateExpression, ImportDeclaration)
* - schedule evaluation of lazy dependencies (those who are not simple expressions //TODO does they have it's name?)
* - let templateProcessor to save evaluated values in babel state as `replacements`.
* On exit, It:
* - store result of extraction in babel's file metadata
*/
import type { Node, Program, Expression } from '@babel/types';
import type { NodePath, Scope, Visitor } from '@babel/traverse';
import { expression, statement } from '@babel/template';
import generator from '@babel/generator';
import preprocess from '../preprocess';
import evaluate from './evaluators';
import getTemplateProcessor from './evaluators/templateProcessor';
import Module from './module';
import type {
State,
StrictOptions,
LazyValue,
ExpressionValue,
ValueCache,
} from './types';
import { ValueType } from './types';
import CollectDependencies from './visitors/CollectDependencies';
import DetectStyledImportName from './visitors/DetectStyledImportName';
import GenerateClassNames from './visitors/GenerateClassNames';
import { debug } from './utils/logger';
import type { Core } from './babel';
function isLazyValue(v: ExpressionValue): v is LazyValue {
return v.kind === ValueType.LAZY;
}
function isNodePath<T extends Node>(obj: NodePath<T> | T): obj is NodePath<T> {
return 'node' in obj && obj?.node !== undefined;
}
function findFreeName(scope: Scope, name: string): string {
// By default `name` is used as a name of the function …
let nextName = name;
let idx = 0;
while (scope.hasBinding(nextName, false)) {
// … but if there is an already defined variable with this name …
// … we are trying to use a name like wrap_N
idx += 1;
nextName = `wrap_${idx}`;
}
return nextName;
}
function unwrapNode<T extends Node>(
item: NodePath<T> | T | string
): T | string {
if (typeof item === 'string') {
return item;
}
return isNodePath(item) ? item.node : item;
}
// All exported values will be wrapped with this function
const expressionWrapperTpl = statement(`
const %%wrapName%% = (fn) => {
try {
return fn();
} catch (e) {
return e;
}
};
`);
const expressionTpl = expression(`%%wrapName%%(() => %%expression%%)`);
const exportsLinariaPrevalTpl = statement(
`exports.__linariaPreval = %%expressions%%`
);
function addLinariaPreval(
{ types: t }: Core,
path: NodePath<Program>,
lazyDeps: Array<Expression | string>
): Program {
// Constant __linariaPreval with all dependencies
const wrapName = findFreeName(path.scope, '_wrap');
const statements = [
expressionWrapperTpl({ wrapName }),
exportsLinariaPrevalTpl({
expressions: t.arrayExpression(
lazyDeps.map((expression) => expressionTpl({ expression, wrapName }))
),
}),
];
const programNode = path.node;
return t.program(
[...programNode.body, ...statements],
programNode.directives,
programNode.sourceType,
programNode.interpreter
);
}
function injectStyleAst({ types: t }: Core, css: string) {
const createStyleElement = t.variableDeclaration('const', [
t.variableDeclarator(
t.identifier('style'),
t.callExpression(
t.memberExpression(
t.identifier('document'),
t.identifier('createElement')
),
[t.stringLiteral('style')]
)
),
]);
const assignInnerHTML = t.expressionStatement(
t.assignmentExpression(
'=',
t.memberExpression(t.identifier('style'), t.identifier('innerHTML')),
t.stringLiteral(css)
)
);
const appendToDOM = t.expressionStatement(
t.callExpression(
t.memberExpression(
t.memberExpression(t.identifier('document'), t.identifier('head')),
t.identifier('appendChild')
),
[t.identifier('style')]
)
);
return t.ifStatement(
t.binaryExpression(
'!==',
t.unaryExpression('typeof', t.identifier('document')),
t.stringLiteral('undefined')
),
t.blockStatement([createStyleElement, assignInnerHTML, appendToDOM])
);
}
export default function extract(
babel: Core,
options: StrictOptions
): { visitor: Visitor<State> } {
const process = getTemplateProcessor(babel, options);
return {
visitor: {
Program: {
enter(path: NodePath<Program>, state: State) {
// Collect all the style rules from the styles we encounter
state.queue = [];
state.rules = {};
state.index = -1;
state.dependencies = [];
state.replacements = [];
debug('extraction:start', state.file.opts.filename);
// Invalidate cache for module evaluation to get fresh modules
Module.invalidate();
// We need our transforms to run before anything else
// So we traverse here instead of a in a visitor
path.traverse({
ImportDeclaration: (p) => DetectStyledImportName(babel, p, state),
TaggedTemplateExpression: (p) => {
GenerateClassNames(babel, p, state, options);
CollectDependencies(babel, p, state, options);
},
});
const lazyDeps = state.queue.reduce(
(acc, { expressionValues: values }) => {
acc.push(...values.filter(isLazyValue));
return acc;
},
[] as LazyValue[]
);
const expressionsToEvaluate = lazyDeps.map((v) => unwrapNode(v.ex));
const originalLazyExpressions = lazyDeps.map((v) =>
unwrapNode(v.originalEx)
);
debug('lazy-deps:count', lazyDeps.length);
let lazyValues: any[] = [];
if (expressionsToEvaluate.length > 0) {
debug(
'lazy-deps:original-expressions-list',
originalLazyExpressions.map((node) =>
typeof node !== 'string' ? generator(node).code : node
)
);
debug(
'lazy-deps:expressions-to-eval-list',
expressionsToEvaluate.map((node) =>
typeof node !== 'string' ? generator(node).code : node
)
);
const program = addLinariaPreval(
babel,
path,
expressionsToEvaluate
);
const { code } = generator(program);
debug('lazy-deps:evaluate', '');
try {
const evaluation = evaluate(
code,
state.file.opts.filename,
options
);
debug('lazy-deps:sub-files', evaluation.dependencies);
state.dependencies.push(...evaluation.dependencies);
lazyValues = evaluation.value.__linariaPreval || [];
debug('lazy-deps:values', evaluation.value.__linariaPreval);
} catch (e) {
throw new Error(
'An unexpected runtime error ocurred during dependencies evaluation: \n' +
e.stack +
'\n\nIt may happen when your code or third party module is invalid or uses identifiers not available in Node environment, eg. window. \n' +
'Note that line numbers in above stack trace will most likely not match, because Linaria needed to transform your code a bit.\n'
);
}
}
const valueCache: ValueCache = new Map();
originalLazyExpressions.forEach((key, idx) =>
valueCache.set(key, lazyValues[idx])
);
state.queue.forEach((item) => process(item, state, valueCache));
},
exit(path: NodePath<Program>, state: State) {
if (Object.keys(state.rules).length) {
// Store the result as the file metadata under linaria key
state.file.metadata.linaria = {
rules: state.rules,
replacements: state.replacements,
dependencies: state.dependencies,
};
if (options.injectStyleTags) {
const { cssText } = preprocess(state.rules, {
filename: state.file.opts.filename,
preprocessor:
options.injectStyleTags === true
? undefined
: options.injectStyleTags.preprocessor,
});
path.pushContainer('body', injectStyleAst(babel, cssText));
}
}
// Invalidate cache for module evaluation when we're done
Module.invalidate();
debug('extraction:end', state.file.opts.filename);
},
},
},
};
}