Socket
Socket
Sign inDemoInstall

dependency-injection-cat

Package Overview
Dependencies
Maintainers
1
Versions
67
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

dependency-injection-cat - npm Package Compare versions

Comparing version 0.1.4 to 0.1.5

core/build-context/transformers/addGlobalContextInstance.js

15

core/bean-dependencies/registerMethodBeanDependencies.js

@@ -12,7 +12,6 @@ "use strict";

var BeanDependenciesRepository_1 = require("./BeanDependenciesRepository");
var getAllBeanNamesInContextByBeanDescriptor_1 = require("./getAllBeanNamesInContextByBeanDescriptor");
var registerMethodBeanDependencies = function (descriptor) {
var parameters = descriptor.node.parameters;
parameters.forEach(function (parameter) {
var qualifier = getQualifierValue(parameter, descriptor);
var qualifier = getQualifierValue(parameter);
var type = getParameterType_1.getParameterType(parameter);

@@ -28,3 +27,3 @@ if (type === null) {

node: parameter,
contextName: descriptor.contextName,
contextName: descriptor.contextDescriptor.name,
originalTypeName: type.originalTypeName,

@@ -39,3 +38,3 @@ type: type.typeId,

exports.registerMethodBeanDependencies = registerMethodBeanDependencies;
function getQualifierValue(parameter, descriptor) {
function getQualifierValue(parameter) {
var _a, _b;

@@ -85,10 +84,2 @@ var qualifierDecorators = (_b = (_a = parameter.decorators) === null || _a === void 0 ? void 0 : _a.filter(isParameterQualifierDecorator_1.isParameterQualifierDecorator)) !== null && _b !== void 0 ? _b : [];

}
var contextBeanNames = getAllBeanNamesInContextByBeanDescriptor_1.getAllBeanNamesInContextByBeanDescriptor(descriptor);
if (!contextBeanNames.includes(qualifierValue.text)) {
CompilationContext_1.CompilationContext.reportError({
node: decoratorExpression,
message: "Bean with qualifier \"" + qualifierValue.text + "\" does not exist in context",
});
return null;
}
return qualifierValue.text;

@@ -95,0 +86,0 @@ }

2

core/bean-dependencies/registerPropertyBeanDependencies.js

@@ -52,3 +52,3 @@ "use strict";

originalTypeName: parameterType.originalTypeName,
contextName: descriptor.contextName,
contextName: descriptor.contextDescriptor.name,
parameterName: parameter.name.getText(),

@@ -55,0 +55,0 @@ node: parameter,

@@ -16,3 +16,2 @@ "use strict";

var uuid_1 = require("uuid");
//Repository for return types of bean
var BeanRepository = /** @class */ (function () {

@@ -24,3 +23,3 @@ function BeanRepository() {

var descriptorWithId = __assign(__assign({}, descriptor), { id: uuid_1.v4() });
var contextName = descriptor.contextName, type = descriptor.type;
var contextName = descriptor.contextDescriptor.name, type = descriptor.type;
var contextMap = (_a = this.beanDescriptorRepository.get(contextName)) !== null && _a !== void 0 ? _a : null;

@@ -39,16 +38,12 @@ if (contextMap === null) {

this.beanNodeToBeanDescriptorMap.set(descriptorWithId.node, descriptorWithId);
var contextDescriptors = (_c = this.contextNameToBeanDescriptorsMap.get(descriptor.contextName)) !== null && _c !== void 0 ? _c : null;
var contextDescriptors = (_c = this.contextIdToBeanDescriptorsMap.get(descriptor.contextDescriptor.id)) !== null && _c !== void 0 ? _c : null;
if (contextDescriptors === null) {
contextDescriptors = [];
this.contextNameToBeanDescriptorsMap.set(descriptor.contextName, contextDescriptors);
this.contextIdToBeanDescriptorsMap.set(descriptor.contextDescriptor.id, contextDescriptors);
}
contextDescriptors.push(descriptorWithId);
};
BeanRepository.getBeanDescriptorsByType = function (contextName, type) {
var _a, _b;
return (_b = (_a = this.beanDescriptorRepository.get(contextName)) === null || _a === void 0 ? void 0 : _a.get(type)) !== null && _b !== void 0 ? _b : [];
};
BeanRepository.beanDescriptorRepository = new Map();
BeanRepository.idToBeanDescriptorMap = new Map();
BeanRepository.contextNameToBeanDescriptorsMap = new Map();
BeanRepository.contextIdToBeanDescriptorsMap = new Map();
BeanRepository.beanNodeToBeanDescriptorMap = new Map();

@@ -55,0 +50,0 @@ return BeanRepository;

@@ -18,4 +18,5 @@ "use strict";

var BeanRepository_1 = require("./BeanRepository");
//Only for not-global contexts
var checkIsAllBeansRegisteredInContext = function () {
ContextRepository_1.ContextRepository.repository.forEach(function (contextDescriptor) {
ContextRepository_1.ContextRepository.contextMap.forEach(function (contextDescriptor) {
var _a, _b, _c, _d;

@@ -74,3 +75,3 @@ var extendsHeritageClause = (_a = contextDescriptor.node.heritageClauses) === null || _a === void 0 ? void 0 : _a.find(function (clause) { return clause.token === typescript_1.default.SyntaxKind.ExtendsKeyword; });

var registeredBeanNames = (_d = (_c = BeanRepository_1.BeanRepository
.contextNameToBeanDescriptorsMap.get(contextDescriptor.name)) === null || _c === void 0 ? void 0 : _c.map(function (it) { return it.classMemberName; })) !== null && _d !== void 0 ? _d : [];
.contextIdToBeanDescriptorsMap.get(contextDescriptor.id)) === null || _c === void 0 ? void 0 : _c.map(function (it) { return it.classMemberName; })) !== null && _d !== void 0 ? _d : [];
var missingBeans = [];

@@ -77,0 +78,0 @@ requiredBeanProperties.forEach(function (requiredBeanProperty) {

@@ -10,3 +10,3 @@ "use strict";

var registerBeans = function () {
ContextRepository_1.ContextRepository.repository.forEach(function (contextDescriptor, contextName) {
ContextRepository_1.ContextRepository.contextMap.forEach(function (contextDescriptor, contextName) {
contextDescriptor.node.members.forEach(function (classElement) {

@@ -21,3 +21,13 @@ if (isMethodBean_1.isMethodBean(classElement)) {

});
ContextRepository_1.ContextRepository.globalContexts.forEach(function (contextDescriptor, contextId) {
contextDescriptor.node.members.forEach(function (classElement) {
if (isMethodBean_1.isMethodBean(classElement)) {
registerMethodBean_1.registerMethodBean(contextDescriptor, classElement);
}
if (isClassPropertyBean_1.isClassPropertyBean(classElement)) {
registerPropertyBean_1.registerPropertyBean(contextDescriptor, classElement);
}
});
});
};
exports.registerBeans = registerBeans;

@@ -45,3 +45,3 @@ "use strict";

classMemberName: classElement.name.getText(),
contextName: contextDescriptor.name,
contextDescriptor: contextDescriptor,
type: typeInfo.typeId,

@@ -48,0 +48,0 @@ originalTypeName: typeInfo.originalTypeName,

@@ -57,3 +57,3 @@ "use strict";

classMemberName: classElement.name.getText(),
contextName: contextDescriptor.name,
contextDescriptor: contextDescriptor,
type: typeInfo.typeId,

@@ -60,0 +60,0 @@ originalTypeName: typeInfo.originalTypeName,

@@ -20,13 +20,15 @@ "use strict";

var removeDIImports_1 = require("../ts-helpers/removeDIImports");
var addGlobalContextInstance_1 = require("./transformers/addGlobalContextInstance");
var buildContexts = function () {
clearOldContexts();
ContextRepository_1.ContextRepository.repository.forEach(function (contextDescriptor, contextName) {
ContextRepository_1.ContextRepository.contextMap.forEach(function (contextDescriptor, contextName) {
var globalContextIdsToAdd = [];
var transformers = [
relativizeImports_1.relativizeImports(),
addNecessaryImports_1.addNecessaryImports(),
addContextPool_1.addContextPool(contextDescriptor),
replaceExtendingFromCatContext_1.replaceExtendingFromCatContext(contextDescriptor),
replacePropertyBeans_1.replacePropertyBeans(),
transformMethodBeans_1.transformMethodBeans(),
replacePropertyBeans_1.replacePropertyBeans(globalContextIdsToAdd),
transformMethodBeans_1.transformMethodBeans(globalContextIdsToAdd),
removeDIImports_1.removeDIImports(),
addNecessaryImports_1.addNecessaryImports(globalContextIdsToAdd),
];

@@ -38,2 +40,18 @@ var sourceFile = contextDescriptor.node.getSourceFile();

});
ContextRepository_1.ContextRepository.globalContexts.forEach(function (contextDescriptor, contextId) {
var globalContextIdsToAdd = [];
var transformers = [
relativizeImports_1.relativizeImports(),
addGlobalContextInstance_1.addGlobalContextInstance(contextDescriptor),
replaceExtendingFromCatContext_1.replaceExtendingFromCatContext(contextDescriptor),
replacePropertyBeans_1.replacePropertyBeans(globalContextIdsToAdd),
transformMethodBeans_1.transformMethodBeans(globalContextIdsToAdd),
removeDIImports_1.removeDIImports(),
addNecessaryImports_1.addNecessaryImports(globalContextIdsToAdd),
];
var sourceFile = contextDescriptor.node.getSourceFile();
var result = typescript_1.default.transform(sourceFile, transformers);
var transformedSourceFile = result.transformed[0];
writeBuildedContext(contextDescriptor, transformedSourceFile);
});
};

@@ -40,0 +58,0 @@ exports.buildContexts = buildContexts;

@@ -29,10 +29,9 @@ "use strict";

var typescript_1 = __importStar(require("typescript"));
var BeanRepository_1 = require("../../bean/BeanRepository");
var constants_1 = require("../constants");
var addNecessaryImports_1 = require("./addNecessaryImports");
var beanConfigDeclarationName = "beanConfig" + constants_1.PRIVATE_TOKEN;
var createBeanConfigDeclaration_1 = require("./createBeanConfigDeclaration");
exports.CONTEXT_POOL_POSTFIX = "_POOL_" + constants_1.PRIVATE_TOKEN;
var addContextPool = function (contextDescriptor) {
return function () { return function (sourceFile) {
return typescript_1.default.factory.updateSourceFile(sourceFile, __spreadArray(__spreadArray(__spreadArray([], sourceFile.statements), createBeanConfigMapForContextPool(contextDescriptor)), [
return typescript_1.default.factory.updateSourceFile(sourceFile, __spreadArray(__spreadArray(__spreadArray([], sourceFile.statements), createBeanConfigDeclaration_1.createBeanConfigDeclaration(contextDescriptor)), [
createContextNamePool(contextDescriptor),

@@ -43,19 +42,8 @@ ]));

exports.addContextPool = addContextPool;
function createBeanConfigMapForContextPool(contextDescriptor) {
var _a;
var beanConfigDeclaration = typescript_1.factory.createVariableStatement(undefined, typescript_1.factory.createVariableDeclarationList([typescript_1.factory.createVariableDeclaration(typescript_1.factory.createIdentifier(beanConfigDeclarationName), undefined, typescript_1.factory.createTypeLiteralNode([typescript_1.factory.createIndexSignature(undefined, undefined, [typescript_1.factory.createParameterDeclaration(undefined, undefined, undefined, typescript_1.factory.createIdentifier('index'), undefined, typescript_1.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.StringKeyword), undefined)], typescript_1.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.AnyKeyword))]), typescript_1.factory.createObjectLiteralExpression([], false))], typescript_1.default.NodeFlags.Const));
var contextBeans = (_a = BeanRepository_1.BeanRepository.contextNameToBeanDescriptorsMap.get(contextDescriptor.name)) !== null && _a !== void 0 ? _a : [];
var mapFilling = contextBeans.map(function (it) {
return typescript_1.factory.createExpressionStatement(typescript_1.factory.createBinaryExpression(typescript_1.factory.createElementAccessExpression(typescript_1.factory.createIdentifier(beanConfigDeclarationName), typescript_1.factory.createStringLiteral(it.classMemberName)), typescript_1.factory.createToken(typescript_1.default.SyntaxKind.EqualsToken), typescript_1.factory.createObjectLiteralExpression([typescript_1.factory.createPropertyAssignment(typescript_1.factory.createIdentifier('scope'), typescript_1.factory.createStringLiteral(it.scope))], false)));
});
return __spreadArray([
beanConfigDeclaration
], mapFilling);
}
function createContextNamePool(contextDescriptor) {
return typescript_1.factory.createVariableStatement([typescript_1.factory.createModifier(typescript_1.default.SyntaxKind.ExportKeyword)], typescript_1.factory.createVariableDeclarationList([typescript_1.factory.createVariableDeclaration(typescript_1.factory.createIdentifier("" + contextDescriptor.name + exports.CONTEXT_POOL_POSTFIX), undefined, undefined, typescript_1.factory.createNewExpression(typescript_1.factory.createPropertyAccessExpression(typescript_1.factory.createIdentifier(addNecessaryImports_1.CONTEXT_POOL_IMPORT), typescript_1.factory.createIdentifier('ContextPool')), undefined, [
typescript_1.factory.createStringLiteral(contextDescriptor.name),
typescript_1.factory.createIdentifier(beanConfigDeclarationName),
typescript_1.factory.createIdentifier(createBeanConfigDeclaration_1.beanConfigDeclarationName),
typescript_1.factory.createIdentifier(contextDescriptor.name),
]))], typescript_1.default.NodeFlags.Const));
}

@@ -33,10 +33,13 @@ "use strict";

var upath_1 = __importDefault(require("upath"));
var lodash_1 = require("lodash");
var constants_1 = require("../constants");
var getRelativePathToExternalDirectoryFromSourceFile_1 = require("../utils/getRelativePathToExternalDirectoryFromSourceFile");
var getBuiltContextDirectory_1 = require("../utils/getBuiltContextDirectory");
var getGlobalContextVariableNameByContextId_1 = require("../utils/getGlobalContextVariableNameByContextId");
exports.REAL_CAT_CONTEXT_IMPORT = "REAL_CAT_CONTEXT_IMPORT" + constants_1.PRIVATE_TOKEN;
exports.CONTEXT_POOL_IMPORT = "CONTEXT_POOL_IMPORT" + constants_1.PRIVATE_TOKEN;
var addNecessaryImports = function () {
var addNecessaryImports = function (globalContextIdsToAdd) {
return function () { return function (sourceFile) {
var relativePathToEXTERNALDirectory = getRelativePathToExternalDirectoryFromSourceFile_1.getRelativePathToExternalDirectoryFromSourceFile(getBuiltContextDirectory_1.getBuiltContextDirectory());
var builtContextDirectory = getBuiltContextDirectory_1.getBuiltContextDirectory();
var relativePathToEXTERNALDirectory = getRelativePathToExternalDirectoryFromSourceFile_1.getRelativePathToExternalDirectoryFromSourceFile(builtContextDirectory);
var pathForRealCatContext = upath_1.default.join(relativePathToEXTERNALDirectory, 'RealCatContext');

@@ -46,8 +49,9 @@ var pathForContextPool = upath_1.default.join(relativePathToEXTERNALDirectory, 'ContextPool');

var contextPoolImport = typescript_1.factory.createImportDeclaration(undefined, undefined, typescript_1.factory.createImportClause(false, undefined, typescript_1.factory.createNamespaceImport(typescript_1.factory.createIdentifier(exports.CONTEXT_POOL_IMPORT))), typescript_1.factory.createStringLiteral(pathForContextPool));
return typescript_1.default.factory.updateSourceFile(sourceFile, __spreadArray([
var globalContextImports = lodash_1.uniq(globalContextIdsToAdd).map(function (it) { return (typescript_1.factory.createImportDeclaration(undefined, undefined, typescript_1.factory.createImportClause(false, undefined, typescript_1.factory.createNamedImports([typescript_1.factory.createImportSpecifier(undefined, typescript_1.factory.createIdentifier(getGlobalContextVariableNameByContextId_1.getGlobalContextVariableNameByContextId(it)))])), typescript_1.factory.createStringLiteral("./context_" + it))); });
return typescript_1.default.factory.updateSourceFile(sourceFile, __spreadArray(__spreadArray([
realCatContextImport,
contextPoolImport
], sourceFile.statements));
], globalContextImports), sourceFile.statements));
}; };
};
exports.addNecessaryImports = addNecessaryImports;

@@ -24,5 +24,8 @@ "use strict";

var typescript_1 = __importStar(require("typescript"));
var lodash_1 = require("lodash");
var BeanRepository_1 = require("../../bean/BeanRepository");
var BeanDependenciesRepository_1 = require("../../bean-dependencies/BeanDependenciesRepository");
var replacePropertyBeans = function () {
var getGlobalContextVariableNameByContextId_1 = require("../utils/getGlobalContextVariableNameByContextId");
var isBeanDependencyFromCurrentContext_1 = require("../utils/isBeanDependencyFromCurrentContext");
var replacePropertyBeans = function (globalContextIdsToAdd) {
return function (context) {

@@ -37,3 +40,3 @@ return function (sourceFile) {

}
return typescript_1.factory.createMethodDeclaration(undefined, undefined, undefined, typescript_1.factory.createIdentifier(beanDescriptor.classMemberName), undefined, undefined, [], beanDescriptor.typeNode, getBeanBlock(beanDescriptor));
return typescript_1.factory.createMethodDeclaration(undefined, undefined, undefined, typescript_1.factory.createIdentifier(beanDescriptor.classMemberName), undefined, undefined, [], beanDescriptor.typeNode, getBeanBlock(beanDescriptor, globalContextIdsToAdd));
}

@@ -47,9 +50,15 @@ return typescript_1.default.visitEachChild(node, visitor, context);

exports.replacePropertyBeans = replacePropertyBeans;
function getBeanBlock(beanDescriptor) {
function getBeanBlock(beanDescriptor, globalContextIdsToAdd) {
var _a, _b;
var dependencies = (_b = (_a = BeanDependenciesRepository_1.BeanDependenciesRepository.beanDependenciesRepository
.get(beanDescriptor.contextName)) === null || _a === void 0 ? void 0 : _a.get(beanDescriptor)) !== null && _b !== void 0 ? _b : [];
.get(beanDescriptor.contextDescriptor.name)) === null || _a === void 0 ? void 0 : _a.get(beanDescriptor)) !== null && _b !== void 0 ? _b : [];
var dependenciesStatements = dependencies.map(function (dependencyDescriptor) {
var _a, _b;
return typescript_1.factory.createCallExpression(typescript_1.factory.createPropertyAccessExpression(typescript_1.factory.createThis(), typescript_1.factory.createIdentifier('getBean')), undefined, [typescript_1.factory.createStringLiteral((_b = (_a = dependencyDescriptor.qualifiedBean) === null || _a === void 0 ? void 0 : _a.classMemberName) !== null && _b !== void 0 ? _b : '')]);
if (dependencyDescriptor.qualifiedBean === null) {
return null;
}
if (isBeanDependencyFromCurrentContext_1.isBeanDependencyFromCurrentContext(beanDescriptor, dependencyDescriptor.qualifiedBean)) {
return typescript_1.factory.createCallExpression(typescript_1.factory.createPropertyAccessExpression(typescript_1.factory.createThis(), typescript_1.factory.createIdentifier('getBean')), undefined, [typescript_1.factory.createStringLiteral(dependencyDescriptor.qualifiedBean.classMemberName)]);
}
globalContextIdsToAdd.push(dependencyDescriptor.qualifiedBean.contextDescriptor.id);
return typescript_1.factory.createCallExpression(typescript_1.factory.createPropertyAccessExpression(typescript_1.factory.createIdentifier(getGlobalContextVariableNameByContextId_1.getGlobalContextVariableNameByContextId(dependencyDescriptor.qualifiedBean.contextDescriptor.id)), typescript_1.factory.createIdentifier('getBean')), undefined, [typescript_1.factory.createStringLiteral(dependencyDescriptor.qualifiedBean.classMemberName)]);
});

@@ -59,4 +68,4 @@ var node = beanDescriptor.node;

return typescript_1.factory.createBlock([
typescript_1.factory.createReturnStatement(typescript_1.factory.createNewExpression(typescript_1.factory.createIdentifier(className), undefined, dependenciesStatements))
typescript_1.factory.createReturnStatement(typescript_1.factory.createNewExpression(typescript_1.factory.createIdentifier(className), undefined, lodash_1.compact(dependenciesStatements)))
], true);
}

@@ -31,3 +31,6 @@ "use strict";

var BeanDependenciesRepository_1 = require("../../bean-dependencies/BeanDependenciesRepository");
var transformMethodBeans = function () {
var lodash_1 = require("lodash");
var isBeanDependencyFromCurrentContext_1 = require("../utils/isBeanDependencyFromCurrentContext");
var getGlobalContextVariableNameByContextId_1 = require("../utils/getGlobalContextVariableNameByContextId");
var transformMethodBeans = function (globalContextIdsToAdd) {
return function (context) {

@@ -42,3 +45,3 @@ return function (sourceFile) {

}
var newBody = getNewBody(beanDescriptor);
var newBody = getNewBody(beanDescriptor, globalContextIdsToAdd);
return typescript_1.factory.updateMethodDeclaration(node, undefined, undefined, undefined, node.name, undefined, undefined, [], node.type, newBody);

@@ -53,3 +56,3 @@ }

exports.transformMethodBeans = transformMethodBeans;
function getNewBody(beanDescriptor) {
function getNewBody(beanDescriptor, globalContextIdsToAdd) {
var _a, _b, _c;

@@ -59,8 +62,15 @@ var node = beanDescriptor.node;

var dependencies = (_c = (_b = BeanDependenciesRepository_1.BeanDependenciesRepository.beanDependenciesRepository
.get(beanDescriptor.contextName)) === null || _b === void 0 ? void 0 : _b.get(beanDescriptor)) !== null && _c !== void 0 ? _c : [];
.get(beanDescriptor.contextDescriptor.name)) === null || _b === void 0 ? void 0 : _b.get(beanDescriptor)) !== null && _c !== void 0 ? _c : [];
var dependenciesStatements = dependencies.map(function (dependencyDescriptor) {
var _a, _b;
return typescript_1.factory.createVariableStatement(undefined, typescript_1.factory.createVariableDeclarationList([typescript_1.factory.createVariableDeclaration(typescript_1.factory.createIdentifier(dependencyDescriptor.parameterName), undefined, dependencyDescriptor.node.type, typescript_1.factory.createCallExpression(typescript_1.factory.createPropertyAccessExpression(typescript_1.factory.createThis(), typescript_1.factory.createIdentifier('getBean')), undefined, [typescript_1.factory.createStringLiteral((_b = (_a = dependencyDescriptor.qualifiedBean) === null || _a === void 0 ? void 0 : _a.classMemberName) !== null && _b !== void 0 ? _b : '')]))], typescript_1.default.NodeFlags.Const));
if (dependencyDescriptor.qualifiedBean === null) {
return;
}
if (isBeanDependencyFromCurrentContext_1.isBeanDependencyFromCurrentContext(beanDescriptor, dependencyDescriptor.qualifiedBean)) {
return typescript_1.factory.createVariableStatement(undefined, typescript_1.factory.createVariableDeclarationList([typescript_1.factory.createVariableDeclaration(typescript_1.factory.createIdentifier(dependencyDescriptor.parameterName), undefined, dependencyDescriptor.node.type, typescript_1.factory.createCallExpression(typescript_1.factory.createPropertyAccessExpression(typescript_1.factory.createThis(), typescript_1.factory.createIdentifier('getBean')), undefined, [typescript_1.factory.createStringLiteral((_b = (_a = dependencyDescriptor.qualifiedBean) === null || _a === void 0 ? void 0 : _a.classMemberName) !== null && _b !== void 0 ? _b : '')]))], typescript_1.default.NodeFlags.Const));
}
globalContextIdsToAdd.push(dependencyDescriptor.qualifiedBean.contextDescriptor.id);
return typescript_1.factory.createVariableStatement(undefined, typescript_1.factory.createVariableDeclarationList([typescript_1.factory.createVariableDeclaration(typescript_1.factory.createIdentifier(dependencyDescriptor.parameterName), undefined, dependencyDescriptor.node.type, typescript_1.factory.createCallExpression(typescript_1.factory.createPropertyAccessExpression(typescript_1.factory.createIdentifier(getGlobalContextVariableNameByContextId_1.getGlobalContextVariableNameByContextId(dependencyDescriptor.qualifiedBean.contextDescriptor.id)), typescript_1.factory.createIdentifier('getBean')), undefined, [typescript_1.factory.createStringLiteral(dependencyDescriptor.qualifiedBean.classMemberName)]))], typescript_1.default.NodeFlags.Const));
});
return typescript_1.factory.updateBlock(nodeBody, __spreadArray(__spreadArray([], dependenciesStatements), nodeBody.statements));
return typescript_1.factory.updateBlock(nodeBody, __spreadArray(__spreadArray([], lodash_1.compact(dependenciesStatements)), nodeBody.statements));
}

@@ -13,2 +13,3 @@ "use strict";

var DependencyGraph_1 = require("./DependencyGraph");
var constants_1 = require("../context/constants");
var buildDependencyGraphAndFillQualifiedBeans = function () {

@@ -28,35 +29,47 @@ BeanRepository_1.BeanRepository.beanDescriptorRepository.forEach(function (beansMap, contextName) {

dependencies.forEach(function (dependencyDescriptor) {
var _a, _b;
var beanCandidates = (_a = beansMap.get(dependencyDescriptor.type)) !== null && _a !== void 0 ? _a : null;
if (beanCandidates === null || beanCandidates.length === 0) {
var _a, _b, _c;
var beanCandidatesFromCurrentContext = (_a = beansMap.get(dependencyDescriptor.type)) !== null && _a !== void 0 ? _a : [];
var beanCandidatesFromGlobalContext = (_c = (_b = BeanRepository_1.BeanRepository.beanDescriptorRepository
.get(constants_1.GLOBAL_CONTEXT_NAME)) === null || _b === void 0 ? void 0 : _b.get(dependencyDescriptor.type)) !== null && _c !== void 0 ? _c : [];
if (dependencyDescriptor.qualifier !== null) {
beanCandidatesFromCurrentContext = beanCandidatesFromCurrentContext
.filter(function (it) { return it.classMemberName === dependencyDescriptor.qualifier; });
beanCandidatesFromGlobalContext = beanCandidatesFromGlobalContext
.filter(function (it) { return it.classMemberName === dependencyDescriptor.qualifier; });
}
if (beanCandidatesFromCurrentContext.length === 0 && beanCandidatesFromGlobalContext.length === 0) {
CompilationContext_1.CompilationContext.reportError({
node: dependencyDescriptor.node,
message: 'Bean for this dependency is not registered',
message: 'Bean for dependency is not registered',
});
return;
}
if (dependencyDescriptor.qualifier !== null) {
var assumedBean = (_b = beanCandidates.find(function (it) { return it.classMemberName === dependencyDescriptor.qualifier; })) !== null && _b !== void 0 ? _b : null;
if (assumedBean === null) {
CompilationContext_1.CompilationContext.reportError({
node: dependencyDescriptor.node,
message: "Bean with qualifier \"" + dependencyDescriptor.qualifier + "\" and type \"" + dependencyDescriptor.originalTypeName + "\" not found",
});
return;
}
dependencyDescriptor.qualifiedBean = assumedBean;
DependencyGraph_1.DependencyGraph.addNodeWithEdges(beanDescriptor, assumedBean);
if (beanCandidatesFromCurrentContext.length === 1) {
dependencyDescriptor.qualifiedBean = beanCandidatesFromCurrentContext[0];
DependencyGraph_1.DependencyGraph.addNodeWithEdges(beanDescriptor, beanCandidatesFromCurrentContext[0]);
return;
}
if (beanCandidates.length > 1) {
if (beanCandidatesFromCurrentContext.length > 1) {
CompilationContext_1.CompilationContext.reportErrorWithMultipleNodes({
nodes: __spreadArray([
dependencyDescriptor.node
], beanCandidates.map(function (it) { return it.node; })),
message: "Found " + beanCandidates.length + " Bean candidates, please use @Qualifier to specify which Bean should be injected",
], beanCandidatesFromCurrentContext.map(function (it) { return it.node; })),
message: "Found " + beanCandidatesFromCurrentContext.length + " Bean candidates, please use @Qualifier to specify which Bean should be injected",
});
return;
}
dependencyDescriptor.qualifiedBean = beanCandidates[0];
DependencyGraph_1.DependencyGraph.addNodeWithEdges(beanDescriptor, beanCandidates[0]);
if (beanCandidatesFromGlobalContext.length === 1) {
dependencyDescriptor.qualifiedBean = beanCandidatesFromGlobalContext[0];
DependencyGraph_1.DependencyGraph.addNodeWithEdges(beanDescriptor, beanCandidatesFromGlobalContext[0]);
return;
}
if (beanCandidatesFromGlobalContext.length > 1) {
CompilationContext_1.CompilationContext.reportErrorWithMultipleNodes({
nodes: __spreadArray([
dependencyDescriptor.node
], beanCandidatesFromGlobalContext.map(function (it) { return it.node; })),
message: "Found " + beanCandidatesFromGlobalContext.length + " Bean candidates in Global context, please use @Qualifier to specify which Bean should be injected",
});
return;
}
});

@@ -63,0 +76,0 @@ });

@@ -33,6 +33,6 @@ "use strict";

.filter(function (it) { return it !== null; });
var addedDescriptorList = (_a = resultMap.get(descriptorList[0].contextName)) !== null && _a !== void 0 ? _a : null;
var addedDescriptorList = (_a = resultMap.get(descriptorList[0].contextDescriptor.name)) !== null && _a !== void 0 ? _a : null;
if (addedDescriptorList === null) {
addedDescriptorList = [];
resultMap.set(descriptorList[0].contextName, addedDescriptorList);
resultMap.set(descriptorList[0].contextDescriptor.name, addedDescriptorList);
}

@@ -39,0 +39,0 @@ addedDescriptorList.push(descriptorList);

@@ -5,2 +5,4 @@ "use strict";

var uniqId_1 = require("../utils/uniqId");
var removeQuotesFromString_1 = require("../utils/removeQuotesFromString");
var constants_1 = require("./constants");
var ContextRepository = /** @class */ (function () {

@@ -15,14 +17,30 @@ function ContextRepository() {

name: name,
isGlobal: false,
className: removeQuotesFromString_1.removeQuotesFromString(classDeclaration.name.getText()),
absolutePath: sourceFile.fileName,
node: classDeclaration,
};
this.repository.set(name, descriptor);
this.contextMap.set(name, descriptor);
return descriptor;
};
ContextRepository.registerGlobalContext = function (classDeclaration) {
var id = uniqId_1.uniqId();
var sourceFile = classDeclaration.getSourceFile();
var descriptor = {
id: id,
name: constants_1.GLOBAL_CONTEXT_NAME,
isGlobal: true,
absolutePath: sourceFile.fileName,
node: classDeclaration,
className: removeQuotesFromString_1.removeQuotesFromString(classDeclaration.name.getText()),
};
this.globalContexts.set(id, descriptor);
return descriptor;
};
ContextRepository.getContextByName = function (name) {
var _a;
return (_a = this.repository.get(name)) !== null && _a !== void 0 ? _a : null;
return (_a = this.contextMap.get(name)) !== null && _a !== void 0 ? _a : null;
};
ContextRepository.hasContext = function (name) {
return this.repository.has(name);
return this.contextMap.has(name);
};

@@ -32,3 +50,4 @@ ContextRepository.registerBeanType = function (contextName, beanType) {

};
ContextRepository.repository = new Map();
ContextRepository.contextMap = new Map();
ContextRepository.globalContexts = new Map();
ContextRepository.contextNameToTBeanNodeSourceDescriptor = new Map();

@@ -35,0 +54,0 @@ return ContextRepository;

"use strict";
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerContexts = void 0;
var lodash_1 = require("lodash");
var ProgramRepository_1 = require("../program/ProgramRepository");

@@ -9,4 +15,7 @@ var isExtendsCatContextContext_1 = require("../ts-helpers/predicates/isExtendsCatContextContext");

var CompilationContext_1 = require("../../compilation-context/CompilationContext");
var isExtendsGlobalCatContext_1 = require("../ts-helpers/predicates/isExtendsGlobalCatContext");
var constants_1 = require("./constants");
var registerContexts = function (contextPaths) {
var sourceFiles = contextPaths.map(function (file) {
var sourceFiles = lodash_1.chain(contextPaths)
.map(function (file) {
var sourceFile = ProgramRepository_1.ProgramRepository.program.getSourceFile(file);

@@ -18,25 +27,67 @@ if (!sourceFile) {

return sourceFile;
}).filter(function (it) { return it !== undefined; });
})
.compact()
.value();
sourceFiles.forEach(function (sourceFile) {
var classDeclarations = sourceFile.statements.filter(isExtendsCatContextContext_1.isExtendsCatContextContext);
classDeclarations.forEach(function (classDeclaration) {
if (!isNamedClassDeclaration_1.isNamedClassDeclaration(classDeclaration)) {
CompilationContext_1.CompilationContext.reportError({
message: 'Context should be a named class declaration',
node: classDeclaration
});
return;
}
var name = classDeclaration.name.getText();
if (ContextRepository_1.ContextRepository.hasContext(name)) {
CompilationContext_1.CompilationContext.reportError({
node: classDeclaration,
message: 'Context should have uniq name',
});
return;
}
ContextRepository_1.ContextRepository.registerContext(name, classDeclaration);
});
var catContextClassDeclarations = sourceFile.statements.filter(isExtendsCatContextContext_1.isExtendsCatContextContext);
var globalCatContextClassDeclarations = sourceFile.statements.filter(isExtendsGlobalCatContext_1.isExtendsGlobalCatContextContext);
if (catContextClassDeclarations.length > 0 && globalCatContextClassDeclarations.length > 0) {
CompilationContext_1.CompilationContext.reportErrorWithMultipleNodes({
message: 'Only one type of CatContext should be defined in one file.',
nodes: __spreadArray(__spreadArray([], catContextClassDeclarations), globalCatContextClassDeclarations),
});
return;
}
if (catContextClassDeclarations.length > 1 || globalCatContextClassDeclarations.length > 1) {
var excessCatContextClasses = catContextClassDeclarations.slice(1);
var excessGlobalCatContextClasses = globalCatContextClassDeclarations.slice(1);
CompilationContext_1.CompilationContext.reportErrorWithMultipleNodes({
nodes: __spreadArray(__spreadArray([], excessCatContextClasses), excessGlobalCatContextClasses),
message: 'Only one context should be defined in file.',
});
return;
}
if (catContextClassDeclarations.length === 1) {
registerCatContext(catContextClassDeclarations[0]);
}
if (globalCatContextClassDeclarations.length === 1) {
registerGlobalCatContext(globalCatContextClassDeclarations[0]);
}
});
};
exports.registerContexts = registerContexts;
function registerCatContext(classDeclaration) {
if (!isNamedClassDeclaration_1.isNamedClassDeclaration(classDeclaration)) {
CompilationContext_1.CompilationContext.reportError({
message: 'Context should be a named class declaration',
node: classDeclaration
});
return;
}
var name = classDeclaration.name.getText();
if (name === constants_1.GLOBAL_CONTEXT_NAME) {
CompilationContext_1.CompilationContext.reportError({
message: "\"" + constants_1.GLOBAL_CONTEXT_NAME + "\" name of context is preserved for DI container",
node: classDeclaration
});
return;
}
if (ContextRepository_1.ContextRepository.hasContext(name)) {
CompilationContext_1.CompilationContext.reportError({
message: 'Context should have uniq name',
node: classDeclaration,
});
return;
}
ContextRepository_1.ContextRepository.registerContext(name, classDeclaration);
}
function registerGlobalCatContext(classDeclaration) {
if (!isNamedClassDeclaration_1.isNamedClassDeclaration(classDeclaration)) {
CompilationContext_1.CompilationContext.reportError({
message: 'Global Context should be a named class declaration',
node: classDeclaration
});
return;
}
ContextRepository_1.ContextRepository.registerGlobalContext(classDeclaration);
}

@@ -26,2 +26,5 @@ "use strict";

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -35,11 +38,23 @@ exports.getTransformerFactory = void 0;

var removeQuotesFromString_1 = require("../utils/removeQuotesFromString");
var minimatch_1 = __importDefault(require("minimatch"));
var getBuiltContextDirectory_1 = require("../build-context/utils/getBuiltContextDirectory");
var getTransformerFactory = function () { return function (context) {
return function (sourceFile) {
if (minimatch_1.default(sourceFile.fileName, getBuiltContextDirectory_1.getBuiltContextDirectory() + "/context_*")) {
//Do not touching built contexts
return sourceFile;
}
var factoryImportsToAdd = [];
var hasContainerAccess = false;
var visitor = (function (node) {
if (isContainerAccess_1.isContainerAccess(node)) {
hasContainerAccess = true;
return replaceContainerCall_1.replaceContainerCall(node, factoryImportsToAdd);
try {
if (isContainerAccess_1.isContainerAccess(node)) {
hasContainerAccess = true;
return replaceContainerCall_1.replaceContainerCall(node, factoryImportsToAdd);
}
}
catch (err) {
err;
sourceFile.text;
}
return typescript_1.default.visitEachChild(node, visitor, context);

@@ -51,3 +66,7 @@ });

: newSourceFile.statements;
var uniqFactoryImportsToAdd = lodash_1.uniqBy(factoryImportsToAdd, function (it) { return removeQuotesFromString_1.removeQuotesFromString(it.moduleSpecifier.getText()); });
var uniqFactoryImportsToAdd = lodash_1.uniqBy(factoryImportsToAdd, function (it) {
if (typescript_1.default.isStringLiteral(it.moduleSpecifier)) {
return removeQuotesFromString_1.removeQuotesFromString(it.moduleSpecifier.text);
}
});
return typescript_1.factory.updateSourceFile(sourceFile, __spreadArray(__spreadArray([], uniqFactoryImportsToAdd), filteredStatements), sourceFile.isDeclarationFile, sourceFile.referencedFiles, undefined, sourceFile.hasNoDefaultLib, undefined);

@@ -54,0 +73,0 @@ };

@@ -16,2 +16,3 @@ "use strict";

var checkBeansInterface_1 = require("./checkBeansInterface");
var constants_1 = require("../../context/constants");
var replaceContainerCall = function (node, factoryImportsToAdd) {

@@ -29,2 +30,9 @@ if (!validContainerKeys_1.validContainerKeys.includes(node.expression.name.getText())) {

}
if (contextName === constants_1.GLOBAL_CONTEXT_NAME) {
CompilationContext_1.CompilationContext.reportError({
message: 'You can\'t access Global Context',
node: node
});
return node;
}
var contextDescriptor = ContextRepository_1.ContextRepository.getContextByName(contextName);

@@ -31,0 +39,0 @@ if (contextDescriptor === null) {

@@ -34,2 +34,5 @@ export interface IDIContext<TBeans> {

}
export declare abstract class GlobalCatContext {
protected constructor();
}
export declare type TClassConstructor<T> = new (...args: any[]) => T;

@@ -36,0 +39,0 @@ export declare type TBeanScope = "prototype" | "singleton";

@@ -16,2 +16,3 @@ "use strict";

__exportStar(require("./external/CatContext"), exports);
__exportStar(require("./external/GlobalCatContext"), exports);
__exportStar(require("./external/decorators"), exports);
{
"name": "dependency-injection-cat",
"version": "0.1.4",
"version": "0.1.5",
"main": "index.js",

@@ -26,10 +26,11 @@ "types": "index.d.ts",

"graphlib": "^2.1.8",
"json-beautify": "^1.1.1",
"line-column": "^1.0.2",
"lodash": "^4.17.20",
"minimatch": "^3.0.4",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.1.3",
"upath": "^2.0.1",
"json-beautify": "^1.1.1",
"uuid": "^8.3.2"
}
}

@@ -16,4 +16,4 @@ # Dependency Injection Cat

export class ApplicationContext extends CatContext<IBeans> {
useCase = Bean<IUseCase>(UseCase)
mobxRepository = Bean<IRepository>(MobxRepository)
useCase = Bean<IUseCase>(UseCase)
mobxRepository = Bean<IRepository>(MobxRepository)
}

@@ -23,7 +23,7 @@

export class UseCase implements IUseCase {
constructor(
private repository: IRepository,
) {}
makeBusinessLogic() {...}
constructor(
private repository: IRepository,
) {}
makeBusinessLogic() {...}
}

@@ -33,8 +33,8 @@

export const UIComponent: React.FC = () => {
const appContext = container.getContext<IBeans>({ name: 'ApplicationContext' });
const { useCase } = appContext.getBeans();
return (
<button onClick={useCase.makeBusinessLogic}> Click me! </button>
)
const appContext = container.getContext<IBeans>({ name: 'ApplicationContext' });
const { useCase } = appContext.getBeans();
return (
<button onClick={useCase.makeBusinessLogic}> Click me! </button>
)
}

@@ -61,5 +61,5 @@ ```

{
"compilerOptions": {
"baseUrl": "Base url should be specified!"
}
"compilerOptions": {
"baseUrl": "Base url should be specified!"
}
}

@@ -77,25 +77,25 @@ ```

module.exports = {
...
module: {
rules: [
...
module: {
rules: [
{
test: /\.(t|j)sx?$/,
loader: 'babel-loader',
options: {
plugins: [
[
require('dependency-injection-cat/transformers/babel'),
{
test: /\.(t|j)sx?$/,
loader: 'babel-loader',
options: {
plugins: [
[
require('dependency-injection-cat/transformers/babel'),
{
//Here is configuration options, see below
}
]
]
}
//Here is configuration options, see below
}
]
]
},
plugins: [
//Without this plugin, a compilation with DI errors will be successful
new ReportDiErrorsPlugin(),
]
}
}
]
},
plugins: [
//Without this plugin, a compilation with DI errors will be successful
new ReportDiErrorsPlugin(),
]
}

@@ -105,7 +105,7 @@

{
"compilerOptions": {
//Should be specified
"baseUrl": "your base url"
}
"compilerOptions": {
//Should be specified
"baseUrl": "your base url"
}
}
```

@@ -122,24 +122,24 @@

module.exports = {
...
module: {
rules: [
{
test: /\.(t|j)sx?$/,
use: {
loader: 'ts-loader',
options: {
getCustomTransformers: (program) => ({
before: [diCatTransformer(program, {
//Here is configuration options, see below
})],
}),
}
}
}
]
},
plugins: [
//Without this plugin, a compilation with DI errors will be successful
new ReportDiErrorsPlugin(),
]
...
module: {
rules: [
{
test: /\.(t|j)sx?$/,
use: {
loader: 'ts-loader',
options: {
getCustomTransformers: (program) => ({
before: [diCatTransformer(program, {
//Here is configuration options, see below
})],
}),
}
}
}
]
},
plugins: [
//Without this plugin, a compilation with DI errors will be successful
new ReportDiErrorsPlugin(),
]
}

@@ -149,7 +149,7 @@

{
"compilerOptions": {
//Should be specified
"baseUrl": "your base url"
}
"compilerOptions": {
//Should be specified
"baseUrl": "your base url"
}
}
```

@@ -165,20 +165,20 @@

module.exports = {
...
module: {
rules: [
{
test: /\.(t|j)sx?$/,
use: {
loader: 'ts-loader',
options: {
compiler: 'ttypescript'
}
}
}
]
},
plugins: [
//Without this plugin, a compilation with DI errors will be successful
new ReportDiErrorsPlugin(),
]
...
module: {
rules: [
{
test: /\.(t|j)sx?$/,
use: {
loader: 'ts-loader',
options: {
compiler: 'ttypescript'
}
}
}
]
},
plugins: [
//Without this plugin, a compilation with DI errors will be successful
new ReportDiErrorsPlugin(),
]
}

@@ -188,13 +188,13 @@

{
"compilerOptions": {
//Should be specified
"baseUrl": "your base url",
"plugins": [
{
"transform": "dependency-injection-cat/transformers/typescript",
//Here is configuration options, see below
}
]
"compilerOptions": {
//Should be specified
"baseUrl": "your base url",
"plugins": [
{
"transform": "dependency-injection-cat/transformers/typescript",
//Here is configuration options, see below
}
]
}
}
```

@@ -208,5 +208,5 @@

{
diConfigPattern ?: string; // Glob pattern, default value. Default: '**/*.di.ts'
ignorePatterns ?: string[]; // Array of Glob patterns, default value. Default: ['**/node_modules/**']
compiledContextOutputDir ?: string; // Output directory of transformed contexts, can be specified for debug purposes. Default: node_modules/dependency-injection-cat/external/built-context
diConfigPattern ?: string; // Glob pattern, default value. Default: '**/*.di.ts'
ignorePatterns ?: string[]; // Array of Glob patterns, default value. Default: ['**/node_modules/**']
compiledContextOutputDir ?: string; // Output directory of transformed contextMap, can be specified for debug purposes. Default: node_modules/dependency-injection-cat/external/built-context
}

@@ -219,2 +219,4 @@ ```

CatContext it's a place, where you should define your **Beans**
```typescript

@@ -224,2 +226,8 @@ class CatContext<TBeans, TConfig = null>

##### Rules
- Name of context should be unique
- Name of context "Global" is preserved for DI container, see **GlobalCatContext**
### TBeans

@@ -263,4 +271,37 @@

## GlobalCatContext
Sometimes you want to describe common dependencies that will be used all across your application, for these purposes you should use GlobalCatContext.
#### Rules
- You can not get beans from the Global Context using container access
#### Syntax and usage
```typescript
//GlobalApplicationContext.di.ts
export class GlobalApplicationContext extends GlobalCatContext {
@Bean
logger(): ILogger {
return new Logger();
}
}
//ApplicationContext.di.ts
export class AppContext extends CatContext<IBeans> {
@Bean
useCase(
//If Bean for ILogger will be defined in current context, bean from current context will be injected
logger: ILogger
): IUseCase {
return new UseCase(logger)
}
}
```
## Container

@@ -270,2 +311,6 @@

#### Rules
- Name of context in container access calls, should not be "Global", it's reserved for the **GlobalCatContext**
### TBeans

@@ -281,3 +326,3 @@

container.initContext<TBeans, TConfig>({
key?: any, //Can be any value, you can use it for creating pool of contexts.
key?: any, //Can be any value, you can use it for creating pool of contextMap.
name: string, //It's the name of the class in which you specified the Beans. Should be a string literal.

@@ -490,3 +535,3 @@ config?: TConfig, //Config that will be transferred to the context

Qualifier needed, when you have 2 or more **Beans** in the **Context** with same type
Qualifier needed, when you have 2 or more **Beans** in the **Context** with same type. Also you can use qualifier, when injecting **Beans** from **GlobalCatContext**

@@ -502,2 +547,3 @@ #### Rules

```typescript
//When Bean placed in current context
export class ApplicationContext extends CatContext<IBeans> {

@@ -516,1 +562,21 @@ httpRequester: IRequester = Bean(HttpRequester);

```typescript
//When Bean placed in Global context
//GlobalApplicationContext.di.ts
export class GlobalApplicationContext extends GlobalCatContext {
graphQLRequester: IRequester = Bean(GraphQLRequester);
httpRequester: IRequester = Bean(HttpRequester);
}
//ApplicationContext.di.ts
export class ApplicationContext extends CatContext<IBeans> {
@Bean
useCase(
@Qualifier('graphQLRequester') requester: IRequester,
): IUseCase {
return new UseCase(requester);
}
}
```
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc