ng-afelio
Version:
Extended Angular CLI
53 lines (52 loc) • 2.87 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.takeUntilDestroyTransformer = void 0;
const ts = require("typescript");
const ast_util_1 = require("../../schematics/util/ast-util");
function findDecorator(nodes, search) {
return nodes.find(node => (0, ast_util_1.findNode)(node, ts.SyntaxKind.Decorator, search));
}
function removeComments(text) {
return text.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '');
}
const takeUntilDestroyTransformer = (context) => {
return (rootNode) => {
if (/untilDestroyed\(/.test(removeComments(rootNode.getText()))) {
const visit = (node) => {
var _a, _b;
let decoratorAdded = false;
if (ts.isClassDeclaration(node) && /untilDestroyed\(this\)/.test(removeComments(node.getText())) && node.decorators) {
console.log('\nuntilDestroyed detected in ' + rootNode.fileName);
const angularDecorator = findDecorator(node.decorators, /^(@Component)|(@Directive)|(@Injectable)|(@Pipe)/);
if (angularDecorator) {
// @ts-ignore
node.decorators = ts.factory.createNodeArray([
ts.factory.createDecorator(ts.factory.createCallExpression(ts.factory.createIdentifier('UntilDestroy'), undefined, [])),
...node.decorators,
]);
decoratorAdded = true;
}
else {
console.error('You cannot use "untilDestroyed(this)" oustide of angular element. Error in ' + ((_a = node.name) === null || _a === void 0 ? void 0 : _a.escapedText));
}
}
else if (ts.isClassDeclaration(node)) {
console.error('You cannot use "untilDestroyed(this)" oustide of angular element. Error in ' + ((_b = node.name) === null || _b === void 0 ? void 0 : _b.escapedText));
}
if (decoratorAdded) {
const newImport = ts.factory.createImportDeclaration(undefined,
/* modifiers */ undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamedImports([
ts.factory.createImportSpecifier(false, ts.factory.createIdentifier('UntilDestroy'), ts.factory.createIdentifier('UntilDestroy')),
])), ts.factory.createStringLiteral('@ngneat/until-destroy'));
return [newImport, node];
}
else {
return ts.visitEachChild(node, visit, context);
}
};
return ts.visitNode(rootNode, visit);
}
return rootNode;
};
};
exports.takeUntilDestroyTransformer = takeUntilDestroyTransformer;