index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. var __importDefault = (this && this.__importDefault) || function (mod) {
  10. return (mod && mod.__esModule) ? mod : { "default": mod };
  11. };
  12. Object.defineProperty(exports, "__esModule", { value: true });
  13. exports.default = default_1;
  14. const schematics_1 = require("@angular-devkit/schematics");
  15. const posix_1 = require("node:path/posix");
  16. const typescript_1 = __importDefault(require("../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
  17. const ast_utils_1 = require("../utility/ast-utils");
  18. const change_1 = require("../utility/change");
  19. const ng_ast_utils_1 = require("../utility/ng-ast-utils");
  20. const util_1 = require("../utility/standalone/util");
  21. const workspace_1 = require("../utility/workspace");
  22. const workspace_models_1 = require("../utility/workspace-models");
  23. const APP_SHELL_ROUTE = 'shell';
  24. function getSourceFile(host, path) {
  25. const content = host.readText(path);
  26. const source = typescript_1.default.createSourceFile(path, content, typescript_1.default.ScriptTarget.Latest, true);
  27. return source;
  28. }
  29. function getServerModulePath(host, sourceRoot, mainPath) {
  30. const mainSource = getSourceFile(host, (0, posix_1.join)(sourceRoot, mainPath));
  31. const allNodes = (0, ast_utils_1.getSourceNodes)(mainSource);
  32. const expNode = allNodes.find((node) => typescript_1.default.isExportDeclaration(node));
  33. if (!expNode) {
  34. return null;
  35. }
  36. const relativePath = expNode.moduleSpecifier;
  37. const modulePath = (0, posix_1.join)(sourceRoot, `${relativePath.text}.ts`);
  38. return modulePath;
  39. }
  40. function getComponentTemplateInfo(host, componentPath) {
  41. const compSource = getSourceFile(host, componentPath);
  42. const compMetadata = (0, ast_utils_1.getDecoratorMetadata)(compSource, 'Component', '@angular/core')[0];
  43. return {
  44. templateProp: getMetadataProperty(compMetadata, 'template'),
  45. templateUrlProp: getMetadataProperty(compMetadata, 'templateUrl'),
  46. };
  47. }
  48. function getComponentTemplate(host, compPath, tmplInfo) {
  49. let template = '';
  50. if (tmplInfo.templateProp) {
  51. template = tmplInfo.templateProp.getFullText();
  52. }
  53. else if (tmplInfo.templateUrlProp) {
  54. const templateUrl = tmplInfo.templateUrlProp.initializer.text;
  55. const dir = (0, posix_1.dirname)(compPath);
  56. const templatePath = (0, posix_1.join)(dir, templateUrl);
  57. try {
  58. template = host.readText(templatePath);
  59. }
  60. catch { }
  61. }
  62. return template;
  63. }
  64. function getBootstrapComponentPath(host, mainPath) {
  65. let bootstrappingFilePath;
  66. let bootstrappingSource;
  67. let componentName;
  68. if ((0, ng_ast_utils_1.isStandaloneApp)(host, mainPath)) {
  69. // Standalone Application
  70. const bootstrapCall = (0, util_1.findBootstrapApplicationCall)(host, mainPath);
  71. componentName = bootstrapCall.arguments[0].getText();
  72. bootstrappingFilePath = mainPath;
  73. bootstrappingSource = getSourceFile(host, mainPath);
  74. }
  75. else {
  76. // NgModule Application
  77. const modulePath = (0, ng_ast_utils_1.getAppModulePath)(host, mainPath);
  78. const moduleSource = getSourceFile(host, modulePath);
  79. const metadataNode = (0, ast_utils_1.getDecoratorMetadata)(moduleSource, 'NgModule', '@angular/core')[0];
  80. const bootstrapProperty = getMetadataProperty(metadataNode, 'bootstrap');
  81. const arrLiteral = bootstrapProperty.initializer;
  82. componentName = arrLiteral.elements[0].getText();
  83. bootstrappingSource = moduleSource;
  84. bootstrappingFilePath = modulePath;
  85. }
  86. const componentRelativeFilePath = (0, ast_utils_1.getSourceNodes)(bootstrappingSource)
  87. .filter(typescript_1.default.isImportDeclaration)
  88. .filter((imp) => {
  89. return (0, ast_utils_1.findNode)(imp, typescript_1.default.SyntaxKind.Identifier, componentName);
  90. })
  91. .map((imp) => {
  92. const pathStringLiteral = imp.moduleSpecifier;
  93. return pathStringLiteral.text;
  94. })[0];
  95. return (0, posix_1.join)((0, posix_1.dirname)(bootstrappingFilePath), componentRelativeFilePath + '.ts');
  96. }
  97. // end helper functions.
  98. function validateProject(mainPath) {
  99. return (host) => {
  100. const routerOutletCheckRegex = /<router-outlet.*?>([\s\S]*?)(?:<\/router-outlet>)?/;
  101. const componentPath = getBootstrapComponentPath(host, mainPath);
  102. const tmpl = getComponentTemplateInfo(host, componentPath);
  103. const template = getComponentTemplate(host, componentPath, tmpl);
  104. if (!routerOutletCheckRegex.test(template)) {
  105. throw new schematics_1.SchematicsException(`Prerequisite for application shell is to define a router-outlet in your root component.`);
  106. }
  107. };
  108. }
  109. function getMetadataProperty(metadata, propertyName) {
  110. const properties = metadata.properties;
  111. const property = properties.filter(typescript_1.default.isPropertyAssignment).filter((prop) => {
  112. const name = prop.name;
  113. switch (name.kind) {
  114. case typescript_1.default.SyntaxKind.Identifier:
  115. return name.getText() === propertyName;
  116. case typescript_1.default.SyntaxKind.StringLiteral:
  117. return name.text === propertyName;
  118. }
  119. return false;
  120. })[0];
  121. return property;
  122. }
  123. function addAppShellConfigToWorkspace(options) {
  124. return (0, workspace_1.updateWorkspace)((workspace) => {
  125. const project = workspace.projects.get(options.project);
  126. if (!project) {
  127. return;
  128. }
  129. const buildTarget = project.targets.get('build');
  130. if (buildTarget?.builder === workspace_models_1.Builders.Application ||
  131. buildTarget?.builder === workspace_models_1.Builders.BuildApplication) {
  132. // Application builder configuration.
  133. const prodConfig = buildTarget.configurations?.production;
  134. if (!prodConfig) {
  135. throw new schematics_1.SchematicsException(`A "production" configuration is not defined for the "build" builder.`);
  136. }
  137. prodConfig.appShell = true;
  138. }
  139. });
  140. }
  141. function addServerRoutes(options) {
  142. return async (host) => {
  143. // The workspace gets updated so this needs to be reloaded
  144. const workspace = await (0, workspace_1.getWorkspace)(host);
  145. const project = workspace.projects.get(options.project);
  146. if (!project) {
  147. throw new schematics_1.SchematicsException(`Invalid project name (${options.project})`);
  148. }
  149. const modulePath = getServerModulePath(host, project.sourceRoot || 'src', 'main.server.ts');
  150. if (modulePath === null) {
  151. throw new schematics_1.SchematicsException('Server module not found.');
  152. }
  153. let moduleSource = getSourceFile(host, modulePath);
  154. if (!(0, ast_utils_1.isImported)(moduleSource, 'Routes', '@angular/router')) {
  155. const recorder = host.beginUpdate(modulePath);
  156. const routesChange = (0, ast_utils_1.insertImport)(moduleSource, modulePath, 'Routes', '@angular/router');
  157. if (routesChange) {
  158. (0, change_1.applyToUpdateRecorder)(recorder, [routesChange]);
  159. }
  160. const imports = (0, ast_utils_1.getSourceNodes)(moduleSource)
  161. .filter((node) => node.kind === typescript_1.default.SyntaxKind.ImportDeclaration)
  162. .sort((a, b) => a.getStart() - b.getStart());
  163. const insertPosition = imports[imports.length - 1].getEnd();
  164. const routeText = `\n\nconst routes: Routes = [ { path: '${APP_SHELL_ROUTE}', component: AppShellComponent }];`;
  165. recorder.insertRight(insertPosition, routeText);
  166. host.commitUpdate(recorder);
  167. }
  168. moduleSource = getSourceFile(host, modulePath);
  169. if (!(0, ast_utils_1.isImported)(moduleSource, 'RouterModule', '@angular/router')) {
  170. const recorder = host.beginUpdate(modulePath);
  171. const routerModuleChange = (0, ast_utils_1.insertImport)(moduleSource, modulePath, 'RouterModule', '@angular/router');
  172. if (routerModuleChange) {
  173. (0, change_1.applyToUpdateRecorder)(recorder, [routerModuleChange]);
  174. }
  175. const metadataChange = (0, ast_utils_1.addSymbolToNgModuleMetadata)(moduleSource, modulePath, 'imports', 'RouterModule.forRoot(routes)');
  176. if (metadataChange) {
  177. (0, change_1.applyToUpdateRecorder)(recorder, metadataChange);
  178. }
  179. host.commitUpdate(recorder);
  180. }
  181. };
  182. }
  183. function addStandaloneServerRoute(options) {
  184. return async (host) => {
  185. const workspace = await (0, workspace_1.getWorkspace)(host);
  186. const project = workspace.projects.get(options.project);
  187. if (!project) {
  188. throw new schematics_1.SchematicsException(`Project name "${options.project}" doesn't not exist.`);
  189. }
  190. const configFilePath = (0, posix_1.join)(project.sourceRoot ?? 'src', 'app/app.config.server.ts');
  191. if (!host.exists(configFilePath)) {
  192. throw new schematics_1.SchematicsException(`Cannot find "${configFilePath}".`);
  193. }
  194. const recorder = host.beginUpdate(configFilePath);
  195. let configSourceFile = getSourceFile(host, configFilePath);
  196. if (!(0, ast_utils_1.isImported)(configSourceFile, 'ROUTES', '@angular/router')) {
  197. const routesChange = (0, ast_utils_1.insertImport)(configSourceFile, configFilePath, 'ROUTES', '@angular/router');
  198. if (routesChange) {
  199. (0, change_1.applyToUpdateRecorder)(recorder, [routesChange]);
  200. }
  201. }
  202. configSourceFile = getSourceFile(host, configFilePath);
  203. const providersLiteral = (0, ast_utils_1.findNodes)(configSourceFile, typescript_1.default.isPropertyAssignment).find((n) => typescript_1.default.isArrayLiteralExpression(n.initializer) && n.name.getText() === 'providers')?.initializer;
  204. if (!providersLiteral) {
  205. throw new schematics_1.SchematicsException(`Cannot find the "providers" configuration in "${configFilePath}".`);
  206. }
  207. // Add route to providers literal.
  208. recorder.remove(providersLiteral.getStart(), providersLiteral.getWidth());
  209. const updatedProvidersString = [
  210. ...providersLiteral.elements.map((element) => ' ' + element.getText()),
  211. ` {
  212. provide: ROUTES,
  213. multi: true,
  214. useValue: [{
  215. path: '${APP_SHELL_ROUTE}',
  216. component: AppShellComponent
  217. }]
  218. }\n `,
  219. ];
  220. recorder.insertRight(providersLiteral.getStart(), `[\n${updatedProvidersString.join(',\n')}]`);
  221. (0, change_1.applyToUpdateRecorder)(recorder, [
  222. (0, ast_utils_1.insertImport)(configSourceFile, configFilePath, 'AppShellComponent', './app-shell/app-shell.component'),
  223. ]);
  224. host.commitUpdate(recorder);
  225. };
  226. }
  227. function addServerRoutingConfig(options, isStandalone) {
  228. return async (host) => {
  229. const workspace = await (0, workspace_1.getWorkspace)(host);
  230. const project = workspace.projects.get(options.project);
  231. if (!project) {
  232. throw new schematics_1.SchematicsException(`Project name "${options.project}" doesn't not exist.`);
  233. }
  234. const configFilePath = isStandalone
  235. ? (0, posix_1.join)(project.sourceRoot ?? 'src', 'app/app.config.server.ts')
  236. : getServerModulePath(host, project.sourceRoot || 'src', 'main.server.ts');
  237. if (!configFilePath || !host.exists(configFilePath)) {
  238. throw new schematics_1.SchematicsException(`Cannot find "${configFilePath}".`);
  239. }
  240. let recorder = host.beginUpdate(configFilePath);
  241. const configSourceFile = getSourceFile(host, configFilePath);
  242. const functionCall = (0, ast_utils_1.findNodes)(configSourceFile, typescript_1.default.isCallExpression,
  243. /** max */ undefined,
  244. /** recursive */ true).find((n) => typescript_1.default.isIdentifier(n.expression) && n.expression.getText() === 'provideServerRouting');
  245. if (!functionCall) {
  246. throw new schematics_1.SchematicsException(`Cannot find the "provideServerRouting" function call in "${configFilePath}".`);
  247. }
  248. recorder = host.beginUpdate(configFilePath);
  249. recorder.insertLeft(functionCall.end - 1, `, withAppShell(AppShellComponent)`);
  250. (0, change_1.applyToUpdateRecorder)(recorder, [
  251. (0, ast_utils_1.insertImport)(configSourceFile, configFilePath, 'withAppShell', '@angular/ssr'),
  252. (0, ast_utils_1.insertImport)(configSourceFile, configFilePath, 'AppShellComponent', './app-shell/app-shell.component'),
  253. ]);
  254. host.commitUpdate(recorder);
  255. };
  256. }
  257. function default_1(options) {
  258. return async (tree) => {
  259. const browserEntryPoint = await (0, util_1.getMainFilePath)(tree, options.project);
  260. const isStandalone = (0, ng_ast_utils_1.isStandaloneApp)(tree, browserEntryPoint);
  261. return (0, schematics_1.chain)([
  262. validateProject(browserEntryPoint),
  263. (0, schematics_1.schematic)('server', options),
  264. ...(options.serverRouting
  265. ? [(0, schematics_1.noop)()]
  266. : isStandalone
  267. ? [addStandaloneServerRoute(options)]
  268. : [addServerRoutes(options)]),
  269. options.serverRouting
  270. ? addServerRoutingConfig(options, isStandalone)
  271. : addAppShellConfigToWorkspace(options),
  272. (0, schematics_1.schematic)('component', {
  273. name: 'app-shell',
  274. module: 'app.module.server.ts',
  275. project: options.project,
  276. standalone: isStandalone,
  277. }),
  278. ]);
  279. };
  280. }