index.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 project_targets_1 = require("../utility/project-targets");
  21. const util_1 = require("../utility/standalone/util");
  22. const workspace_1 = require("../utility/workspace");
  23. function getSourceFile(host, path) {
  24. const content = host.readText(path);
  25. const source = typescript_1.default.createSourceFile(path, content, typescript_1.default.ScriptTarget.Latest, true);
  26. return source;
  27. }
  28. function getServerModulePath(host, sourceRoot, mainPath) {
  29. const mainSource = getSourceFile(host, (0, posix_1.join)(sourceRoot, mainPath));
  30. const allNodes = (0, ast_utils_1.getSourceNodes)(mainSource);
  31. const expNode = allNodes.find((node) => typescript_1.default.isExportDeclaration(node));
  32. if (!expNode) {
  33. return null;
  34. }
  35. const relativePath = expNode.moduleSpecifier;
  36. const modulePath = (0, posix_1.join)(sourceRoot, `${relativePath.text}.ts`);
  37. return modulePath;
  38. }
  39. function getComponentTemplateInfo(host, componentPath) {
  40. const compSource = getSourceFile(host, componentPath);
  41. const compMetadata = (0, ast_utils_1.getDecoratorMetadata)(compSource, 'Component', '@angular/core')[0];
  42. return {
  43. templateProp: getMetadataProperty(compMetadata, 'template'),
  44. templateUrlProp: getMetadataProperty(compMetadata, 'templateUrl'),
  45. };
  46. }
  47. function getComponentTemplate(host, compPath, tmplInfo) {
  48. let template = '';
  49. if (tmplInfo.templateProp) {
  50. template = tmplInfo.templateProp.getFullText();
  51. }
  52. else if (tmplInfo.templateUrlProp) {
  53. const templateUrl = tmplInfo.templateUrlProp.initializer.text;
  54. const dir = (0, posix_1.dirname)(compPath);
  55. const templatePath = (0, posix_1.join)(dir, templateUrl);
  56. try {
  57. template = host.readText(templatePath);
  58. }
  59. catch { }
  60. }
  61. return template;
  62. }
  63. function getBootstrapComponentPath(host, mainPath) {
  64. let bootstrappingFilePath;
  65. let bootstrappingSource;
  66. let componentName;
  67. if ((0, ng_ast_utils_1.isStandaloneApp)(host, mainPath)) {
  68. // Standalone Application
  69. const bootstrapCall = (0, util_1.findBootstrapApplicationCall)(host, mainPath);
  70. componentName = bootstrapCall.arguments[0].getText();
  71. bootstrappingFilePath = mainPath;
  72. bootstrappingSource = getSourceFile(host, mainPath);
  73. }
  74. else {
  75. // NgModule Application
  76. const modulePath = (0, ng_ast_utils_1.getAppModulePath)(host, mainPath);
  77. const moduleSource = getSourceFile(host, modulePath);
  78. const metadataNode = (0, ast_utils_1.getDecoratorMetadata)(moduleSource, 'NgModule', '@angular/core')[0];
  79. const bootstrapProperty = getMetadataProperty(metadataNode, 'bootstrap');
  80. const arrLiteral = bootstrapProperty.initializer;
  81. componentName = arrLiteral.elements[0].getText();
  82. bootstrappingSource = moduleSource;
  83. bootstrappingFilePath = modulePath;
  84. }
  85. const componentRelativeFilePath = (0, ast_utils_1.getSourceNodes)(bootstrappingSource)
  86. .filter(typescript_1.default.isImportDeclaration)
  87. .filter((imp) => {
  88. return (0, ast_utils_1.findNode)(imp, typescript_1.default.SyntaxKind.Identifier, componentName);
  89. })
  90. .map((imp) => {
  91. const pathStringLiteral = imp.moduleSpecifier;
  92. return pathStringLiteral.text;
  93. })[0];
  94. return (0, posix_1.join)((0, posix_1.dirname)(bootstrappingFilePath), componentRelativeFilePath + '.ts');
  95. }
  96. // end helper functions.
  97. function validateProject(mainPath) {
  98. return (host) => {
  99. const routerOutletCheckRegex = /<router-outlet.*?>([\s\S]*?)(?:<\/router-outlet>)?/;
  100. const componentPath = getBootstrapComponentPath(host, mainPath);
  101. const tmpl = getComponentTemplateInfo(host, componentPath);
  102. const template = getComponentTemplate(host, componentPath, tmpl);
  103. if (!routerOutletCheckRegex.test(template)) {
  104. throw new schematics_1.SchematicsException(`Prerequisite for application shell is to define a router-outlet in your root component.`);
  105. }
  106. };
  107. }
  108. function getMetadataProperty(metadata, propertyName) {
  109. const properties = metadata.properties;
  110. const property = properties.filter(typescript_1.default.isPropertyAssignment).filter((prop) => {
  111. const name = prop.name;
  112. switch (name.kind) {
  113. case typescript_1.default.SyntaxKind.Identifier:
  114. return name.getText() === propertyName;
  115. case typescript_1.default.SyntaxKind.StringLiteral:
  116. return name.text === propertyName;
  117. }
  118. return false;
  119. })[0];
  120. return property;
  121. }
  122. function addServerRoutingConfig(options, isStandalone) {
  123. return async (host) => {
  124. const workspace = await (0, workspace_1.getWorkspace)(host);
  125. const project = workspace.projects.get(options.project);
  126. if (!project) {
  127. throw new schematics_1.SchematicsException(`Project name "${options.project}" doesn't not exist.`);
  128. }
  129. const configFilePath = isStandalone
  130. ? (0, posix_1.join)(project.sourceRoot ?? 'src', 'app/app.config.server.ts')
  131. : getServerModulePath(host, project.sourceRoot || 'src', 'main.server.ts');
  132. if (!configFilePath || !host.exists(configFilePath)) {
  133. throw new schematics_1.SchematicsException(`Cannot find "${configFilePath}".`);
  134. }
  135. let recorder = host.beginUpdate(configFilePath);
  136. const configSourceFile = getSourceFile(host, configFilePath);
  137. const functionCall = (0, ast_utils_1.findNodes)(configSourceFile, typescript_1.default.isCallExpression,
  138. /** max */ undefined,
  139. /** recursive */ true).find((n) => typescript_1.default.isIdentifier(n.expression) && n.expression.getText() === 'provideServerRendering');
  140. if (!functionCall) {
  141. throw new schematics_1.SchematicsException(`Cannot find the "provideServerRendering" function call in "${configFilePath}".`);
  142. }
  143. recorder = host.beginUpdate(configFilePath);
  144. recorder.insertLeft(functionCall.end - 1, `, withAppShell(AppShell)`);
  145. (0, change_1.applyToUpdateRecorder)(recorder, [
  146. (0, ast_utils_1.insertImport)(configSourceFile, configFilePath, 'withAppShell', '@angular/ssr'),
  147. (0, ast_utils_1.insertImport)(configSourceFile, configFilePath, 'AppShell', './app-shell/app-shell'),
  148. ]);
  149. host.commitUpdate(recorder);
  150. };
  151. }
  152. function default_1(options) {
  153. return async (tree) => {
  154. const browserEntryPoint = await (0, util_1.getMainFilePath)(tree, options.project);
  155. const isStandalone = (0, ng_ast_utils_1.isStandaloneApp)(tree, browserEntryPoint);
  156. const workspace = await (0, workspace_1.getWorkspace)(tree);
  157. const project = workspace.projects.get(options.project);
  158. if (!project) {
  159. throw (0, project_targets_1.targetBuildNotFoundError)();
  160. }
  161. return (0, schematics_1.chain)([
  162. validateProject(browserEntryPoint),
  163. (0, schematics_1.schematic)('server', options),
  164. addServerRoutingConfig(options, isStandalone),
  165. (0, schematics_1.schematic)('component', {
  166. name: 'app-shell',
  167. module: 'app.module.server.ts',
  168. project: options.project,
  169. standalone: isStandalone,
  170. }),
  171. ]);
  172. };
  173. }