@abp/ng.schematics 10.5.0 → 10.6.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/commands/ai-config/index.d.ts +3 -3
  2. package/commands/ai-config/index.js +88 -88
  3. package/commands/ai-config/index.js.map +1 -1
  4. package/commands/ai-config/model.d.ts +10 -10
  5. package/commands/ai-config/model.js +2 -2
  6. package/commands/api/files-service/proxy/__namespace@dir__/__name@kebab__.service.ts.template +6 -4
  7. package/commands/api/index.d.ts +2 -2
  8. package/commands/api/index.js +139 -138
  9. package/commands/api/index.js.map +1 -1
  10. package/commands/change-theme/index.d.ts +28 -28
  11. package/commands/change-theme/index.js +474 -473
  12. package/commands/change-theme/index.js.map +1 -1
  13. package/commands/change-theme/model.d.ts +5 -5
  14. package/commands/change-theme/model.js +2 -2
  15. package/commands/change-theme/style-map.d.ts +16 -16
  16. package/commands/change-theme/style-map.js +424 -424
  17. package/commands/change-theme/theme-options.enum.d.ts +6 -6
  18. package/commands/change-theme/theme-options.enum.js +11 -11
  19. package/commands/change-theme/theme-options.enum.js.map +1 -1
  20. package/commands/create-lib/index.d.ts +13 -13
  21. package/commands/create-lib/index.js +298 -298
  22. package/commands/create-lib/index.js.map +1 -1
  23. package/commands/create-lib/models/generate-lib-schema.d.ts +20 -20
  24. package/commands/create-lib/models/generate-lib-schema.js +8 -8
  25. package/commands/create-lib/models/generate-lib-schema.js.map +1 -1
  26. package/commands/create-lib/models/index.d.ts +1 -1
  27. package/commands/create-lib/models/index.js +4 -17
  28. package/commands/create-lib/models/index.js.map +1 -1
  29. package/commands/proxy-add/index.d.ts +2 -2
  30. package/commands/proxy-add/index.js +41 -41
  31. package/commands/proxy-add/index.js.map +1 -1
  32. package/commands/proxy-index/index.d.ts +5 -5
  33. package/commands/proxy-index/index.js +14 -14
  34. package/commands/proxy-index/index.js.map +1 -1
  35. package/commands/proxy-refresh/index.d.ts +3 -3
  36. package/commands/proxy-refresh/index.js +27 -27
  37. package/commands/proxy-refresh/index.js.map +1 -1
  38. package/commands/proxy-remove/index.d.ts +3 -3
  39. package/commands/proxy-remove/index.js +33 -33
  40. package/commands/proxy-remove/index.js.map +1 -1
  41. package/commands/ssr-add/index.d.ts +11 -11
  42. package/commands/ssr-add/index.js +360 -361
  43. package/commands/ssr-add/index.js.map +1 -1
  44. package/commands/ssr-add/server/index.d.ts +10 -10
  45. package/commands/ssr-add/server/index.js +209 -205
  46. package/commands/ssr-add/server/index.js.map +1 -1
  47. package/commands/ssr-add/server/index.ts +6 -2
  48. package/constants/api.d.ts +1 -1
  49. package/constants/api.js +4 -4
  50. package/constants/index.d.ts +4 -4
  51. package/constants/index.js +7 -20
  52. package/constants/index.js.map +1 -1
  53. package/constants/proxy.d.ts +4 -4
  54. package/constants/proxy.js +7 -7
  55. package/constants/symbols.d.ts +1 -1
  56. package/constants/symbols.js +4 -4
  57. package/constants/system-types.d.ts +1 -1
  58. package/constants/system-types.js +29 -29
  59. package/constants/volo.d.ts +5 -5
  60. package/constants/volo.js +34 -34
  61. package/enums/binding-source-id.d.ts +8 -7
  62. package/enums/binding-source-id.js +12 -11
  63. package/enums/binding-source-id.js.map +1 -1
  64. package/enums/exception.d.ts +17 -17
  65. package/enums/exception.js +2 -2
  66. package/enums/import-keyword.d.ts +4 -4
  67. package/enums/import-keyword.js +8 -8
  68. package/enums/import-keyword.js.map +1 -1
  69. package/enums/index.d.ts +5 -5
  70. package/enums/index.js +8 -21
  71. package/enums/index.js.map +1 -1
  72. package/enums/method-modifier.d.ts +6 -6
  73. package/enums/method-modifier.js +10 -10
  74. package/enums/method-modifier.js.map +1 -1
  75. package/enums/service-types.d.ts +6 -6
  76. package/enums/service-types.js +10 -10
  77. package/enums/service-types.js.map +1 -1
  78. package/index.d.ts +3 -3
  79. package/index.js +6 -19
  80. package/index.js.map +1 -1
  81. package/models/api-definition.d.ts +97 -93
  82. package/models/api-definition.js +2 -2
  83. package/models/generate-proxy-schema.d.ts +28 -28
  84. package/models/generate-proxy-schema.js +2 -2
  85. package/models/import.d.ts +11 -11
  86. package/models/import.js +13 -13
  87. package/models/index.d.ts +11 -11
  88. package/models/index.js +14 -27
  89. package/models/index.js.map +1 -1
  90. package/models/method.d.ts +36 -34
  91. package/models/method.js +73 -70
  92. package/models/method.js.map +1 -1
  93. package/models/model.d.ts +48 -48
  94. package/models/model.js +76 -76
  95. package/models/model.js.map +1 -1
  96. package/models/project.d.ts +5 -5
  97. package/models/project.js +2 -2
  98. package/models/proxy-config.d.ts +4 -4
  99. package/models/proxy-config.js +2 -2
  100. package/models/rule.d.ts +2 -2
  101. package/models/rule.js +2 -2
  102. package/models/service.d.ts +21 -21
  103. package/models/service.js +11 -11
  104. package/models/tree.d.ts +1 -1
  105. package/models/tree.js +2 -2
  106. package/models/util.d.ts +7 -7
  107. package/models/util.js +2 -2
  108. package/package.json +6 -6
  109. package/utils/angular/add-declaration-to-ng-module.d.ts +20 -20
  110. package/utils/angular/add-declaration-to-ng-module.js +45 -45
  111. package/utils/angular/add-declaration-to-ng-module.js.map +1 -1
  112. package/utils/angular/ast-utils.d.ts +106 -106
  113. package/utils/angular/ast-utils.js +518 -518
  114. package/utils/angular/ast-utils.js.map +1 -1
  115. package/utils/angular/change.d.ts +68 -68
  116. package/utils/angular/change.js +121 -121
  117. package/utils/angular/change.js.map +1 -1
  118. package/utils/angular/dependencies.d.ts +23 -23
  119. package/utils/angular/dependencies.js +56 -56
  120. package/utils/angular/dependencies.js.map +1 -1
  121. package/utils/angular/dependency.d.ts +96 -96
  122. package/utils/angular/dependency.js +123 -122
  123. package/utils/angular/dependency.js.map +1 -1
  124. package/utils/angular/eol.d.ts +8 -8
  125. package/utils/angular/eol.js +22 -23
  126. package/utils/angular/eol.js.map +1 -1
  127. package/utils/angular/find-module.d.ts +33 -33
  128. package/utils/angular/find-module.js +105 -105
  129. package/utils/angular/find-module.js.map +1 -1
  130. package/utils/angular/generate-from-files.d.ts +19 -19
  131. package/utils/angular/generate-from-files.js +48 -49
  132. package/utils/angular/generate-from-files.js.map +1 -1
  133. package/utils/angular/index.d.ts +15 -15
  134. package/utils/angular/index.js +18 -31
  135. package/utils/angular/index.js.map +1 -1
  136. package/utils/angular/json-file.d.ts +24 -24
  137. package/utils/angular/json-file.js +71 -71
  138. package/utils/angular/json-file.js.map +1 -1
  139. package/utils/angular/latest-versions/index.d.ts +28 -28
  140. package/utils/angular/latest-versions/index.js +31 -31
  141. package/utils/angular/ng-ast-utils.d.ts +12 -12
  142. package/utils/angular/ng-ast-utils.js +79 -79
  143. package/utils/angular/ng-ast-utils.js.map +1 -1
  144. package/utils/angular/parse-name.d.ts +13 -13
  145. package/utils/angular/parse-name.js +19 -20
  146. package/utils/angular/parse-name.js.map +1 -1
  147. package/utils/angular/paths.d.ts +8 -8
  148. package/utils/angular/paths.js +17 -18
  149. package/utils/angular/paths.js.map +1 -1
  150. package/utils/angular/project-targets.d.ts +11 -11
  151. package/utils/angular/project-targets.js +21 -22
  152. package/utils/angular/project-targets.js.map +1 -1
  153. package/utils/angular/standalone/app_component.d.ts +29 -29
  154. package/utils/angular/standalone/app_component.js +107 -107
  155. package/utils/angular/standalone/app_component.js.map +1 -1
  156. package/utils/angular/standalone/app_config.d.ts +23 -23
  157. package/utils/angular/standalone/app_config.js +89 -89
  158. package/utils/angular/standalone/app_config.js.map +1 -1
  159. package/utils/angular/standalone/code_block.d.ts +53 -53
  160. package/utils/angular/standalone/code_block.js +80 -79
  161. package/utils/angular/standalone/code_block.js.map +1 -1
  162. package/utils/angular/standalone/index.d.ts +9 -9
  163. package/utils/angular/standalone/index.js +13 -13
  164. package/utils/angular/standalone/rules.d.ts +45 -45
  165. package/utils/angular/standalone/rules.js +187 -188
  166. package/utils/angular/standalone/rules.js.map +1 -1
  167. package/utils/angular/standalone/util.d.ts +35 -35
  168. package/utils/angular/standalone/util.js +135 -135
  169. package/utils/angular/standalone/util.js.map +1 -1
  170. package/utils/angular/test/create-app-module.d.ts +9 -9
  171. package/utils/angular/test/create-app-module.js +14 -15
  172. package/utils/angular/test/create-app-module.js.map +1 -1
  173. package/utils/angular/test/get-file-content.d.ts +9 -9
  174. package/utils/angular/test/get-file-content.js +17 -18
  175. package/utils/angular/test/get-file-content.js.map +1 -1
  176. package/utils/angular/test/index.d.ts +9 -9
  177. package/utils/angular/test/index.js +12 -25
  178. package/utils/angular/test/index.js.map +1 -1
  179. package/utils/angular/validation.d.ts +10 -10
  180. package/utils/angular/validation.js +28 -28
  181. package/utils/angular/validation.js.map +1 -1
  182. package/utils/angular/workspace-models.d.ts +167 -167
  183. package/utils/angular/workspace-models.js +43 -43
  184. package/utils/angular/workspace-models.js.map +1 -1
  185. package/utils/angular/workspace.d.ts +65 -65
  186. package/utils/angular/workspace.js +135 -135
  187. package/utils/angular/workspace.js.map +1 -1
  188. package/utils/angular-schematic/generate-lib.d.ts +3 -3
  189. package/utils/angular-schematic/generate-lib.js +52 -53
  190. package/utils/angular-schematic/generate-lib.js.map +1 -1
  191. package/utils/angular-schematic/index.d.ts +1 -1
  192. package/utils/angular-schematic/index.js +4 -17
  193. package/utils/angular-schematic/index.js.map +1 -1
  194. package/utils/api.d.ts +2 -2
  195. package/utils/api.js +7 -8
  196. package/utils/api.js.map +1 -1
  197. package/utils/ast.d.ts +5 -5
  198. package/utils/ast.js +28 -28
  199. package/utils/ast.js.map +1 -1
  200. package/utils/barrel.d.ts +4 -4
  201. package/utils/barrel.js +86 -87
  202. package/utils/barrel.js.map +1 -1
  203. package/utils/common.d.ts +11 -11
  204. package/utils/common.js +78 -78
  205. package/utils/common.js.map +1 -1
  206. package/utils/enum.d.ts +18 -18
  207. package/utils/enum.js +39 -40
  208. package/utils/enum.js.map +1 -1
  209. package/utils/file.d.ts +2 -2
  210. package/utils/file.js +8 -9
  211. package/utils/file.js.map +1 -1
  212. package/utils/generics.d.ts +26 -26
  213. package/utils/generics.js +89 -89
  214. package/utils/generics.js.map +1 -1
  215. package/utils/import.d.ts +3 -3
  216. package/utils/import.js +10 -11
  217. package/utils/import.js.map +1 -1
  218. package/utils/index.d.ts +22 -22
  219. package/utils/index.js +25 -38
  220. package/utils/index.js.map +1 -1
  221. package/utils/methods.d.ts +4 -4
  222. package/utils/methods.js +31 -31
  223. package/utils/methods.js.map +1 -1
  224. package/utils/model.d.ts +14 -14
  225. package/utils/model.js +217 -211
  226. package/utils/model.js.map +1 -1
  227. package/utils/namespace.d.ts +1 -1
  228. package/utils/namespace.js +17 -18
  229. package/utils/namespace.js.map +1 -1
  230. package/utils/ng-module.d.ts +46 -46
  231. package/utils/ng-module.js +126 -125
  232. package/utils/ng-module.js.map +1 -1
  233. package/utils/path.d.ts +2 -2
  234. package/utils/path.js +35 -36
  235. package/utils/path.js.map +1 -1
  236. package/utils/rule.d.ts +4 -4
  237. package/utils/rule.js +32 -33
  238. package/utils/rule.js.map +1 -1
  239. package/utils/service.d.ts +8 -8
  240. package/utils/service.js +280 -171
  241. package/utils/service.js.map +1 -1
  242. package/utils/source.d.ts +13 -13
  243. package/utils/source.js +165 -165
  244. package/utils/source.js.map +1 -1
  245. package/utils/standalone.d.ts +59 -59
  246. package/utils/standalone.js +146 -145
  247. package/utils/standalone.js.map +1 -1
  248. package/utils/text.d.ts +10 -10
  249. package/utils/text.js +59 -59
  250. package/utils/text.js.map +1 -1
  251. package/utils/tree.d.ts +14 -14
  252. package/utils/tree.js +83 -83
  253. package/utils/tree.js.map +1 -1
  254. package/utils/type.d.ts +13 -13
  255. package/utils/type.js +112 -113
  256. package/utils/type.js.map +1 -1
  257. package/utils/workspace.d.ts +20 -20
  258. package/utils/workspace.js +113 -114
  259. package/utils/workspace.js.map +1 -1
@@ -1,519 +1,519 @@
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.dev/license
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.hasTopLevelIdentifier = exports.addRouteDeclarationToModule = exports.getRouterModuleDeclaration = exports.isImported = exports.addBootstrapToModule = exports.addExportToModule = exports.addProviderToModule = exports.addImportToModule = exports.addDeclarationToModule = exports.addSymbolToNgModuleMetadata = exports.getMetadataField = exports.getDecoratorMetadata = exports.insertAfterLastOccurrence = exports.findNode = exports.getSourceNodes = exports.findNodes = exports.insertImport = void 0;
11
- const core_1 = require("@angular-devkit/core");
12
- const ts = require("typescript");
13
- const change_1 = require("./change");
14
- const eol_1 = require("./eol");
15
- /**
16
- * Add Import `import { symbolName } from fileName` if the import doesn't exit
17
- * already. Assumes fileToEdit can be resolved and accessed.
18
- * @param fileToEdit File we want to add import to.
19
- * @param symbolName Item to import.
20
- * @param fileName Path to the file.
21
- * @param isDefault If true, import follows style for importing default exports.
22
- * @param alias Alias that the symbol should be inserted under.
23
- * @return Change
24
- */
25
- function insertImport(source, fileToEdit, symbolName, fileName, isDefault = false, alias) {
26
- const rootNode = source;
27
- const allImports = findNodes(rootNode, ts.isImportDeclaration);
28
- const importExpression = alias ? `${symbolName} as ${alias}` : symbolName;
29
- // get nodes that map to import statements from the file fileName
30
- const relevantImports = allImports.filter(node => {
31
- return ts.isStringLiteralLike(node.moduleSpecifier) && node.moduleSpecifier.text === fileName;
32
- });
33
- if (relevantImports.length > 0) {
34
- const hasNamespaceImport = relevantImports.some(node => {
35
- return node.importClause?.namedBindings?.kind === ts.SyntaxKind.NamespaceImport;
36
- });
37
- // if imports * from fileName, don't add symbolName
38
- if (hasNamespaceImport) {
39
- return new change_1.NoopChange();
40
- }
41
- const imports = relevantImports.flatMap(node => {
42
- return node.importClause?.namedBindings && ts.isNamedImports(node.importClause.namedBindings)
43
- ? node.importClause.namedBindings.elements
44
- : [];
45
- });
46
- // insert import if it's not there
47
- if (!imports.some(node => (node.propertyName || node.name).text === symbolName)) {
48
- const fallbackPos = findNodes(relevantImports[0], ts.SyntaxKind.CloseBraceToken)[0].getStart() ||
49
- findNodes(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].getStart();
50
- return insertAfterLastOccurrence(imports, `, ${importExpression}`, fileToEdit, fallbackPos);
51
- }
52
- return new change_1.NoopChange();
53
- }
54
- // no such import declaration exists
55
- const useStrict = findNodes(rootNode, ts.isStringLiteral).filter(n => n.text === 'use strict');
56
- let fallbackPos = 0;
57
- if (useStrict.length > 0) {
58
- fallbackPos = useStrict[0].end;
59
- }
60
- const open = isDefault ? '' : '{ ';
61
- const close = isDefault ? '' : ' }';
62
- const eol = (0, eol_1.getEOL)(rootNode.getText());
63
- // if there are no imports or 'use strict' statement, insert import at beginning of file
64
- const insertAtBeginning = allImports.length === 0 && useStrict.length === 0;
65
- const separator = insertAtBeginning ? '' : `;${eol}`;
66
- const toInsert = `${separator}import ${open}${importExpression}${close}` +
67
- ` from '${fileName}'${insertAtBeginning ? `;${eol}` : ''}`;
68
- return insertAfterLastOccurrence(allImports, toInsert, fileToEdit, fallbackPos, ts.SyntaxKind.StringLiteral);
69
- }
70
- exports.insertImport = insertImport;
71
- function findNodes(node, kindOrGuard, max = Infinity, recursive = false) {
72
- if (!node || max == 0) {
73
- return [];
74
- }
75
- const test = typeof kindOrGuard === 'function'
76
- ? kindOrGuard
77
- : (node) => node.kind === kindOrGuard;
78
- const arr = [];
79
- if (test(node)) {
80
- arr.push(node);
81
- max--;
82
- }
83
- if (max > 0 && (recursive || !test(node))) {
84
- for (const child of node.getChildren()) {
85
- findNodes(child, test, max, recursive).forEach(node => {
86
- if (max > 0) {
87
- arr.push(node);
88
- }
89
- max--;
90
- });
91
- if (max <= 0) {
92
- break;
93
- }
94
- }
95
- }
96
- return arr;
97
- }
98
- exports.findNodes = findNodes;
99
- /**
100
- * Get all the nodes from a source.
101
- * @param sourceFile The source file object.
102
- * @returns {Array<ts.Node>} An array of all the nodes in the source.
103
- */
104
- function getSourceNodes(sourceFile) {
105
- const nodes = [sourceFile];
106
- const result = [];
107
- while (nodes.length > 0) {
108
- const node = nodes.shift();
109
- if (node) {
110
- result.push(node);
111
- if (node.getChildCount(sourceFile) >= 0) {
112
- nodes.unshift(...node.getChildren());
113
- }
114
- }
115
- }
116
- return result;
117
- }
118
- exports.getSourceNodes = getSourceNodes;
119
- function findNode(node, kind, text) {
120
- if (node.kind === kind && node.getText() === text) {
121
- return node;
122
- }
123
- let foundNode = null;
124
- ts.forEachChild(node, childNode => {
125
- foundNode = foundNode || findNode(childNode, kind, text);
126
- });
127
- return foundNode;
128
- }
129
- exports.findNode = findNode;
130
- /**
131
- * Helper for sorting nodes.
132
- * @return function to sort nodes in increasing order of position in sourceFile
133
- */
134
- function nodesByPosition(first, second) {
135
- return first.getStart() - second.getStart();
136
- }
137
- /**
138
- * Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]`
139
- * or after the last of occurence of `syntaxKind` if the last occurence is a sub child
140
- * of ts.SyntaxKind[nodes[i].kind] and save the changes in file.
141
- *
142
- * @param nodes insert after the last occurence of nodes
143
- * @param toInsert string to insert
144
- * @param file file to insert changes into
145
- * @param fallbackPos position to insert if toInsert happens to be the first occurence
146
- * @param syntaxKind the ts.SyntaxKind of the subchildren to insert after
147
- * @return Change instance
148
- * @throw Error if toInsert is first occurence but fall back is not set
149
- */
150
- function insertAfterLastOccurrence(nodes, toInsert, file, fallbackPos, syntaxKind) {
151
- let lastItem;
152
- for (const node of nodes) {
153
- if (!lastItem || lastItem.getStart() < node.getStart()) {
154
- lastItem = node;
155
- }
156
- }
157
- if (syntaxKind && lastItem) {
158
- lastItem = findNodes(lastItem, syntaxKind).sort(nodesByPosition).pop();
159
- }
160
- if (!lastItem && fallbackPos == undefined) {
161
- throw new Error(`tried to insert ${toInsert} as first occurence with no fallback position`);
162
- }
163
- const lastItemPosition = lastItem ? lastItem.getEnd() : fallbackPos;
164
- return new change_1.InsertChange(file, lastItemPosition, toInsert);
165
- }
166
- exports.insertAfterLastOccurrence = insertAfterLastOccurrence;
167
- function _angularImportsFromNode(node) {
168
- const ms = node.moduleSpecifier;
169
- let modulePath;
170
- switch (ms.kind) {
171
- case ts.SyntaxKind.StringLiteral:
172
- modulePath = ms.text;
173
- break;
174
- default:
175
- return {};
176
- }
177
- if (!modulePath.startsWith('@angular/')) {
178
- return {};
179
- }
180
- if (node.importClause) {
181
- if (node.importClause.name) {
182
- // This is of the form `import Name from 'path'`. Ignore.
183
- return {};
184
- }
185
- else if (node.importClause.namedBindings) {
186
- const nb = node.importClause.namedBindings;
187
- if (nb.kind == ts.SyntaxKind.NamespaceImport) {
188
- // This is of the form `import * as name from 'path'`. Return `name.`.
189
- return {
190
- [nb.name.text + '.']: modulePath,
191
- };
192
- }
193
- else {
194
- // This is of the form `import {a,b,c} from 'path'`
195
- const namedImports = nb;
196
- return namedImports.elements
197
- .map((is) => (is.propertyName ? is.propertyName.text : is.name.text))
198
- .reduce((acc, curr) => {
199
- acc[curr] = modulePath;
200
- return acc;
201
- }, {});
202
- }
203
- }
204
- return {};
205
- }
206
- else {
207
- // This is of the form `import 'path';`. Nothing to do.
208
- return {};
209
- }
210
- }
211
- function getDecoratorMetadata(source, identifier, module) {
212
- const angularImports = findNodes(source, ts.isImportDeclaration)
213
- .map(node => _angularImportsFromNode(node))
214
- .reduce((acc, current) => {
215
- for (const key of Object.keys(current)) {
216
- acc[key] = current[key];
217
- }
218
- return acc;
219
- }, {});
220
- return getSourceNodes(source)
221
- .filter(node => {
222
- return (node.kind == ts.SyntaxKind.Decorator &&
223
- node.expression.kind == ts.SyntaxKind.CallExpression);
224
- })
225
- .map(node => node.expression)
226
- .filter(expr => {
227
- if (expr.expression.kind == ts.SyntaxKind.Identifier) {
228
- const id = expr.expression;
229
- return id.text == identifier && angularImports[id.text] === module;
230
- }
231
- else if (expr.expression.kind == ts.SyntaxKind.PropertyAccessExpression) {
232
- // This covers foo.NgModule when importing * as foo.
233
- const paExpr = expr.expression;
234
- // If the left expression is not an identifier, just give up at that point.
235
- if (paExpr.expression.kind !== ts.SyntaxKind.Identifier) {
236
- return false;
237
- }
238
- const id = paExpr.name.text;
239
- const moduleId = paExpr.expression.text;
240
- return id === identifier && angularImports[moduleId + '.'] === module;
241
- }
242
- return false;
243
- })
244
- .filter(expr => expr.arguments[0] && expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression)
245
- .map(expr => expr.arguments[0]);
246
- }
247
- exports.getDecoratorMetadata = getDecoratorMetadata;
248
- function getMetadataField(node, metadataField) {
249
- return (node.properties
250
- .filter(ts.isPropertyAssignment)
251
- // Filter out every fields that's not "metadataField". Also handles string literals
252
- // (but not expressions).
253
- .filter(({ name }) => {
254
- return (ts.isIdentifier(name) || ts.isStringLiteral(name)) && name.text === metadataField;
255
- }));
256
- }
257
- exports.getMetadataField = getMetadataField;
258
- function addSymbolToNgModuleMetadata(source, ngModulePath, metadataField, symbolName, importPath = null) {
259
- const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core');
260
- const node = nodes[0];
261
- // Find the decorator declaration.
262
- if (!node || !ts.isObjectLiteralExpression(node)) {
263
- return [];
264
- }
265
- // Get all the children property assignment of object literals.
266
- const matchingProperties = getMetadataField(node, metadataField);
267
- if (matchingProperties.length == 0) {
268
- // We haven't found the field in the metadata declaration. Insert a new field.
269
- let position;
270
- let toInsert;
271
- if (node.properties.length == 0) {
272
- position = node.getEnd() - 1;
273
- toInsert = `\n ${metadataField}: [\n${core_1.tags.indentBy(4) `${symbolName}`}\n ]\n`;
274
- }
275
- else {
276
- const childNode = node.properties[node.properties.length - 1];
277
- position = childNode.getEnd();
278
- // Get the indentation of the last element, if any.
279
- const text = childNode.getFullText(source);
280
- const matches = text.match(/^(\r?\n)(\s*)/);
281
- if (matches) {
282
- toInsert =
283
- `,${matches[0]}${metadataField}: [${matches[1]}` +
284
- `${core_1.tags.indentBy(matches[2].length + 2) `${symbolName}`}${matches[0]}]`;
285
- }
286
- else {
287
- toInsert = `, ${metadataField}: [${symbolName}]`;
288
- }
289
- }
290
- if (importPath !== null) {
291
- return [
292
- new change_1.InsertChange(ngModulePath, position, toInsert),
293
- insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath),
294
- ];
295
- }
296
- else {
297
- return [new change_1.InsertChange(ngModulePath, position, toInsert)];
298
- }
299
- }
300
- const assignment = matchingProperties[0];
301
- // If it's not an array, nothing we can do really.
302
- if (!ts.isPropertyAssignment(assignment) ||
303
- !ts.isArrayLiteralExpression(assignment.initializer)) {
304
- return [];
305
- }
306
- let expression;
307
- const assignmentInit = assignment.initializer;
308
- const elements = assignmentInit.elements;
309
- if (elements.length) {
310
- const symbolsArray = elements.map(node => core_1.tags.oneLine `${node.getText()}`);
311
- if (symbolsArray.includes(core_1.tags.oneLine `${symbolName}`)) {
312
- return [];
313
- }
314
- expression = elements[elements.length - 1];
315
- }
316
- else {
317
- expression = assignmentInit;
318
- }
319
- let toInsert;
320
- let position = expression.getEnd();
321
- if (ts.isArrayLiteralExpression(expression)) {
322
- // We found the field but it's empty. Insert it just before the `]`.
323
- position--;
324
- toInsert = `\n${core_1.tags.indentBy(4) `${symbolName}`}\n `;
325
- }
326
- else {
327
- // Get the indentation of the last element, if any.
328
- const text = expression.getFullText(source);
329
- const matches = text.match(/^(\r?\n)(\s*)/);
330
- if (matches) {
331
- toInsert = `,${matches[1]}${core_1.tags.indentBy(matches[2].length) `${symbolName}`}`;
332
- }
333
- else {
334
- toInsert = `, ${symbolName}`;
335
- }
336
- }
337
- if (importPath !== null) {
338
- return [
339
- new change_1.InsertChange(ngModulePath, position, toInsert),
340
- insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath),
341
- ];
342
- }
343
- return [new change_1.InsertChange(ngModulePath, position, toInsert)];
344
- }
345
- exports.addSymbolToNgModuleMetadata = addSymbolToNgModuleMetadata;
346
- /**
347
- * Custom function to insert a declaration (component, pipe, directive)
348
- * into NgModule declarations. It also imports the component.
349
- */
350
- function addDeclarationToModule(source, modulePath, classifiedName, importPath) {
351
- return addSymbolToNgModuleMetadata(source, modulePath, 'declarations', classifiedName, importPath);
352
- }
353
- exports.addDeclarationToModule = addDeclarationToModule;
354
- /**
355
- * Custom function to insert an NgModule into NgModule imports. It also imports the module.
356
- */
357
- function addImportToModule(source, modulePath, classifiedName, importPath) {
358
- return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath);
359
- }
360
- exports.addImportToModule = addImportToModule;
361
- /**
362
- * Custom function to insert a provider into NgModule. It also imports it.
363
- */
364
- function addProviderToModule(source, modulePath, classifiedName, importPath) {
365
- return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath);
366
- }
367
- exports.addProviderToModule = addProviderToModule;
368
- /**
369
- * Custom function to insert an export into NgModule. It also imports it.
370
- */
371
- function addExportToModule(source, modulePath, classifiedName, importPath) {
372
- return addSymbolToNgModuleMetadata(source, modulePath, 'exports', classifiedName, importPath);
373
- }
374
- exports.addExportToModule = addExportToModule;
375
- /**
376
- * Custom function to insert an export into NgModule. It also imports it.
377
- */
378
- function addBootstrapToModule(source, modulePath, classifiedName, importPath) {
379
- return addSymbolToNgModuleMetadata(source, modulePath, 'bootstrap', classifiedName, importPath);
380
- }
381
- exports.addBootstrapToModule = addBootstrapToModule;
382
- /**
383
- * Determine if an import already exists.
384
- */
385
- function isImported(source, classifiedName, importPath) {
386
- const allNodes = getSourceNodes(source);
387
- const matchingNodes = allNodes
388
- .filter(ts.isImportDeclaration)
389
- .filter(imp => ts.isStringLiteral(imp.moduleSpecifier) && imp.moduleSpecifier.text === importPath)
390
- .filter(imp => {
391
- if (!imp.importClause) {
392
- return false;
393
- }
394
- const nodes = findNodes(imp.importClause, ts.isImportSpecifier).filter(n => n.getText() === classifiedName);
395
- return nodes.length > 0;
396
- });
397
- return matchingNodes.length > 0;
398
- }
399
- exports.isImported = isImported;
400
- /**
401
- * Returns the RouterModule declaration from NgModule metadata, if any.
402
- */
403
- function getRouterModuleDeclaration(source) {
404
- const result = getDecoratorMetadata(source, 'NgModule', '@angular/core');
405
- const node = result[0];
406
- if (!node || !ts.isObjectLiteralExpression(node)) {
407
- return undefined;
408
- }
409
- const matchingProperties = getMetadataField(node, 'imports');
410
- const assignment = matchingProperties[0];
411
- if (!assignment || assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
412
- return;
413
- }
414
- const arrLiteral = assignment.initializer;
415
- return arrLiteral.elements
416
- .filter(el => el.kind === ts.SyntaxKind.CallExpression)
417
- .find(el => el.getText().startsWith('RouterModule'));
418
- }
419
- exports.getRouterModuleDeclaration = getRouterModuleDeclaration;
420
- /**
421
- * Adds a new route declaration to a router module (i.e. has a RouterModule declaration)
422
- */
423
- function addRouteDeclarationToModule(source, fileToAdd, routeLiteral) {
424
- const routerModuleExpr = getRouterModuleDeclaration(source);
425
- if (!routerModuleExpr) {
426
- throw new Error(`Couldn't find a route declaration in ${fileToAdd}.\n` +
427
- `Use the '--module' option to specify a different routing module.`);
428
- }
429
- const scopeConfigMethodArgs = routerModuleExpr.arguments;
430
- if (!scopeConfigMethodArgs.length) {
431
- const { line } = source.getLineAndCharacterOfPosition(routerModuleExpr.getStart());
432
- throw new Error(`The router module method doesn't have arguments ` + `at line ${line} in ${fileToAdd}`);
433
- }
434
- let routesArr;
435
- const routesArg = scopeConfigMethodArgs[0];
436
- // Check if the route declarations array is
437
- // an inlined argument of RouterModule or a standalone variable
438
- if (ts.isArrayLiteralExpression(routesArg)) {
439
- routesArr = routesArg;
440
- }
441
- else {
442
- const routesVarName = routesArg.getText();
443
- let routesVar;
444
- if (routesArg.kind === ts.SyntaxKind.Identifier) {
445
- routesVar = source.statements.filter(ts.isVariableStatement).find(v => {
446
- return v.declarationList.declarations[0].name.getText() === routesVarName;
447
- });
448
- }
449
- if (!routesVar) {
450
- const { line } = source.getLineAndCharacterOfPosition(routesArg.getStart());
451
- throw new Error(`No route declaration array was found that corresponds ` +
452
- `to router module at line ${line} in ${fileToAdd}`);
453
- }
454
- routesArr = findNodes(routesVar, ts.SyntaxKind.ArrayLiteralExpression, 1)[0];
455
- }
456
- const occurrencesCount = routesArr.elements.length;
457
- const text = routesArr.getFullText(source);
458
- let route = routeLiteral;
459
- let insertPos = routesArr.elements.pos;
460
- if (occurrencesCount > 0) {
461
- const lastRouteLiteral = [...routesArr.elements].pop();
462
- const lastRouteIsWildcard = ts.isObjectLiteralExpression(lastRouteLiteral) &&
463
- lastRouteLiteral.properties.some(n => ts.isPropertyAssignment(n) &&
464
- ts.isIdentifier(n.name) &&
465
- n.name.text === 'path' &&
466
- ts.isStringLiteral(n.initializer) &&
467
- n.initializer.text === '**');
468
- const indentation = text.match(/\r?\n(\r?)\s*/) || [];
469
- const routeText = `${indentation[0] || ' '}${routeLiteral}`;
470
- // Add the new route before the wildcard route
471
- // otherwise we'll always redirect to the wildcard route
472
- if (lastRouteIsWildcard) {
473
- insertPos = lastRouteLiteral.pos;
474
- route = `${routeText},`;
475
- }
476
- else {
477
- insertPos = lastRouteLiteral.end;
478
- route = `,${routeText}`;
479
- }
480
- }
481
- return new change_1.InsertChange(fileToAdd, insertPos, route);
482
- }
483
- exports.addRouteDeclarationToModule = addRouteDeclarationToModule;
484
- /** Asserts if the specified node is a named declaration (e.g. class, interface). */
485
- function isNamedNode(node) {
486
- return !!node.name && ts.isIdentifier(node.name);
487
- }
488
- /**
489
- * Determines if a SourceFile has a top-level declaration whose name matches a specific symbol.
490
- * Can be used to avoid conflicts when inserting new imports into a file.
491
- * @param sourceFile File in which to search.
492
- * @param symbolName Name of the symbol to search for.
493
- * @param skipModule Path of the module that the symbol may have been imported from. Used to
494
- * avoid false positives where the same symbol we're looking for may have been imported.
495
- */
496
- function hasTopLevelIdentifier(sourceFile, symbolName, skipModule = null) {
497
- for (const node of sourceFile.statements) {
498
- if (isNamedNode(node) && node.name.text === symbolName) {
499
- return true;
500
- }
501
- if (ts.isVariableStatement(node) &&
502
- node.declarationList.declarations.some(decl => {
503
- return isNamedNode(decl) && decl.name.text === symbolName;
504
- })) {
505
- return true;
506
- }
507
- if (ts.isImportDeclaration(node) &&
508
- ts.isStringLiteralLike(node.moduleSpecifier) &&
509
- node.moduleSpecifier.text !== skipModule &&
510
- node.importClause?.namedBindings &&
511
- ts.isNamedImports(node.importClause.namedBindings) &&
512
- node.importClause.namedBindings.elements.some(el => el.name.text === symbolName)) {
513
- return true;
514
- }
515
- }
516
- return false;
517
- }
518
- exports.hasTopLevelIdentifier = hasTopLevelIdentifier;
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.dev/license
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.insertImport = insertImport;
11
+ exports.findNodes = findNodes;
12
+ exports.getSourceNodes = getSourceNodes;
13
+ exports.findNode = findNode;
14
+ exports.insertAfterLastOccurrence = insertAfterLastOccurrence;
15
+ exports.getDecoratorMetadata = getDecoratorMetadata;
16
+ exports.getMetadataField = getMetadataField;
17
+ exports.addSymbolToNgModuleMetadata = addSymbolToNgModuleMetadata;
18
+ exports.addDeclarationToModule = addDeclarationToModule;
19
+ exports.addImportToModule = addImportToModule;
20
+ exports.addProviderToModule = addProviderToModule;
21
+ exports.addExportToModule = addExportToModule;
22
+ exports.addBootstrapToModule = addBootstrapToModule;
23
+ exports.isImported = isImported;
24
+ exports.getRouterModuleDeclaration = getRouterModuleDeclaration;
25
+ exports.addRouteDeclarationToModule = addRouteDeclarationToModule;
26
+ exports.hasTopLevelIdentifier = hasTopLevelIdentifier;
27
+ const tslib_1 = require("tslib");
28
+ const core_1 = require("@angular-devkit/core");
29
+ const ts = tslib_1.__importStar(require("typescript"));
30
+ const change_1 = require("./change");
31
+ const eol_1 = require("./eol");
32
+ /**
33
+ * Add Import `import { symbolName } from fileName` if the import doesn't exit
34
+ * already. Assumes fileToEdit can be resolved and accessed.
35
+ * @param fileToEdit File we want to add import to.
36
+ * @param symbolName Item to import.
37
+ * @param fileName Path to the file.
38
+ * @param isDefault If true, import follows style for importing default exports.
39
+ * @param alias Alias that the symbol should be inserted under.
40
+ * @return Change
41
+ */
42
+ function insertImport(source, fileToEdit, symbolName, fileName, isDefault = false, alias) {
43
+ const rootNode = source;
44
+ const allImports = findNodes(rootNode, ts.isImportDeclaration);
45
+ const importExpression = alias ? `${symbolName} as ${alias}` : symbolName;
46
+ // get nodes that map to import statements from the file fileName
47
+ const relevantImports = allImports.filter(node => {
48
+ return ts.isStringLiteralLike(node.moduleSpecifier) && node.moduleSpecifier.text === fileName;
49
+ });
50
+ if (relevantImports.length > 0) {
51
+ const hasNamespaceImport = relevantImports.some(node => {
52
+ return node.importClause?.namedBindings?.kind === ts.SyntaxKind.NamespaceImport;
53
+ });
54
+ // if imports * from fileName, don't add symbolName
55
+ if (hasNamespaceImport) {
56
+ return new change_1.NoopChange();
57
+ }
58
+ const imports = relevantImports.flatMap(node => {
59
+ return node.importClause?.namedBindings && ts.isNamedImports(node.importClause.namedBindings)
60
+ ? node.importClause.namedBindings.elements
61
+ : [];
62
+ });
63
+ // insert import if it's not there
64
+ if (!imports.some(node => (node.propertyName || node.name).text === symbolName)) {
65
+ const fallbackPos = findNodes(relevantImports[0], ts.SyntaxKind.CloseBraceToken)[0].getStart() ||
66
+ findNodes(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].getStart();
67
+ return insertAfterLastOccurrence(imports, `, ${importExpression}`, fileToEdit, fallbackPos);
68
+ }
69
+ return new change_1.NoopChange();
70
+ }
71
+ // no such import declaration exists
72
+ const useStrict = findNodes(rootNode, ts.isStringLiteral).filter(n => n.text === 'use strict');
73
+ let fallbackPos = 0;
74
+ if (useStrict.length > 0) {
75
+ fallbackPos = useStrict[0].end;
76
+ }
77
+ const open = isDefault ? '' : '{ ';
78
+ const close = isDefault ? '' : ' }';
79
+ const eol = (0, eol_1.getEOL)(rootNode.getText());
80
+ // if there are no imports or 'use strict' statement, insert import at beginning of file
81
+ const insertAtBeginning = allImports.length === 0 && useStrict.length === 0;
82
+ const separator = insertAtBeginning ? '' : `;${eol}`;
83
+ const toInsert = `${separator}import ${open}${importExpression}${close}` +
84
+ ` from '${fileName}'${insertAtBeginning ? `;${eol}` : ''}`;
85
+ return insertAfterLastOccurrence(allImports, toInsert, fileToEdit, fallbackPos, ts.SyntaxKind.StringLiteral);
86
+ }
87
+ function findNodes(node, kindOrGuard, max = Infinity, recursive = false) {
88
+ if (!node || max == 0) {
89
+ return [];
90
+ }
91
+ const test = typeof kindOrGuard === 'function'
92
+ ? kindOrGuard
93
+ : (node) => node.kind === kindOrGuard;
94
+ const arr = [];
95
+ if (test(node)) {
96
+ arr.push(node);
97
+ max--;
98
+ }
99
+ if (max > 0 && (recursive || !test(node))) {
100
+ for (const child of node.getChildren()) {
101
+ findNodes(child, test, max, recursive).forEach(node => {
102
+ if (max > 0) {
103
+ arr.push(node);
104
+ }
105
+ max--;
106
+ });
107
+ if (max <= 0) {
108
+ break;
109
+ }
110
+ }
111
+ }
112
+ return arr;
113
+ }
114
+ /**
115
+ * Get all the nodes from a source.
116
+ * @param sourceFile The source file object.
117
+ * @returns {Array<ts.Node>} An array of all the nodes in the source.
118
+ */
119
+ function getSourceNodes(sourceFile) {
120
+ const nodes = [sourceFile];
121
+ const result = [];
122
+ while (nodes.length > 0) {
123
+ const node = nodes.shift();
124
+ if (node) {
125
+ result.push(node);
126
+ if (node.getChildCount(sourceFile) >= 0) {
127
+ nodes.unshift(...node.getChildren());
128
+ }
129
+ }
130
+ }
131
+ return result;
132
+ }
133
+ function findNode(node, kind, text) {
134
+ if (node.kind === kind && node.getText() === text) {
135
+ return node;
136
+ }
137
+ let foundNode = null;
138
+ ts.forEachChild(node, childNode => {
139
+ foundNode = foundNode || findNode(childNode, kind, text);
140
+ });
141
+ return foundNode;
142
+ }
143
+ /**
144
+ * Helper for sorting nodes.
145
+ * @return function to sort nodes in increasing order of position in sourceFile
146
+ */
147
+ function nodesByPosition(first, second) {
148
+ return first.getStart() - second.getStart();
149
+ }
150
+ /**
151
+ * Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]`
152
+ * or after the last of occurence of `syntaxKind` if the last occurence is a sub child
153
+ * of ts.SyntaxKind[nodes[i].kind] and save the changes in file.
154
+ *
155
+ * @param nodes insert after the last occurence of nodes
156
+ * @param toInsert string to insert
157
+ * @param file file to insert changes into
158
+ * @param fallbackPos position to insert if toInsert happens to be the first occurence
159
+ * @param syntaxKind the ts.SyntaxKind of the subchildren to insert after
160
+ * @return Change instance
161
+ * @throw Error if toInsert is first occurence but fall back is not set
162
+ */
163
+ function insertAfterLastOccurrence(nodes, toInsert, file, fallbackPos, syntaxKind) {
164
+ let lastItem;
165
+ for (const node of nodes) {
166
+ if (!lastItem || lastItem.getStart() < node.getStart()) {
167
+ lastItem = node;
168
+ }
169
+ }
170
+ if (syntaxKind && lastItem) {
171
+ lastItem = findNodes(lastItem, syntaxKind).sort(nodesByPosition).pop();
172
+ }
173
+ if (!lastItem && fallbackPos == undefined) {
174
+ throw new Error(`tried to insert ${toInsert} as first occurence with no fallback position`);
175
+ }
176
+ const lastItemPosition = lastItem ? lastItem.getEnd() : fallbackPos;
177
+ return new change_1.InsertChange(file, lastItemPosition, toInsert);
178
+ }
179
+ function _angularImportsFromNode(node) {
180
+ const ms = node.moduleSpecifier;
181
+ let modulePath;
182
+ switch (ms.kind) {
183
+ case ts.SyntaxKind.StringLiteral:
184
+ modulePath = ms.text;
185
+ break;
186
+ default:
187
+ return {};
188
+ }
189
+ if (!modulePath.startsWith('@angular/')) {
190
+ return {};
191
+ }
192
+ if (node.importClause) {
193
+ if (node.importClause.name) {
194
+ // This is of the form `import Name from 'path'`. Ignore.
195
+ return {};
196
+ }
197
+ else if (node.importClause.namedBindings) {
198
+ const nb = node.importClause.namedBindings;
199
+ if (nb.kind == ts.SyntaxKind.NamespaceImport) {
200
+ // This is of the form `import * as name from 'path'`. Return `name.`.
201
+ return {
202
+ [nb.name.text + '.']: modulePath,
203
+ };
204
+ }
205
+ else {
206
+ // This is of the form `import {a,b,c} from 'path'`
207
+ const namedImports = nb;
208
+ return namedImports.elements
209
+ .map((is) => (is.propertyName ? is.propertyName.text : is.name.text))
210
+ .reduce((acc, curr) => {
211
+ acc[curr] = modulePath;
212
+ return acc;
213
+ }, {});
214
+ }
215
+ }
216
+ return {};
217
+ }
218
+ else {
219
+ // This is of the form `import 'path';`. Nothing to do.
220
+ return {};
221
+ }
222
+ }
223
+ function getDecoratorMetadata(source, identifier, module) {
224
+ const angularImports = findNodes(source, ts.isImportDeclaration)
225
+ .map(node => _angularImportsFromNode(node))
226
+ .reduce((acc, current) => {
227
+ for (const key of Object.keys(current)) {
228
+ acc[key] = current[key];
229
+ }
230
+ return acc;
231
+ }, {});
232
+ return getSourceNodes(source)
233
+ .filter(node => {
234
+ return (node.kind == ts.SyntaxKind.Decorator &&
235
+ node.expression.kind == ts.SyntaxKind.CallExpression);
236
+ })
237
+ .map(node => node.expression)
238
+ .filter(expr => {
239
+ if (expr.expression.kind == ts.SyntaxKind.Identifier) {
240
+ const id = expr.expression;
241
+ return id.text == identifier && angularImports[id.text] === module;
242
+ }
243
+ else if (expr.expression.kind == ts.SyntaxKind.PropertyAccessExpression) {
244
+ // This covers foo.NgModule when importing * as foo.
245
+ const paExpr = expr.expression;
246
+ // If the left expression is not an identifier, just give up at that point.
247
+ if (paExpr.expression.kind !== ts.SyntaxKind.Identifier) {
248
+ return false;
249
+ }
250
+ const id = paExpr.name.text;
251
+ const moduleId = paExpr.expression.text;
252
+ return id === identifier && angularImports[moduleId + '.'] === module;
253
+ }
254
+ return false;
255
+ })
256
+ .filter(expr => expr.arguments[0] && expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression)
257
+ .map(expr => expr.arguments[0]);
258
+ }
259
+ function getMetadataField(node, metadataField) {
260
+ return (node.properties
261
+ .filter(ts.isPropertyAssignment)
262
+ // Filter out every fields that's not "metadataField". Also handles string literals
263
+ // (but not expressions).
264
+ .filter(({ name }) => {
265
+ return (ts.isIdentifier(name) || ts.isStringLiteral(name)) && name.text === metadataField;
266
+ }));
267
+ }
268
+ function addSymbolToNgModuleMetadata(source, ngModulePath, metadataField, symbolName, importPath = null) {
269
+ const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core');
270
+ const node = nodes[0];
271
+ // Find the decorator declaration.
272
+ if (!node || !ts.isObjectLiteralExpression(node)) {
273
+ return [];
274
+ }
275
+ // Get all the children property assignment of object literals.
276
+ const matchingProperties = getMetadataField(node, metadataField);
277
+ if (matchingProperties.length == 0) {
278
+ // We haven't found the field in the metadata declaration. Insert a new field.
279
+ let position;
280
+ let toInsert;
281
+ if (node.properties.length == 0) {
282
+ position = node.getEnd() - 1;
283
+ toInsert = `\n ${metadataField}: [\n${core_1.tags.indentBy(4) `${symbolName}`}\n ]\n`;
284
+ }
285
+ else {
286
+ const childNode = node.properties[node.properties.length - 1];
287
+ position = childNode.getEnd();
288
+ // Get the indentation of the last element, if any.
289
+ const text = childNode.getFullText(source);
290
+ const matches = text.match(/^(\r?\n)(\s*)/);
291
+ if (matches) {
292
+ toInsert =
293
+ `,${matches[0]}${metadataField}: [${matches[1]}` +
294
+ `${core_1.tags.indentBy(matches[2].length + 2) `${symbolName}`}${matches[0]}]`;
295
+ }
296
+ else {
297
+ toInsert = `, ${metadataField}: [${symbolName}]`;
298
+ }
299
+ }
300
+ if (importPath !== null) {
301
+ return [
302
+ new change_1.InsertChange(ngModulePath, position, toInsert),
303
+ insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath),
304
+ ];
305
+ }
306
+ else {
307
+ return [new change_1.InsertChange(ngModulePath, position, toInsert)];
308
+ }
309
+ }
310
+ const assignment = matchingProperties[0];
311
+ // If it's not an array, nothing we can do really.
312
+ if (!ts.isPropertyAssignment(assignment) ||
313
+ !ts.isArrayLiteralExpression(assignment.initializer)) {
314
+ return [];
315
+ }
316
+ let expression;
317
+ const assignmentInit = assignment.initializer;
318
+ const elements = assignmentInit.elements;
319
+ if (elements.length) {
320
+ const symbolsArray = elements.map(node => core_1.tags.oneLine `${node.getText()}`);
321
+ if (symbolsArray.includes(core_1.tags.oneLine `${symbolName}`)) {
322
+ return [];
323
+ }
324
+ expression = elements[elements.length - 1];
325
+ }
326
+ else {
327
+ expression = assignmentInit;
328
+ }
329
+ let toInsert;
330
+ let position = expression.getEnd();
331
+ if (ts.isArrayLiteralExpression(expression)) {
332
+ // We found the field but it's empty. Insert it just before the `]`.
333
+ position--;
334
+ toInsert = `\n${core_1.tags.indentBy(4) `${symbolName}`}\n `;
335
+ }
336
+ else {
337
+ // Get the indentation of the last element, if any.
338
+ const text = expression.getFullText(source);
339
+ const matches = text.match(/^(\r?\n)(\s*)/);
340
+ if (matches) {
341
+ toInsert = `,${matches[1]}${core_1.tags.indentBy(matches[2].length) `${symbolName}`}`;
342
+ }
343
+ else {
344
+ toInsert = `, ${symbolName}`;
345
+ }
346
+ }
347
+ if (importPath !== null) {
348
+ return [
349
+ new change_1.InsertChange(ngModulePath, position, toInsert),
350
+ insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath),
351
+ ];
352
+ }
353
+ return [new change_1.InsertChange(ngModulePath, position, toInsert)];
354
+ }
355
+ /**
356
+ * Custom function to insert a declaration (component, pipe, directive)
357
+ * into NgModule declarations. It also imports the component.
358
+ */
359
+ function addDeclarationToModule(source, modulePath, classifiedName, importPath) {
360
+ return addSymbolToNgModuleMetadata(source, modulePath, 'declarations', classifiedName, importPath);
361
+ }
362
+ /**
363
+ * Custom function to insert an NgModule into NgModule imports. It also imports the module.
364
+ */
365
+ function addImportToModule(source, modulePath, classifiedName, importPath) {
366
+ return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath);
367
+ }
368
+ /**
369
+ * Custom function to insert a provider into NgModule. It also imports it.
370
+ */
371
+ function addProviderToModule(source, modulePath, classifiedName, importPath) {
372
+ return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath);
373
+ }
374
+ /**
375
+ * Custom function to insert an export into NgModule. It also imports it.
376
+ */
377
+ function addExportToModule(source, modulePath, classifiedName, importPath) {
378
+ return addSymbolToNgModuleMetadata(source, modulePath, 'exports', classifiedName, importPath);
379
+ }
380
+ /**
381
+ * Custom function to insert an export into NgModule. It also imports it.
382
+ */
383
+ function addBootstrapToModule(source, modulePath, classifiedName, importPath) {
384
+ return addSymbolToNgModuleMetadata(source, modulePath, 'bootstrap', classifiedName, importPath);
385
+ }
386
+ /**
387
+ * Determine if an import already exists.
388
+ */
389
+ function isImported(source, classifiedName, importPath) {
390
+ const allNodes = getSourceNodes(source);
391
+ const matchingNodes = allNodes
392
+ .filter(ts.isImportDeclaration)
393
+ .filter(imp => ts.isStringLiteral(imp.moduleSpecifier) && imp.moduleSpecifier.text === importPath)
394
+ .filter(imp => {
395
+ if (!imp.importClause) {
396
+ return false;
397
+ }
398
+ const nodes = findNodes(imp.importClause, ts.isImportSpecifier).filter(n => n.getText() === classifiedName);
399
+ return nodes.length > 0;
400
+ });
401
+ return matchingNodes.length > 0;
402
+ }
403
+ /**
404
+ * Returns the RouterModule declaration from NgModule metadata, if any.
405
+ */
406
+ function getRouterModuleDeclaration(source) {
407
+ const result = getDecoratorMetadata(source, 'NgModule', '@angular/core');
408
+ const node = result[0];
409
+ if (!node || !ts.isObjectLiteralExpression(node)) {
410
+ return undefined;
411
+ }
412
+ const matchingProperties = getMetadataField(node, 'imports');
413
+ const assignment = matchingProperties[0];
414
+ if (!assignment || assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
415
+ return;
416
+ }
417
+ const arrLiteral = assignment.initializer;
418
+ return arrLiteral.elements
419
+ .filter(el => el.kind === ts.SyntaxKind.CallExpression)
420
+ .find(el => el.getText().startsWith('RouterModule'));
421
+ }
422
+ /**
423
+ * Adds a new route declaration to a router module (i.e. has a RouterModule declaration)
424
+ */
425
+ function addRouteDeclarationToModule(source, fileToAdd, routeLiteral) {
426
+ const routerModuleExpr = getRouterModuleDeclaration(source);
427
+ if (!routerModuleExpr) {
428
+ throw new Error(`Couldn't find a route declaration in ${fileToAdd}.\n` +
429
+ `Use the '--module' option to specify a different routing module.`);
430
+ }
431
+ const scopeConfigMethodArgs = routerModuleExpr.arguments;
432
+ if (!scopeConfigMethodArgs.length) {
433
+ const { line } = source.getLineAndCharacterOfPosition(routerModuleExpr.getStart());
434
+ throw new Error(`The router module method doesn't have arguments ` + `at line ${line} in ${fileToAdd}`);
435
+ }
436
+ let routesArr;
437
+ const routesArg = scopeConfigMethodArgs[0];
438
+ // Check if the route declarations array is
439
+ // an inlined argument of RouterModule or a standalone variable
440
+ if (ts.isArrayLiteralExpression(routesArg)) {
441
+ routesArr = routesArg;
442
+ }
443
+ else {
444
+ const routesVarName = routesArg.getText();
445
+ let routesVar;
446
+ if (routesArg.kind === ts.SyntaxKind.Identifier) {
447
+ routesVar = source.statements.filter(ts.isVariableStatement).find(v => {
448
+ return v.declarationList.declarations[0].name.getText() === routesVarName;
449
+ });
450
+ }
451
+ if (!routesVar) {
452
+ const { line } = source.getLineAndCharacterOfPosition(routesArg.getStart());
453
+ throw new Error(`No route declaration array was found that corresponds ` +
454
+ `to router module at line ${line} in ${fileToAdd}`);
455
+ }
456
+ routesArr = findNodes(routesVar, ts.SyntaxKind.ArrayLiteralExpression, 1)[0];
457
+ }
458
+ const occurrencesCount = routesArr.elements.length;
459
+ const text = routesArr.getFullText(source);
460
+ let route = routeLiteral;
461
+ let insertPos = routesArr.elements.pos;
462
+ if (occurrencesCount > 0) {
463
+ const lastRouteLiteral = [...routesArr.elements].pop();
464
+ const lastRouteIsWildcard = ts.isObjectLiteralExpression(lastRouteLiteral) &&
465
+ lastRouteLiteral.properties.some(n => ts.isPropertyAssignment(n) &&
466
+ ts.isIdentifier(n.name) &&
467
+ n.name.text === 'path' &&
468
+ ts.isStringLiteral(n.initializer) &&
469
+ n.initializer.text === '**');
470
+ const indentation = text.match(/\r?\n(\r?)\s*/) || [];
471
+ const routeText = `${indentation[0] || ' '}${routeLiteral}`;
472
+ // Add the new route before the wildcard route
473
+ // otherwise we'll always redirect to the wildcard route
474
+ if (lastRouteIsWildcard) {
475
+ insertPos = lastRouteLiteral.pos;
476
+ route = `${routeText},`;
477
+ }
478
+ else {
479
+ insertPos = lastRouteLiteral.end;
480
+ route = `,${routeText}`;
481
+ }
482
+ }
483
+ return new change_1.InsertChange(fileToAdd, insertPos, route);
484
+ }
485
+ /** Asserts if the specified node is a named declaration (e.g. class, interface). */
486
+ function isNamedNode(node) {
487
+ return !!node.name && ts.isIdentifier(node.name);
488
+ }
489
+ /**
490
+ * Determines if a SourceFile has a top-level declaration whose name matches a specific symbol.
491
+ * Can be used to avoid conflicts when inserting new imports into a file.
492
+ * @param sourceFile File in which to search.
493
+ * @param symbolName Name of the symbol to search for.
494
+ * @param skipModule Path of the module that the symbol may have been imported from. Used to
495
+ * avoid false positives where the same symbol we're looking for may have been imported.
496
+ */
497
+ function hasTopLevelIdentifier(sourceFile, symbolName, skipModule = null) {
498
+ for (const node of sourceFile.statements) {
499
+ if (isNamedNode(node) && node.name.text === symbolName) {
500
+ return true;
501
+ }
502
+ if (ts.isVariableStatement(node) &&
503
+ node.declarationList.declarations.some(decl => {
504
+ return isNamedNode(decl) && decl.name.text === symbolName;
505
+ })) {
506
+ return true;
507
+ }
508
+ if (ts.isImportDeclaration(node) &&
509
+ ts.isStringLiteralLike(node.moduleSpecifier) &&
510
+ node.moduleSpecifier.text !== skipModule &&
511
+ node.importClause?.namedBindings &&
512
+ ts.isNamedImports(node.importClause.namedBindings) &&
513
+ node.importClause.namedBindings.elements.some(el => el.name.text === symbolName)) {
514
+ return true;
515
+ }
516
+ }
517
+ return false;
518
+ }
519
519
  //# sourceMappingURL=ast-utils.js.map