source: trip-planner-front/node_modules/@schematics/angular/app-shell/index.js@ 6a3a178

Last change on this file since 6a3a178 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 12.5 KB
Line 
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 */
9var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10 if (k2 === undefined) k2 = k;
11 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
12}) : (function(o, m, k, k2) {
13 if (k2 === undefined) k2 = k;
14 o[k2] = m[k];
15}));
16var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17 Object.defineProperty(o, "default", { enumerable: true, value: v });
18}) : function(o, v) {
19 o["default"] = v;
20});
21var __importStar = (this && this.__importStar) || function (mod) {
22 if (mod && mod.__esModule) return mod;
23 var result = {};
24 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
25 __setModuleDefault(result, mod);
26 return result;
27};
28Object.defineProperty(exports, "__esModule", { value: true });
29const core_1 = require("@angular-devkit/core");
30const schematics_1 = require("@angular-devkit/schematics");
31const ts = __importStar(require("../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
32const ast_utils_1 = require("../utility/ast-utils");
33const change_1 = require("../utility/change");
34const ng_ast_utils_1 = require("../utility/ng-ast-utils");
35const project_targets_1 = require("../utility/project-targets");
36const workspace_1 = require("../utility/workspace");
37const workspace_models_1 = require("../utility/workspace-models");
38function getSourceFile(host, path) {
39 const buffer = host.read(path);
40 if (!buffer) {
41 throw new schematics_1.SchematicsException(`Could not find ${path}.`);
42 }
43 const content = buffer.toString();
44 const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true);
45 return source;
46}
47function getServerModulePath(host, sourceRoot, mainPath) {
48 const mainSource = getSourceFile(host, core_1.join(core_1.normalize(sourceRoot), mainPath));
49 const allNodes = ast_utils_1.getSourceNodes(mainSource);
50 const expNode = allNodes.find((node) => ts.isExportDeclaration(node));
51 if (!expNode) {
52 return null;
53 }
54 const relativePath = expNode.moduleSpecifier;
55 const modulePath = core_1.normalize(`/${sourceRoot}/${relativePath.text}.ts`);
56 return modulePath;
57}
58function getComponentTemplateInfo(host, componentPath) {
59 const compSource = getSourceFile(host, componentPath);
60 const compMetadata = ast_utils_1.getDecoratorMetadata(compSource, 'Component', '@angular/core')[0];
61 return {
62 templateProp: getMetadataProperty(compMetadata, 'template'),
63 templateUrlProp: getMetadataProperty(compMetadata, 'templateUrl'),
64 };
65}
66function getComponentTemplate(host, compPath, tmplInfo) {
67 let template = '';
68 if (tmplInfo.templateProp) {
69 template = tmplInfo.templateProp.getFullText();
70 }
71 else if (tmplInfo.templateUrlProp) {
72 const templateUrl = tmplInfo.templateUrlProp.initializer.text;
73 const dir = core_1.dirname(core_1.normalize(compPath));
74 const templatePath = core_1.join(dir, templateUrl);
75 const buffer = host.read(templatePath);
76 if (buffer) {
77 template = buffer.toString();
78 }
79 }
80 return template;
81}
82function getBootstrapComponentPath(host, mainPath) {
83 const modulePath = ng_ast_utils_1.getAppModulePath(host, mainPath);
84 const moduleSource = getSourceFile(host, modulePath);
85 const metadataNode = ast_utils_1.getDecoratorMetadata(moduleSource, 'NgModule', '@angular/core')[0];
86 const bootstrapProperty = getMetadataProperty(metadataNode, 'bootstrap');
87 const arrLiteral = bootstrapProperty.initializer;
88 const componentSymbol = arrLiteral.elements[0].getText();
89 const relativePath = ast_utils_1.getSourceNodes(moduleSource)
90 .filter(ts.isImportDeclaration)
91 .filter((imp) => {
92 return ast_utils_1.findNode(imp, ts.SyntaxKind.Identifier, componentSymbol);
93 })
94 .map((imp) => {
95 const pathStringLiteral = imp.moduleSpecifier;
96 return pathStringLiteral.text;
97 })[0];
98 return core_1.join(core_1.dirname(core_1.normalize(modulePath)), relativePath + '.ts');
99}
100// end helper functions.
101function validateProject(mainPath) {
102 return (host, context) => {
103 const routerOutletCheckRegex = /<router\-outlet.*?>([\s\S]*?)<\/router\-outlet>/;
104 const componentPath = getBootstrapComponentPath(host, mainPath);
105 const tmpl = getComponentTemplateInfo(host, componentPath);
106 const template = getComponentTemplate(host, componentPath, tmpl);
107 if (!routerOutletCheckRegex.test(template)) {
108 const errorMsg = `Prerequisite for app shell is to define a router-outlet in your root component.`;
109 context.logger.error(errorMsg);
110 throw new schematics_1.SchematicsException(errorMsg);
111 }
112 };
113}
114function addUniversalTarget(options) {
115 return () => {
116 // Copy options.
117 const universalOptions = {
118 ...options,
119 };
120 // Delete non-universal options.
121 delete universalOptions.route;
122 return schematics_1.schematic('universal', universalOptions);
123 };
124}
125function addAppShellConfigToWorkspace(options) {
126 return (host, context) => {
127 if (!options.route) {
128 throw new schematics_1.SchematicsException(`Route is not defined`);
129 }
130 return workspace_1.updateWorkspace((workspace) => {
131 var _a, _b, _c, _d;
132 const project = workspace.projects.get(options.project);
133 if (!project) {
134 return;
135 }
136 // Validation of targets is handled already in the main function.
137 // Duplicate keys means that we have configurations in both server and build builders.
138 const serverConfigKeys = (_b = (_a = project.targets.get('server')) === null || _a === void 0 ? void 0 : _a.configurations) !== null && _b !== void 0 ? _b : {};
139 const buildConfigKeys = (_d = (_c = project.targets.get('build')) === null || _c === void 0 ? void 0 : _c.configurations) !== null && _d !== void 0 ? _d : {};
140 const configurationNames = Object.keys({
141 ...serverConfigKeys,
142 ...buildConfigKeys,
143 });
144 const configurations = {};
145 for (const key of configurationNames) {
146 if (!serverConfigKeys[key]) {
147 context.logger.warn(`Skipped adding "${key}" configuration to "app-shell" target as it's missing from "server" target.`);
148 continue;
149 }
150 if (!buildConfigKeys[key]) {
151 context.logger.warn(`Skipped adding "${key}" configuration to "app-shell" target as it's missing from "build" target.`);
152 continue;
153 }
154 configurations[key] = {
155 browserTarget: `${options.project}:build:${key}`,
156 serverTarget: `${options.project}:server:${key}`,
157 };
158 }
159 project.targets.add({
160 name: 'app-shell',
161 builder: workspace_models_1.Builders.AppShell,
162 defaultConfiguration: configurations['production'] ? 'production' : undefined,
163 options: {
164 route: options.route,
165 },
166 configurations,
167 });
168 });
169 };
170}
171function addRouterModule(mainPath) {
172 return (host) => {
173 const modulePath = ng_ast_utils_1.getAppModulePath(host, mainPath);
174 const moduleSource = getSourceFile(host, modulePath);
175 const changes = ast_utils_1.addImportToModule(moduleSource, modulePath, 'RouterModule', '@angular/router');
176 const recorder = host.beginUpdate(modulePath);
177 change_1.applyToUpdateRecorder(recorder, changes);
178 host.commitUpdate(recorder);
179 return host;
180 };
181}
182function getMetadataProperty(metadata, propertyName) {
183 const properties = metadata.properties;
184 const property = properties.filter(ts.isPropertyAssignment).filter((prop) => {
185 const name = prop.name;
186 switch (name.kind) {
187 case ts.SyntaxKind.Identifier:
188 return name.getText() === propertyName;
189 case ts.SyntaxKind.StringLiteral:
190 return name.text === propertyName;
191 }
192 return false;
193 })[0];
194 return property;
195}
196function addServerRoutes(options) {
197 return async (host) => {
198 // The workspace gets updated so this needs to be reloaded
199 const workspace = await workspace_1.getWorkspace(host);
200 const clientProject = workspace.projects.get(options.project);
201 if (!clientProject) {
202 throw new Error('Universal schematic removed client project.');
203 }
204 const clientServerTarget = clientProject.targets.get('server');
205 if (!clientServerTarget) {
206 throw new Error('Universal schematic did not add server target to client project.');
207 }
208 const clientServerOptions = clientServerTarget.options;
209 if (!clientServerOptions) {
210 throw new schematics_1.SchematicsException('Server target does not contain options.');
211 }
212 const modulePath = getServerModulePath(host, clientProject.sourceRoot || 'src', options.main);
213 if (modulePath === null) {
214 throw new schematics_1.SchematicsException('Universal/server module not found.');
215 }
216 let moduleSource = getSourceFile(host, modulePath);
217 if (!ast_utils_1.isImported(moduleSource, 'Routes', '@angular/router')) {
218 const recorder = host.beginUpdate(modulePath);
219 const routesChange = ast_utils_1.insertImport(moduleSource, modulePath, 'Routes', '@angular/router');
220 if (routesChange) {
221 change_1.applyToUpdateRecorder(recorder, [routesChange]);
222 }
223 const imports = ast_utils_1.getSourceNodes(moduleSource)
224 .filter((node) => node.kind === ts.SyntaxKind.ImportDeclaration)
225 .sort((a, b) => a.getStart() - b.getStart());
226 const insertPosition = imports[imports.length - 1].getEnd();
227 const routeText = `\n\nconst routes: Routes = [ { path: '${options.route}', component: AppShellComponent }];`;
228 recorder.insertRight(insertPosition, routeText);
229 host.commitUpdate(recorder);
230 }
231 moduleSource = getSourceFile(host, modulePath);
232 if (!ast_utils_1.isImported(moduleSource, 'RouterModule', '@angular/router')) {
233 const recorder = host.beginUpdate(modulePath);
234 const routerModuleChange = ast_utils_1.insertImport(moduleSource, modulePath, 'RouterModule', '@angular/router');
235 if (routerModuleChange) {
236 change_1.applyToUpdateRecorder(recorder, [routerModuleChange]);
237 }
238 const metadataChange = ast_utils_1.addSymbolToNgModuleMetadata(moduleSource, modulePath, 'imports', 'RouterModule.forRoot(routes)');
239 if (metadataChange) {
240 change_1.applyToUpdateRecorder(recorder, metadataChange);
241 }
242 host.commitUpdate(recorder);
243 }
244 };
245}
246function addShellComponent(options) {
247 const componentOptions = {
248 name: 'app-shell',
249 module: options.rootModuleFileName,
250 project: options.project,
251 };
252 return schematics_1.schematic('component', componentOptions);
253}
254function default_1(options) {
255 return async (tree) => {
256 const workspace = await workspace_1.getWorkspace(tree);
257 const clientProject = workspace.projects.get(options.project);
258 if (!clientProject || clientProject.extensions.projectType !== 'application') {
259 throw new schematics_1.SchematicsException(`A client project type of "application" is required.`);
260 }
261 const clientBuildTarget = clientProject.targets.get('build');
262 if (!clientBuildTarget) {
263 throw project_targets_1.targetBuildNotFoundError();
264 }
265 const clientBuildOptions = (clientBuildTarget.options ||
266 {});
267 return schematics_1.chain([
268 validateProject(clientBuildOptions.main),
269 clientProject.targets.has('server') ? schematics_1.noop() : addUniversalTarget(options),
270 addAppShellConfigToWorkspace(options),
271 addRouterModule(clientBuildOptions.main),
272 addServerRoutes(options),
273 addShellComponent(options),
274 ]);
275 };
276}
277exports.default = default_1;
Note: See TracBrowser for help on using the repository browser.