UNPKG

2.87 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright Google LLC All Rights Reserved.
5 *
6 * Use of this source code is governed by an MIT-style license that can be
7 * found in the LICENSE file at https://angular.io/license
8 */
9Object.defineProperty(exports, "__esModule", { value: true });
10exports.hasNgModuleImport = void 0;
11const ts = require("typescript");
12/**
13 * Whether the Angular module in the given path imports the specifed module class name.
14 */
15function hasNgModuleImport(tree, modulePath, className) {
16 const moduleFileContent = tree.read(modulePath);
17 if (!moduleFileContent) {
18 throw new Error(`Could not read Angular module file: ${modulePath}`);
19 }
20 const parsedFile = ts.createSourceFile(modulePath, moduleFileContent.toString(), ts.ScriptTarget.Latest, true);
21 let ngModuleMetadata = null;
22 const findModuleDecorator = (node) => {
23 if (ts.isDecorator(node) && ts.isCallExpression(node.expression) &&
24 isNgModuleCallExpression(node.expression)) {
25 ngModuleMetadata = node.expression.arguments[0];
26 return;
27 }
28 ts.forEachChild(node, findModuleDecorator);
29 };
30 ts.forEachChild(parsedFile, findModuleDecorator);
31 if (!ngModuleMetadata) {
32 throw new Error(`Could not find NgModule declaration inside: "${modulePath}"`);
33 }
34 for (const property of ngModuleMetadata === null || ngModuleMetadata === void 0 ? void 0 : ngModuleMetadata.properties) {
35 if (!ts.isPropertyAssignment(property) || property.name.getText() !== 'imports' ||
36 !ts.isArrayLiteralExpression(property.initializer)) {
37 continue;
38 }
39 // eslint-disable-next-line @typescript-eslint/no-explicit-any
40 if (property.initializer.elements.some((element) => element.getText() === className)) {
41 return true;
42 }
43 }
44 return false;
45}
46exports.hasNgModuleImport = hasNgModuleImport;
47/**
48 * Resolves the last identifier that is part of the given expression. This helps resolving
49 * identifiers of nested property access expressions (e.g. myNamespace.core.NgModule).
50 */
51function resolveIdentifierOfExpression(expression) {
52 if (ts.isIdentifier(expression)) {
53 return expression;
54 }
55 else if (ts.isPropertyAccessExpression(expression)) {
56 return resolveIdentifierOfExpression(expression.expression);
57 }
58 return null;
59}
60/** Whether the specified call expression is referring to a NgModule definition. */
61function isNgModuleCallExpression(callExpression) {
62 if (!callExpression.arguments.length ||
63 !ts.isObjectLiteralExpression(callExpression.arguments[0])) {
64 return false;
65 }
66 const decoratorIdentifier = resolveIdentifierOfExpression(callExpression.expression);
67 return decoratorIdentifier ? decoratorIdentifier.text === 'NgModule' : false;
68}
69//# sourceMappingURL=ng-module-imports.js.map
\No newline at end of file