react-magnetic-di
Version:
Context driven dependency injection
86 lines (71 loc) • 2.7 kB
JavaScript
;
var PACKAGE_NAME = 'react-magnetic-di';
var PACKAGE_FUNCTION = 'di';
var isDiStatement = function isDiStatement(stm, spec) {
return stm.type === 'ExpressionStatement' && stm.expression && stm.expression.callee && stm.expression.callee.name === spec.name;
};
var isHookName = function isHookName(node) {
return /^use[A-Z0-9].*$/.test(node.name);
};
var isComponentName = function isComponentName(node) {
return !/^[a-z]/.test(node.name);
};
var isLocalVariable = function isLocalVariable(node, scope, diIdentifier) {
do {
// if we reach module/global scope then is not local
if (scope.type === 'module' || scope.type === 'global') return false;
var isLocal = scope.variables.some(function (v) {
return v.name === node.name;
});
if (isLocal) return true; // if we got to the scope containing di() and was not found in variables yet
// we presume it is not local
if (scope.references.some(function (r) {
return r.identifier.name === diIdentifier.name;
})) return false; // eslint-disable-next-line no-cond-assign
} while (scope = scope.upper);
return false;
};
var getDiIdentifier = function getDiIdentifier(node) {
var importSource = node.source.value;
var importSpecifier = node.specifiers.find(function (s) {
return s.imported && s.imported.name === PACKAGE_FUNCTION;
});
if (importSource.startsWith(PACKAGE_NAME) && importSpecifier) {
return importSpecifier.local;
}
};
var getDiStatements = function getDiStatements(node, diIdentifier) {
return (node.body || []).reduce(function (acc, statement) {
return isDiStatement(statement, diIdentifier) ? acc.concat(statement) : acc;
}, []);
};
var getParentDiBlock = function getParentDiBlock(node, diIdentifier) {
// eslint-disable-next-line no-cond-assign
while (node = node.parent) {
if (node.type === 'BlockStatement') {
if (getDiStatements(node, diIdentifier).length) return node;
}
}
return null;
};
var getParentDiStatements = function getParentDiStatements(node, diIdentifier) {
var parentBlock = getParentDiBlock(node, diIdentifier);
if (parentBlock) return getDiStatements(parentBlock, diIdentifier);
return [];
};
var getDiVars = function getDiVars(statements) {
return statements.reduce(function (acc, s) {
return acc.concat(s.expression.arguments);
}, []);
};
module.exports = {
isDiStatement: isDiStatement,
isHookName: isHookName,
isComponentName: isComponentName,
isLocalVariable: isLocalVariable,
getDiIdentifier: getDiIdentifier,
getDiStatements: getDiStatements,
getParentDiBlock: getParentDiBlock,
getParentDiStatements: getParentDiStatements,
getDiVars: getDiVars
};