creevey
Version:
Cross-browser screenshot testing tool for Storybook with fancy UI Runner
477 lines (398 loc) • 21.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.storyVisitor = exports.mdxVisitor = exports.previewVisitor = exports.commonVisitor = exports.FileType = void 0;
var t = _interopRequireWildcard(require("@babel/types"));
var _types2 = require("../../../types");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function isExports(path) {
const {
parentPath
} = path;
return path.node.name == 'exports' && path.scope.hasGlobal('exports') && !path.scope.hasBinding('exports') && parentPath.isMemberExpression() && parentPath.get('object').isIdentifier({
name: 'exports'
});
}
function isModuleExports(path) {
const {
parentPath
} = path;
return path.node.name == 'module' && path.scope.hasGlobal('module') && !path.scope.hasBinding('module') && parentPath.isMemberExpression() && parentPath.get('object').isIdentifier({
name: 'module'
}) && parentPath.get('property').isIdentifier({
name: 'exports'
});
}
function isObjectAssign(path) {
if (!(path !== null && path !== void 0 && path.isCallExpression())) return false;
const calleePath = path.get('callee');
return calleePath.isMemberExpression() && calleePath.get('object').isIdentifier({
name: 'Object'
}) && calleePath.get('property').isIdentifier({
name: 'assign'
});
}
function isTemplateBind(path) {
if (!(path !== null && path !== void 0 && path.isCallExpression())) return false;
const calleePath = path.get('callee');
return calleePath.isMemberExpression() && calleePath.get('object').isIdentifier() && calleePath.get('property').isIdentifier({
name: 'bind'
});
}
function findRootPath(path) {
return path.find(x => {
var _x$parentPath;
return (_x$parentPath = x.parentPath) === null || _x$parentPath === void 0 ? void 0 : _x$parentPath.isProgram();
});
}
function getPropertyPath(path, name) {
const propertyPath = path.get('properties').find(propPath => propPath.isObjectProperty() && t.isIdentifier(propPath.node.key, {
name
}));
return propertyPath !== null && propertyPath !== void 0 && propertyPath.isObjectProperty() ? propertyPath : undefined;
} // TODO Support import and process them
function getDeclaratorPath(path) {
if (path !== null && path !== void 0 && path.isIdentifier()) {
var _path$scope$getBindin;
const {
path: bindingPath
} = (_path$scope$getBindin = path.scope.getBinding(path.node.name)) !== null && _path$scope$getBindin !== void 0 ? _path$scope$getBindin : {};
if (bindingPath !== null && bindingPath !== void 0 && bindingPath.isVariableDeclarator() || bindingPath !== null && bindingPath !== void 0 && bindingPath.isFunctionDeclaration() || bindingPath !== null && bindingPath !== void 0 && bindingPath.isImportSpecifier()) return bindingPath;
}
}
function getKindObjectNodePath(path) {
if (path.isObjectExpression()) {
return getPropertyPath(path, 'title') ? path : undefined;
}
}
function getIdentifiers(path) {
return path.map(x => x.isFunctionDeclaration() ? x.get('id') : x.get('id')).map(idPath => idPath.isIdentifier() ? idPath : null).filter(_types2.isDefined);
}
function removeAllPropsExcept(path, propNames) {
const getPropName = propPath => propNames.find(names => {
const keyPath = propPath.isObjectProperty() ? propPath.get('key') : propPath.get('key');
if (!keyPath.isIdentifier()) return;
const name = Array.isArray(names) ? names[0] : names;
return typeof name == 'string' ? keyPath.isIdentifier({
name
}) : name(keyPath.node.name);
});
path.get('properties').forEach(propPath => {
if (propPath.isObjectProperty() || propPath.isObjectMethod()) {
const propName = getPropName(propPath);
if (!propName) return propPath.remove();
const restNames = Array.isArray(propName) ? propName.slice(1) : [];
if (propPath.isObjectProperty() && restNames.length != 0) removeAllExpressionPropsExcept(propPath === null || propPath === void 0 ? void 0 : propPath.get('value'), restNames);
if (propPath.isObjectMethod() && restNames[0] == 'storyName') replaceStoryFnToNoop(propPath);
} else if (propPath.isSpreadElement()) {
removeAllExpressionPropsExcept(propPath.get('argument'), propNames);
} else propPath.remove();
});
}
function removeAllPropAssignsExcept(propAssigns, propNames) {
for (const [assignPath, props] of propAssigns !== null && propAssigns !== void 0 ? propAssigns : []) {
const restNames = props.reduce((subPropNames, prop) => {
const propName = subPropNames.find(names => {
const name = Array.isArray(names) ? names[0] : names;
return typeof name == 'string' ? name == prop : name(prop);
});
if (Array.isArray(propName)) return propName.slice(1);
if (!propName) assignPath.remove();
return [];
}, propNames);
if (restNames.length != 0) removeAllExpressionPropsExcept(assignPath.get('right'), restNames);
}
}
function replaceStoryFnToNoop(path) {
if (path !== null && path !== void 0 && path.isArrowFunctionExpression()) path.get('body').replaceWith(t.blockStatement([]));else if (path !== null && path !== void 0 && path.isFunctionDeclaration()) path.get('body').replaceWith(t.blockStatement([]));else if (path !== null && path !== void 0 && path.isFunctionExpression()) path.get('body').replaceWith(t.blockStatement([]));else if (path !== null && path !== void 0 && path.isObjectMethod()) path.get('body').replaceWith(t.blockStatement([]));
}
function getAssignmentPathWithProps(refPath) {
const assignmentPath = refPath.findParent(parentPath => parentPath.isAssignmentExpression());
if (!(assignmentPath !== null && assignmentPath !== void 0 && assignmentPath.isAssignmentExpression())) return;
const props = [];
for (let propPath = refPath.parentPath; propPath != assignmentPath; propPath = propPath.parentPath) {
if (!propPath.isMemberExpression()) return;
const propNode = propPath.node.property;
if (!t.isIdentifier(propNode)) return;
props.push(propNode.name);
}
if (props.length != 0) return [assignmentPath, props];
}
function getPropertyAssignmentPaths(idPaths) {
const assignPaths = new Map();
idPaths.forEach(idPath => {
var _idPath$scope$getBind, _idPath$scope$getBind2;
const referencePaths = (_idPath$scope$getBind = (_idPath$scope$getBind2 = idPath.scope.getBinding(idPath.node.name)) === null || _idPath$scope$getBind2 === void 0 ? void 0 : _idPath$scope$getBind2.referencePaths) !== null && _idPath$scope$getBind !== void 0 ? _idPath$scope$getBind : [];
referencePaths.forEach(refPath => {
var _getAssignmentPathWit;
const [assignmentPath, props] = (_getAssignmentPathWit = getAssignmentPathWithProps(refPath)) !== null && _getAssignmentPathWit !== void 0 ? _getAssignmentPathWit : [];
if (assignmentPath && props) assignPaths.set(assignmentPath, props);
});
});
return assignPaths;
}
function removeAllExpressionPropsExcept(expressionPath, propNames) {
const resolvedDeclPath = getDeclaratorPath(expressionPath);
if (expressionPath !== null && expressionPath !== void 0 && expressionPath.isObjectExpression()) removeAllPropsExcept(expressionPath, propNames);else if (expressionPath !== null && expressionPath !== void 0 && expressionPath.isCallExpression()) {
if (isObjectAssign(expressionPath)) expressionPath.get('arguments').forEach(argumentPath => removeAllExpressionPropsExcept(argumentPath, storyProps));else if (isTemplateBind(expressionPath)) {
const calleePath = expressionPath.get('callee');
if (calleePath.isMemberExpression()) removeAllExpressionPropsExcept(calleePath.get('object'), propNames);
} else if (propNames[0] == 'storyName') {
expressionPath === null || expressionPath === void 0 ? void 0 : expressionPath.replaceWith(t.arrowFunctionExpression([], t.blockStatement([])));
}
} else if ((expressionPath !== null && expressionPath !== void 0 && expressionPath.isFunctionExpression() || expressionPath !== null && expressionPath !== void 0 && expressionPath.isArrowFunctionExpression()) && propNames[0] == 'storyName') replaceStoryFnToNoop(expressionPath);else if ((!resolvedDeclPath || resolvedDeclPath.isImportSpecifier()) && propNames[0] == 'storyName') expressionPath === null || expressionPath === void 0 ? void 0 : expressionPath.replaceWith(t.arrowFunctionExpression([], t.blockStatement([])));
if (resolvedDeclPath) {
if (!resolvedDeclPath.isImportSpecifier()) removeAllPropAssignsExcept(getPropertyAssignmentPaths(getIdentifiers([resolvedDeclPath])).entries(), propNames);
if (resolvedDeclPath.isVariableDeclarator()) removeAllExpressionPropsExcept(resolvedDeclPath.get('init'), propNames);
if (resolvedDeclPath.isFunctionDeclaration() && propNames[0] == 'storyName') replaceStoryFnToNoop(resolvedDeclPath);
}
}
function cleanUpStoriesOfCallChain(storiesOfPath) {
let callPath = storiesOfPath;
do {
const childCallPath = callPath;
const {
parentPath: memberPath
} = childCallPath;
callPath = memberPath.parentPath;
if (!memberPath.isMemberExpression()) return;
const propPath = memberPath.get('property');
if (!callPath.isCallExpression()) return;
if (propPath.isIdentifier({
name: 'add'
})) {
const [, storyPath, parametersPath] = callPath.get('arguments');
storyPath.replaceWith(t.arrowFunctionExpression([], t.blockStatement([])));
removeAllExpressionPropsExcept(parametersPath, ['creevey']);
} else if (propPath.isIdentifier({
name: 'addDecorator'
})) {
callPath.replaceWith(childCallPath);
} else if (propPath.isIdentifier({
name: 'addParameters'
})) {
const [parametersPath] = callPath.get('arguments');
removeAllExpressionPropsExcept(parametersPath, ['creevey']);
}
} while (callPath.parentPath != null);
}
function recursivelyRemoveUnreferencedBindings(path) {
const getUnreferencedBindings = () => {
path.scope.crawl();
return Object.values(path.scope.bindings).filter(binding => !binding.referenced || binding.referencePaths.every(refPath => refPath.find(x => x.node == binding.path.node)));
};
let bindings = getUnreferencedBindings();
do {
bindings.forEach(binding => !binding.path.removed && binding.path.remove());
} while ((bindings = getUnreferencedBindings()).length > 0);
}
function getUnvisitedRefs(paths, // eslint-disable-next-line @typescript-eslint/no-explicit-any
state) {
const rootPaths = [...new Set(paths.map(findRootPath).filter(_types2.isDefined))];
const bindings = new Set();
rootPaths.forEach(rootPath => {
state.visitedTopPaths.add(rootPath);
rootPath.traverse({
Identifier(identifierPath) {
const binding = identifierPath.scope.getBinding(identifierPath.node.name);
if ((binding === null || binding === void 0 ? void 0 : binding.scope) == rootPath.scope && !state.visitedBindings.has(binding)) {
bindings.add(binding);
state.visitedBindings.add(binding);
}
}
});
});
const refs = [].concat(...[...bindings].map(b => [b.path, ...b.referencePaths]));
return [...new Set(refs)];
}
let FileType;
exports.FileType = FileType;
(function (FileType) {
FileType[FileType["Invalid"] = -1] = "Invalid";
FileType[FileType["Entry"] = 0] = "Entry";
FileType[FileType["Preview"] = 1] = "Preview";
FileType[FileType["Story"] = 2] = "Story";
})(FileType || (exports.FileType = FileType = {}));
const commonVisitor = {
Program: {
enter(path) {
path.traverse({
TSDeclareFunction(path) {
path.remove();
},
TSTypeAliasDeclaration(path) {
path.remove();
},
TSInterfaceDeclaration(path) {
path.remove();
},
TSTypeAnnotation(path) {
path.remove();
},
TSAsExpression(path) {
path.replaceWith(path.get('expression'));
}
});
},
exit(path) {
if (this.fileType != FileType.Story && this.fileType != FileType.Preview) return;
recursivelyRemoveUnreferencedBindings(path);
path.traverse({
ImportDeclaration(path) {
if (path.node.specifiers.length == 0) path.remove();
}
});
let refs = [...this.visitedTopPaths];
while (refs.length > 0) {
refs = getUnvisitedRefs(refs, this);
}
path.get('body').filter(x => !this.visitedTopPaths.has(x)).forEach(x => x.remove());
}
}
};
exports.commonVisitor = commonVisitor;
const previewVisitor = {
ExportNamedDeclaration(namedPath) {
this.visitedTopPaths.add(namedPath);
const declarationPath = namedPath.get('declaration');
if (!declarationPath.isVariableDeclaration()) return;
declarationPath.get('declarations').forEach(declPath => {
if (!declPath.isVariableDeclarator()) return;
if (t.isIdentifier(declPath.node.id, {
name: 'decorators'
})) return declPath.remove();
if (t.isIdentifier(declPath.node.id, {
name: 'parameters'
})) {
removeAllExpressionPropsExcept(declPath.get('init'), ['creevey']);
}
});
},
CallExpression(rootCallPath) {
const rootPath = findRootPath(rootCallPath);
const calleePath = rootCallPath.get('callee');
if (calleePath.isIdentifier({
name: 'configure'
}) && rootPath) this.visitedTopPaths.add(rootPath);else if (calleePath.isIdentifier({
name: 'addDecorator'
})) rootCallPath.remove();else if (calleePath.isIdentifier({
name: 'addParameters'
})) {
const [argPath] = rootCallPath.get('arguments');
if (!argPath || !argPath.isObjectExpression()) return;
if (rootPath) this.visitedTopPaths.add(rootPath);
removeAllPropsExcept(argPath, ['creevey']);
}
}
};
exports.previewVisitor = previewVisitor;
const mdxVisitor = {
FunctionDeclaration(functionPath) {
var _functionPath$get$nod, _rootPath$scope$getBi, _rootPath$scope$getBi2;
const functionName = (_functionPath$get$nod = functionPath.get('id').node) === null || _functionPath$get$nod === void 0 ? void 0 : _functionPath$get$nod.name;
if (functionName != 'MDXContent') return;
const rootPath = findRootPath(functionPath);
const refs = (_rootPath$scope$getBi = rootPath === null || rootPath === void 0 ? void 0 : (_rootPath$scope$getBi2 = rootPath.scope.getBinding(functionName)) === null || _rootPath$scope$getBi2 === void 0 ? void 0 : _rootPath$scope$getBi2.referencePaths) !== null && _rootPath$scope$getBi !== void 0 ? _rootPath$scope$getBi : [];
refs.forEach(refPath => {
var _findRootPath;
return (_findRootPath = findRootPath(refPath)) === null || _findRootPath === void 0 ? void 0 : _findRootPath.remove();
});
rootPath === null || rootPath === void 0 ? void 0 : rootPath.remove();
}
};
exports.mdxVisitor = mdxVisitor;
const kindProps = ['title', 'id', ['parameters', 'creevey'], 'includeStories', 'excludeStories'];
const storyProps = ['storyName', ['story', 'name', ['parameters', 'creevey', 'docsOnly']], ['parameters', 'creevey', 'docsOnly']];
const exportsProps = [['default', ...kindProps], [name => name != 'default', ...storyProps]];
const storyVisitor = {
ExportDefaultDeclaration(defaultPath) {
const defaultDeclaration = defaultPath.get('declaration');
const declaratorPath = getDeclaratorPath(defaultDeclaration);
const kindPath = declaratorPath !== null && declaratorPath !== void 0 && declaratorPath.isVariableDeclarator() ? getKindObjectNodePath(declaratorPath.get('init')) : getKindObjectNodePath(defaultDeclaration);
if (!kindPath) return;
this.visitedTopPaths.add(defaultPath);
removeAllPropsExcept(kindPath, kindProps);
if (declaratorPath && !declaratorPath.isImportSpecifier()) removeAllPropAssignsExcept(getPropertyAssignmentPaths(getIdentifiers([declaratorPath])).entries(), kindProps);
},
ExportAllDeclaration(allPath) {
var _this$reexportedStori;
const request = allPath.get('source').node.value;
this.reexportedStories.set(this.resourcePath, ((_this$reexportedStori = this.reexportedStories.get(this.resourcePath)) !== null && _this$reexportedStori !== void 0 ? _this$reexportedStori : new Set()).add(request));
this.visitedTopPaths.add(allPath);
},
ExportNamedDeclaration(namedPath) {
this.visitedTopPaths.add(namedPath);
const declarationPath = namedPath.get('declaration');
let storyFnPropAssigns = new Map();
if (declarationPath.isVariableDeclaration()) {
const declarations = declarationPath.get('declarations');
declarations.map(x => x.get('init')).forEach(initPath => removeAllExpressionPropsExcept(initPath, storyProps));
storyFnPropAssigns = getPropertyAssignmentPaths(getIdentifiers(declarations));
} else if (declarationPath.isFunctionDeclaration()) {
replaceStoryFnToNoop(declarationPath);
storyFnPropAssigns = getPropertyAssignmentPaths(getIdentifiers([declarationPath]));
}
removeAllPropAssignsExcept(storyFnPropAssigns.entries(), storyProps);
},
CallExpression(rootCallPath) {
const rootPath = findRootPath(rootCallPath);
if (!rootCallPath.get('callee').isIdentifier({
name: 'storiesOf'
})) return;
if (rootPath) this.visitedTopPaths.add(rootPath);
if (rootPath !== null && rootPath !== void 0 && rootPath.isVariableDeclaration()) {
var _rootPath$get$find;
const storiesIdPath = (_rootPath$get$find = rootPath.get('declarations').find(decl => decl.get('init') == rootCallPath)) === null || _rootPath$get$find === void 0 ? void 0 : _rootPath$get$find.get('id');
if (storiesIdPath !== null && storiesIdPath !== void 0 && storiesIdPath.isIdentifier()) {
var _storiesIdPath$scope$, _storiesIdPath$scope$2;
((_storiesIdPath$scope$ = (_storiesIdPath$scope$2 = storiesIdPath.scope.getBinding(storiesIdPath.node.name)) === null || _storiesIdPath$scope$2 === void 0 ? void 0 : _storiesIdPath$scope$2.referencePaths) !== null && _storiesIdPath$scope$ !== void 0 ? _storiesIdPath$scope$ : []).forEach(cleanUpStoriesOfCallChain);
}
}
cleanUpStoriesOfCallChain(rootCallPath);
},
Identifier(identifierPath) {
if (isExports(identifierPath)) {
var _getAssignmentPathWit2;
const rootPath = findRootPath(identifierPath);
if (rootPath) this.visitedTopPaths.add(rootPath);
const [assignmentPath, props] = (_getAssignmentPathWit2 = getAssignmentPathWithProps(identifierPath)) !== null && _getAssignmentPathWit2 !== void 0 ? _getAssignmentPathWit2 : [];
if (assignmentPath && props) {
if (props.length == 1 && props[0] != 'default') {
const declaratorPath = getDeclaratorPath(assignmentPath.get('right'));
if (declaratorPath && !declaratorPath.isImportSpecifier()) {
removeAllPropAssignsExcept(getPropertyAssignmentPaths(getIdentifiers([declaratorPath])).entries(), storyProps);
} else {
const rightPath = assignmentPath.get('right');
if (isObjectAssign(rightPath)) {
rightPath.get('arguments').forEach(argumentPath => removeAllExpressionPropsExcept(argumentPath, storyProps));
} else rightPath.replaceWith(t.arrowFunctionExpression([], t.blockStatement([])));
}
} else removeAllPropAssignsExcept(new Map([[assignmentPath, props]]).entries(), exportsProps);
}
}
if (isModuleExports(identifierPath)) {
var _getAssignmentPathWit3;
const rootPath = findRootPath(identifierPath);
if (rootPath) this.visitedTopPaths.add(rootPath);
const [assignmentPath, props] = (_getAssignmentPathWit3 = getAssignmentPathWithProps(identifierPath)) !== null && _getAssignmentPathWit3 !== void 0 ? _getAssignmentPathWit3 : [];
if (assignmentPath && props) {
if (props.length == 1 && props[0] == 'exports') {
removeAllExpressionPropsExcept(assignmentPath.get('right'), exportsProps);
} else if (props.length == 2 && props[0] == 'exports' && props[1] != 'default') {
const declaratorPath = getDeclaratorPath(assignmentPath.get('right'));
if (declaratorPath && !declaratorPath.isImportSpecifier()) {
removeAllPropAssignsExcept(getPropertyAssignmentPaths(getIdentifiers([declaratorPath])).entries(), storyProps);
} else {
const rightPath = assignmentPath.get('right');
if (isObjectAssign(rightPath)) {
rightPath.get('arguments').forEach(argumentPath => removeAllExpressionPropsExcept(argumentPath, storyProps));
} else rightPath.replaceWith(t.arrowFunctionExpression([], t.blockStatement([])));
}
} else removeAllPropAssignsExcept(new Map([[assignmentPath, props]]).entries(), [['exports', ...exportsProps]]);
}
}
}
};
exports.storyVisitor = storyVisitor;