index.js
9.93 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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"use strict";
const p = require('path');
const resolve = require('resolve'); // const printAST = require('ast-pretty-print')
const macrosRegex = /[./]macro(\.c?js)?$/;
const testMacrosRegex = v => macrosRegex.test(v); // https://stackoverflow.com/a/32749533/971592
class MacroError extends Error {
constructor(message) {
super(message);
this.name = 'MacroError';
/* istanbul ignore else */
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else if (!this.stack) {
this.stack = new Error(message).stack;
}
}
}
let _configExplorer = null;
function getConfigExplorer() {
return _configExplorer = _configExplorer || // Lazy load cosmiconfig since it is a relatively large bundle
require('cosmiconfig').cosmiconfigSync('babel-plugin-macros', {
searchPlaces: ['package.json', '.babel-plugin-macrosrc', '.babel-plugin-macrosrc.json', '.babel-plugin-macrosrc.yaml', '.babel-plugin-macrosrc.yml', '.babel-plugin-macrosrc.js', 'babel-plugin-macros.config.js'],
packageProp: 'babelMacros'
});
}
function createMacro(macro, options = {}) {
if (options.configName === 'options') {
throw new Error(`You cannot use the configName "options". It is reserved for babel-plugin-macros.`);
}
macroWrapper.isBabelMacro = true;
macroWrapper.options = options;
return macroWrapper;
function macroWrapper(args) {
const {
source,
isBabelMacrosCall
} = args;
if (!isBabelMacrosCall) {
throw new MacroError(`The macro you imported from "${source}" is being executed outside the context of compilation with babel-plugin-macros. ` + `This indicates that you don't have the babel plugin "babel-plugin-macros" configured correctly. ` + `Please see the documentation for how to configure babel-plugin-macros properly: ` + 'https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/docs/user.md');
}
return macro(args);
}
}
function nodeResolvePath(source, basedir) {
return resolve.sync(source, {
basedir,
extensions: ['.js', '.ts', '.tsx', '.mjs', '.cjs', '.jsx'],
// This is here to support the package being globally installed
// read more: https://github.com/kentcdodds/babel-plugin-macros/pull/138
paths: [p.resolve(__dirname, '../../')]
});
}
function macrosPlugin(babel, // istanbul doesn't like the default of an object for the plugin options
// but I think older versions of babel didn't always pass options
// istanbul ignore next
{
require: _require = require,
resolvePath = nodeResolvePath,
isMacrosName = testMacrosRegex,
...options
} = {}) {
function interopRequire(path) {
// eslint-disable-next-line import/no-dynamic-require
const o = _require(path);
return o && o.__esModule && o.default ? o.default : o;
}
return {
name: 'macros',
visitor: {
Program(progPath, state) {
progPath.traverse({
ImportDeclaration(path) {
const isMacros = looksLike(path, {
node: {
source: {
value: v => isMacrosName(v)
}
}
});
if (!isMacros) {
return;
}
const imports = path.node.specifiers.map(s => ({
localName: s.local.name,
importedName: s.type === 'ImportDefaultSpecifier' ? 'default' : s.imported.name
}));
const source = path.node.source.value;
const result = applyMacros({
path,
imports,
source,
state,
babel,
interopRequire,
resolvePath,
options
});
if (!result || !result.keepImports) {
path.remove();
}
},
VariableDeclaration(path) {
const isMacros = child => looksLike(child, {
node: {
init: {
callee: {
type: 'Identifier',
name: 'require'
},
arguments: args => args.length === 1 && isMacrosName(args[0].value)
}
}
});
path.get('declarations').filter(isMacros).forEach(child => {
const imports = child.node.id.name ? [{
localName: child.node.id.name,
importedName: 'default'
}] : child.node.id.properties.map(property => ({
localName: property.value.name,
importedName: property.key.name
}));
const call = child.get('init');
const source = call.node.arguments[0].value;
const result = applyMacros({
path: call,
imports,
source,
state,
babel,
interopRequire,
resolvePath,
options
});
if (!result || !result.keepImports) {
child.remove();
}
});
}
});
}
}
};
} // eslint-disable-next-line complexity
function applyMacros({
path,
imports,
source,
state,
babel,
interopRequire,
resolvePath,
options
}) {
/* istanbul ignore next (pretty much only useful for astexplorer I think) */
const {
file: {
opts: {
filename = ''
}
}
} = state;
let hasReferences = false;
const referencePathsByImportName = imports.reduce((byName, {
importedName,
localName
}) => {
const binding = path.scope.getBinding(localName);
byName[importedName] = binding.referencePaths;
hasReferences = hasReferences || Boolean(byName[importedName].length);
return byName;
}, {});
const isRelative = source.indexOf('.') === 0;
const requirePath = resolvePath(source, p.dirname(getFullFilename(filename)));
const macro = interopRequire(requirePath);
if (!macro.isBabelMacro) {
throw new Error(`The macro imported from "${source}" must be wrapped in "createMacro" ` + `which you can get from "babel-plugin-macros". ` + `Please refer to the documentation to see how to do this properly: https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/docs/author.md#writing-a-macro`);
}
const config = getConfig(macro, filename, source, options);
let result;
try {
/**
* Other plugins that run before babel-plugin-macros might use path.replace, where a path is
* put into its own replacement. Apparently babel does not update the scope after such
* an operation. As a remedy, the whole scope is traversed again with an empty "Identifier"
* visitor - this makes the problem go away.
*
* See: https://github.com/kentcdodds/import-all.macro/issues/7
*/
state.file.scope.path.traverse({
Identifier() {}
});
result = macro({
references: referencePathsByImportName,
source,
state,
babel,
config,
isBabelMacrosCall: true
});
} catch (error) {
if (error.name === 'MacroError') {
throw error;
}
error.message = `${source}: ${error.message}`;
if (!isRelative) {
error.message = `${error.message} Learn more: https://www.npmjs.com/package/${source.replace( // remove everything after package name
// @org/package/macro -> @org/package
// package/macro -> package
/^((?:@[^/]+\/)?[^/]+).*/, '$1')}`;
}
throw error;
}
return result;
}
function getConfigFromFile(configName, filename) {
try {
const loaded = getConfigExplorer().search(filename);
if (loaded) {
return {
options: loaded.config[configName],
path: loaded.filepath
};
}
} catch (e) {
return {
error: e
};
}
return {};
}
function getConfigFromOptions(configName, options) {
if (options.hasOwnProperty(configName)) {
if (options[configName] && typeof options[configName] !== 'object') {
// eslint-disable-next-line no-console
console.error(`The macro plugin options' ${configName} property was not an object or null.`);
} else {
return {
options: options[configName]
};
}
}
return {};
}
function getConfig(macro, filename, source, options) {
const {
configName
} = macro.options;
if (configName) {
const fileConfig = getConfigFromFile(configName, filename);
const optionsConfig = getConfigFromOptions(configName, options);
if (optionsConfig.options === undefined && fileConfig.options === undefined && fileConfig.error !== undefined) {
// eslint-disable-next-line no-console
console.error(`There was an error trying to load the config "${configName}" ` + `for the macro imported from "${source}. ` + `Please see the error thrown for more information.`);
throw fileConfig.error;
}
if (fileConfig.options !== undefined && optionsConfig.options !== undefined && typeof fileConfig.options !== 'object') {
throw new Error(`${fileConfig.path} specified a ${configName} config of type ` + `${typeof optionsConfig.options}, but the the macros plugin's ` + `options.${configName} did contain an object. Both configs must ` + `contain objects for their options to be mergeable.`);
}
return { ...optionsConfig.options,
...fileConfig.options
};
}
return undefined;
}
/*
istanbul ignore next
because this is hard to test
and not worth it...
*/
function getFullFilename(filename) {
if (p.isAbsolute(filename)) {
return filename;
}
return p.join(process.cwd(), filename);
}
function looksLike(a, b) {
return a && b && Object.keys(b).every(bKey => {
const bVal = b[bKey];
const aVal = a[bKey];
if (typeof bVal === 'function') {
return bVal(aVal);
}
return isPrimitive(bVal) ? bVal === aVal : looksLike(aVal, bVal);
});
}
function isPrimitive(val) {
// eslint-disable-next-line
return val == null || /^[sbn]/.test(typeof val);
}
module.exports = macrosPlugin;
Object.assign(module.exports, {
createMacro,
MacroError
});