UNPKG

2.47 kBJavaScriptView Raw
1'use strict';
2
3var path = require('path');
4var _templateBuilder = require('@babel/template');
5
6function isAtom(t, callee, customAtomNames) {
7 if (customAtomNames === void 0) {
8 customAtomNames = [];
9 }
10 var atomNames = [].concat(atomFunctionNames, customAtomNames);
11 if (t.isIdentifier(callee) && atomNames.includes(callee.name)) {
12 return true;
13 }
14 if (t.isMemberExpression(callee)) {
15 var property = callee.property;
16 if (t.isIdentifier(property) && atomNames.includes(property.name)) {
17 return true;
18 }
19 }
20 return false;
21}
22var atomFunctionNames = ['abortableAtom', 'atom', 'atomFamily', 'atomWithDefault', 'atomWithHash', 'atomWithImmer', 'atomWithInfiniteQuery', 'atomWithMachine', 'atomWithMutation', 'atomWithObservable', 'atomWithProxy', 'atomWithQuery', 'atomWithReducer', 'atomWithReset', 'atomWithSubscription', 'atomWithStorage', 'atomWithStore', 'freezeAtom', 'loadable', 'selectAtom', 'splitAtom'];
23
24var templateBuilder = _templateBuilder.default || _templateBuilder;
25function debugLabelPlugin(_ref, options) {
26 var t = _ref.types;
27 return {
28 visitor: {
29 ExportDefaultDeclaration: function ExportDefaultDeclaration(nodePath, state) {
30 var node = nodePath.node;
31 if (t.isCallExpression(node.declaration) && isAtom(t, node.declaration.callee, options == null ? void 0 : options.customAtomNames)) {
32 var filename = state.filename || 'unknown';
33 var displayName = path.basename(filename, path.extname(filename));
34 if (displayName === 'index') {
35 displayName = path.basename(path.dirname(filename));
36 }
37 var buildExport = templateBuilder("\n const %%atomIdentifier%% = %%atom%%;\n export default %%atomIdentifier%%\n ");
38 var ast = buildExport({
39 atomIdentifier: t.identifier(displayName),
40 atom: node.declaration
41 });
42 nodePath.replaceWithMultiple(ast);
43 }
44 },
45 VariableDeclarator: function VariableDeclarator(path) {
46 if (t.isIdentifier(path.node.id) && t.isCallExpression(path.node.init) && isAtom(t, path.node.init.callee, options == null ? void 0 : options.customAtomNames)) {
47 path.parentPath.insertAfter(t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.identifier(path.node.id.name), t.identifier('debugLabel')), t.stringLiteral(path.node.id.name))));
48 }
49 }
50 }
51 };
52}
53
54module.exports = debugLabelPlugin;