forked from facebook/create-react-app
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathplugins.js
272 lines (258 loc) · 7.75 KB
/
plugins.js
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
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
const babylon = require('babylon');
const traverse = require('babel-traverse').default;
const template = require('babel-template');
const generator = require('babel-generator').default;
const t = require('babel-types');
const { readFileSync } = require('fs');
const prettier = require('prettier');
const getPackageJson = require('read-pkg-up').sync;
const { dirname, isAbsolute } = require('path');
const semver = require('semver');
function applyPlugins(config, plugins, { path, paths }) {
const pluginPaths = plugins
.map(p => {
try {
return require.resolve(`react-scripts-plugin-${p}`);
} catch (e) {
return null;
}
})
.filter(e => e != null);
for (const pluginPath of pluginPaths) {
const { apply } = require(pluginPath);
config = apply(config, { path, paths });
}
return config;
}
function hasPlugin(plugin) {
try {
require.resolve(`react-scripts-plugin-${plugin}`);
return true;
} catch (e) {
return false;
}
}
function _getArrayValues(arr) {
const { elements } = arr;
return elements.map(e => {
if (e.type === 'StringLiteral') {
return e.value;
}
return e;
});
}
// arr: [[afterExt, strExt1, strExt2, ...], ...]
function pushExtensions({ config, ast }, arr) {
if (ast != null) {
traverse(ast, {
enter(path) {
const { type } = path;
if (type !== 'ArrayExpression') {
return;
}
const { key } = path.parent;
if (key == null || key.name !== 'extensions') {
return;
}
const { elements } = path.node;
const extensions = _getArrayValues(path.node);
for (const [after, ...exts] of arr) {
// Find the extension we want to add after
const index = extensions.findIndex(s => s === after);
if (index === -1) {
throw new Error(
`Unable to find extension ${after} in configuration.`
);
}
// Push the extensions into array in the order we specify
elements.splice(
index + 1,
0,
...exts.map(ext => t.stringLiteral(ext))
);
// Simulate into our local copy of the array to keep proper indices
extensions.splice(index + 1, 0, ...exts);
}
},
});
} else if (config != null) {
const { resolve: { extensions } } = config;
for (const [after, ...exts] of arr) {
// Find the extension we want to add after
const index = extensions.findIndex(s => s === after);
if (index === -1) {
throw new Error(`Unable to find extension ${after} in configuration.`);
}
// Push the extensions into array in the order we specify
extensions.splice(index + 1, 0, ...exts);
}
}
}
function pushExclusiveLoader({ config, ast }, testStr, loader) {
if (ast != null) {
traverse(ast, {
enter(path) {
const { type } = path;
if (type !== 'ArrayExpression') {
return;
}
const { key } = path.parent;
if (key == null || key.name !== 'oneOf') {
return;
}
const entries = _getArrayValues(path.node);
const afterIndex = entries.findIndex(entry => {
const { properties } = entry;
return (
properties.find(property => {
if (property.value.type !== 'RegExpLiteral') {
return false;
}
return property.value.pattern === testStr.slice(1, -1);
}) != null
);
});
if (afterIndex === -1) {
throw new Error('Unable to match pre-loader.');
}
path.node.elements.splice(afterIndex + 1, 0, loader);
},
});
} else if (config != null) {
const { module: { rules: [, { oneOf: rules }] } } = config;
const loaderIndex = rules.findIndex(
rule => rule.test.toString() === testStr
);
if (loaderIndex === -1) {
throw new Error('Unable to match pre-loader.');
}
rules.splice(loaderIndex + 1, 0, loader);
}
}
function ejectFile({ filename, code, existingDependencies }) {
if (filename != null) {
code = readFileSync(filename, 'utf8');
}
let ast = babylon.parse(code);
let plugins = [];
traverse(ast, {
enter(path) {
const { type } = path;
if (type === 'VariableDeclaration') {
const { node: { declarations: [{ id: { name }, init }] } } = path;
if (name !== 'base') {
return;
}
path.replaceWith(template('module.exports = RIGHT;')({ RIGHT: init }));
} else if (type === 'AssignmentExpression') {
const { node: { left, right } } = path;
if (left.type !== 'MemberExpression') {
return;
}
if (right.type !== 'CallExpression') {
return;
}
const { callee: { name }, arguments: args } = right;
if (name !== 'applyPlugins') {
return;
}
plugins = _getArrayValues(args[1]);
path.parentPath.remove();
}
},
});
let deferredTransforms = [];
const dependencies = new Map([...existingDependencies]);
const paths = new Set();
plugins.forEach(p => {
let path;
try {
path = require.resolve(`react-scripts-plugin-${p}`);
} catch (e) {
return;
}
paths.add(path);
const { pkg: pluginPackage } = getPackageJson({ cwd: dirname(path) });
for (const pkg of Object.keys(pluginPackage.dependencies)) {
const version = pluginPackage.dependencies[pkg];
if (dependencies.has(pkg)) {
const prev = dependencies.get(pkg);
if (
isAbsolute(version) ||
semver.satisfies(version.replace(/[\^~]/g, ''), prev)
) {
continue;
} else if (!semver.satisfies(prev.replace(/[\^~]/g, ''), version)) {
throw new Error(
`Dependency ${pkg}@${version} cannot be satisfied by colliding range ${pkg}@${prev}.`
);
}
}
dependencies.set(pkg, pluginPackage.dependencies[pkg]);
}
const pluginCode = readFileSync(path, 'utf8');
const pluginAst = babylon.parse(pluginCode);
traverse(pluginAst, {
enter(path) {
const { type } = path;
if (type !== 'CallExpression') {
return;
}
const { node: { callee: { name }, arguments: pluginArgs } } = path;
switch (name) {
case 'pushExtensions': {
const [, _exts] = pluginArgs;
const exts = _getArrayValues(_exts).map(entry =>
_getArrayValues(entry)
);
deferredTransforms.push(
pushExtensions.bind(undefined, { ast }, exts)
);
break;
}
case 'pushExclusiveLoader': {
const [, { value: testStr }, _loader] = pluginArgs;
deferredTransforms.push(
pushExclusiveLoader.bind(undefined, { ast }, testStr, _loader)
);
break;
}
default: {
// Not a call we care about
break;
}
}
},
});
});
// Execute 'em!
for (const transform of deferredTransforms) {
transform();
}
let { code: outCode } = generator(
ast,
{ sourceMaps: false, comments: true, retainLines: false },
code
);
outCode = prettier.format(outCode, {
singleQuote: true,
trailingComma: 'es5',
});
return { code: outCode, dependencies, paths };
}
module.exports = {
applyPlugins,
hasPlugin,
pushExtensions,
pushExclusiveLoader,
ejectFile,
};