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 | */
|
---|
9 | var __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 | }));
|
---|
16 | var __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 | });
|
---|
21 | var __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 | };
|
---|
28 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
29 | const core_1 = require("@angular-devkit/core");
|
---|
30 | const schematics_1 = require("@angular-devkit/schematics");
|
---|
31 | const tasks_1 = require("@angular-devkit/schematics/tasks");
|
---|
32 | const ts = __importStar(require("../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
|
---|
33 | const ast_utils_1 = require("../utility/ast-utils");
|
---|
34 | const change_1 = require("../utility/change");
|
---|
35 | const dependencies_1 = require("../utility/dependencies");
|
---|
36 | const ng_ast_utils_1 = require("../utility/ng-ast-utils");
|
---|
37 | const paths_1 = require("../utility/paths");
|
---|
38 | const project_targets_1 = require("../utility/project-targets");
|
---|
39 | const workspace_1 = require("../utility/workspace");
|
---|
40 | const workspace_models_1 = require("../utility/workspace-models");
|
---|
41 | function updateConfigFile(options, tsConfigDirectory) {
|
---|
42 | return workspace_1.updateWorkspace((workspace) => {
|
---|
43 | const clientProject = workspace.projects.get(options.project);
|
---|
44 | if (clientProject) {
|
---|
45 | // In case the browser builder hashes the assets
|
---|
46 | // we need to add this setting to the server builder
|
---|
47 | // as otherwise when assets it will be requested twice.
|
---|
48 | // One for the server which will be unhashed, and other on the client which will be hashed.
|
---|
49 | const getServerOptions = (options = {}) => {
|
---|
50 | return {
|
---|
51 | outputHashing: (options === null || options === void 0 ? void 0 : options.outputHashing) === 'all' ? 'media' : options === null || options === void 0 ? void 0 : options.outputHashing,
|
---|
52 | fileReplacements: options === null || options === void 0 ? void 0 : options.fileReplacements,
|
---|
53 | optimization: (options === null || options === void 0 ? void 0 : options.optimization) === undefined ? undefined : !!(options === null || options === void 0 ? void 0 : options.optimization),
|
---|
54 | sourceMap: options === null || options === void 0 ? void 0 : options.sourceMap,
|
---|
55 | localization: options === null || options === void 0 ? void 0 : options.localization,
|
---|
56 | stylePreprocessorOptions: options === null || options === void 0 ? void 0 : options.stylePreprocessorOptions,
|
---|
57 | resourcesOutputPath: options === null || options === void 0 ? void 0 : options.resourcesOutputPath,
|
---|
58 | deployUrl: options === null || options === void 0 ? void 0 : options.deployUrl,
|
---|
59 | i18nMissingTranslation: options === null || options === void 0 ? void 0 : options.i18nMissingTranslation,
|
---|
60 | preserveSymlinks: options === null || options === void 0 ? void 0 : options.preserveSymlinks,
|
---|
61 | extractLicenses: options === null || options === void 0 ? void 0 : options.extractLicenses,
|
---|
62 | inlineStyleLanguage: options === null || options === void 0 ? void 0 : options.inlineStyleLanguage,
|
---|
63 | };
|
---|
64 | };
|
---|
65 | const buildTarget = clientProject.targets.get('build');
|
---|
66 | if (buildTarget === null || buildTarget === void 0 ? void 0 : buildTarget.options) {
|
---|
67 | buildTarget.options.outputPath = `dist/${options.project}/browser`;
|
---|
68 | }
|
---|
69 | const buildConfigurations = buildTarget === null || buildTarget === void 0 ? void 0 : buildTarget.configurations;
|
---|
70 | const configurations = {};
|
---|
71 | if (buildConfigurations) {
|
---|
72 | for (const [key, options] of Object.entries(buildConfigurations)) {
|
---|
73 | configurations[key] = getServerOptions(options);
|
---|
74 | }
|
---|
75 | }
|
---|
76 | const mainPath = options.main;
|
---|
77 | const serverTsConfig = core_1.join(tsConfigDirectory, 'tsconfig.server.json');
|
---|
78 | clientProject.targets.add({
|
---|
79 | name: 'server',
|
---|
80 | builder: workspace_models_1.Builders.Server,
|
---|
81 | defaultConfiguration: 'production',
|
---|
82 | options: {
|
---|
83 | outputPath: `dist/${options.project}/server`,
|
---|
84 | main: core_1.join(core_1.normalize(clientProject.root), 'src', mainPath.endsWith('.ts') ? mainPath : mainPath + '.ts'),
|
---|
85 | tsConfig: serverTsConfig,
|
---|
86 | ...((buildTarget === null || buildTarget === void 0 ? void 0 : buildTarget.options) ? getServerOptions(buildTarget === null || buildTarget === void 0 ? void 0 : buildTarget.options) : {}),
|
---|
87 | },
|
---|
88 | configurations,
|
---|
89 | });
|
---|
90 | }
|
---|
91 | });
|
---|
92 | }
|
---|
93 | function findBrowserModuleImport(host, modulePath) {
|
---|
94 | const moduleBuffer = host.read(modulePath);
|
---|
95 | if (!moduleBuffer) {
|
---|
96 | throw new schematics_1.SchematicsException(`Module file (${modulePath}) not found`);
|
---|
97 | }
|
---|
98 | const moduleFileText = moduleBuffer.toString('utf-8');
|
---|
99 | const source = ts.createSourceFile(modulePath, moduleFileText, ts.ScriptTarget.Latest, true);
|
---|
100 | const decoratorMetadata = ast_utils_1.getDecoratorMetadata(source, 'NgModule', '@angular/core')[0];
|
---|
101 | const browserModuleNode = ast_utils_1.findNode(decoratorMetadata, ts.SyntaxKind.Identifier, 'BrowserModule');
|
---|
102 | if (browserModuleNode === null) {
|
---|
103 | throw new schematics_1.SchematicsException(`Cannot find BrowserModule import in ${modulePath}`);
|
---|
104 | }
|
---|
105 | return browserModuleNode;
|
---|
106 | }
|
---|
107 | function wrapBootstrapCall(mainFile) {
|
---|
108 | return (host) => {
|
---|
109 | const mainPath = core_1.normalize('/' + mainFile);
|
---|
110 | let bootstrapCall = ng_ast_utils_1.findBootstrapModuleCall(host, mainPath);
|
---|
111 | if (bootstrapCall === null) {
|
---|
112 | throw new schematics_1.SchematicsException('Bootstrap module not found.');
|
---|
113 | }
|
---|
114 | let bootstrapCallExpression = null;
|
---|
115 | let currentCall = bootstrapCall;
|
---|
116 | while (bootstrapCallExpression === null && currentCall.parent) {
|
---|
117 | currentCall = currentCall.parent;
|
---|
118 | if (ts.isExpressionStatement(currentCall) || ts.isVariableStatement(currentCall)) {
|
---|
119 | bootstrapCallExpression = currentCall;
|
---|
120 | }
|
---|
121 | }
|
---|
122 | bootstrapCall = currentCall;
|
---|
123 | // In case the bootstrap code is a variable statement
|
---|
124 | // we need to determine it's usage
|
---|
125 | if (bootstrapCallExpression && ts.isVariableStatement(bootstrapCallExpression)) {
|
---|
126 | const declaration = bootstrapCallExpression.declarationList.declarations[0];
|
---|
127 | const bootstrapVar = declaration.name.text;
|
---|
128 | const sf = bootstrapCallExpression.getSourceFile();
|
---|
129 | bootstrapCall = findCallExpressionNode(sf, bootstrapVar) || currentCall;
|
---|
130 | }
|
---|
131 | // indent contents
|
---|
132 | const triviaWidth = bootstrapCall.getLeadingTriviaWidth();
|
---|
133 | const beforeText = `function bootstrap() {\n` + ' '.repeat(triviaWidth > 2 ? triviaWidth + 1 : triviaWidth);
|
---|
134 | const afterText = `\n${triviaWidth > 2 ? ' '.repeat(triviaWidth - 1) : ''}};\n` +
|
---|
135 | `
|
---|
136 |
|
---|
137 | if (document.readyState === 'complete') {
|
---|
138 | bootstrap();
|
---|
139 | } else {
|
---|
140 | document.addEventListener('DOMContentLoaded', bootstrap);
|
---|
141 | }
|
---|
142 | `;
|
---|
143 | // in some cases we need to cater for a trailing semicolon such as;
|
---|
144 | // bootstrap().catch(err => console.log(err));
|
---|
145 | const lastToken = bootstrapCall.parent.getLastToken();
|
---|
146 | let endPos = bootstrapCall.getEnd();
|
---|
147 | if (lastToken && lastToken.kind === ts.SyntaxKind.SemicolonToken) {
|
---|
148 | endPos = lastToken.getEnd();
|
---|
149 | }
|
---|
150 | const recorder = host.beginUpdate(mainPath);
|
---|
151 | recorder.insertLeft(bootstrapCall.getStart(), beforeText);
|
---|
152 | recorder.insertRight(endPos, afterText);
|
---|
153 | host.commitUpdate(recorder);
|
---|
154 | };
|
---|
155 | }
|
---|
156 | function findCallExpressionNode(node, text) {
|
---|
157 | if (ts.isCallExpression(node) &&
|
---|
158 | ts.isIdentifier(node.expression) &&
|
---|
159 | node.expression.text === text) {
|
---|
160 | return node;
|
---|
161 | }
|
---|
162 | let foundNode = null;
|
---|
163 | ts.forEachChild(node, (childNode) => {
|
---|
164 | foundNode = findCallExpressionNode(childNode, text);
|
---|
165 | if (foundNode) {
|
---|
166 | return true;
|
---|
167 | }
|
---|
168 | });
|
---|
169 | return foundNode;
|
---|
170 | }
|
---|
171 | function addServerTransition(options, mainFile, clientProjectRoot) {
|
---|
172 | return (host) => {
|
---|
173 | const mainPath = core_1.normalize('/' + mainFile);
|
---|
174 | const bootstrapModuleRelativePath = ng_ast_utils_1.findBootstrapModulePath(host, mainPath);
|
---|
175 | const bootstrapModulePath = core_1.normalize(`/${clientProjectRoot}/src/${bootstrapModuleRelativePath}.ts`);
|
---|
176 | const browserModuleImport = findBrowserModuleImport(host, bootstrapModulePath);
|
---|
177 | const appId = options.appId;
|
---|
178 | const transitionCall = `.withServerTransition({ appId: '${appId}' })`;
|
---|
179 | const position = browserModuleImport.pos + browserModuleImport.getFullText().length;
|
---|
180 | const transitionCallChange = new change_1.InsertChange(bootstrapModulePath, position, transitionCall);
|
---|
181 | const transitionCallRecorder = host.beginUpdate(bootstrapModulePath);
|
---|
182 | transitionCallRecorder.insertLeft(transitionCallChange.pos, transitionCallChange.toAdd);
|
---|
183 | host.commitUpdate(transitionCallRecorder);
|
---|
184 | };
|
---|
185 | }
|
---|
186 | function addDependencies() {
|
---|
187 | return (host) => {
|
---|
188 | const coreDep = dependencies_1.getPackageJsonDependency(host, '@angular/core');
|
---|
189 | if (coreDep === null) {
|
---|
190 | throw new schematics_1.SchematicsException('Could not find version.');
|
---|
191 | }
|
---|
192 | const platformServerDep = {
|
---|
193 | ...coreDep,
|
---|
194 | name: '@angular/platform-server',
|
---|
195 | };
|
---|
196 | dependencies_1.addPackageJsonDependency(host, platformServerDep);
|
---|
197 | return host;
|
---|
198 | };
|
---|
199 | }
|
---|
200 | function default_1(options) {
|
---|
201 | return async (host, context) => {
|
---|
202 | const workspace = await workspace_1.getWorkspace(host);
|
---|
203 | const clientProject = workspace.projects.get(options.project);
|
---|
204 | if (!clientProject || clientProject.extensions.projectType !== 'application') {
|
---|
205 | throw new schematics_1.SchematicsException(`Universal requires a project type of "application".`);
|
---|
206 | }
|
---|
207 | const clientBuildTarget = clientProject.targets.get('build');
|
---|
208 | if (!clientBuildTarget) {
|
---|
209 | throw project_targets_1.targetBuildNotFoundError();
|
---|
210 | }
|
---|
211 | const clientBuildOptions = (clientBuildTarget.options ||
|
---|
212 | {});
|
---|
213 | const clientTsConfig = core_1.normalize(clientBuildOptions.tsConfig);
|
---|
214 | const tsConfigExtends = core_1.basename(clientTsConfig);
|
---|
215 | // this is needed because prior to version 8, tsconfig might have been in 'src'
|
---|
216 | // and we don't want to break the 'ng add @nguniversal/express-engine schematics'
|
---|
217 | const rootInSrc = clientProject.root === '' && clientTsConfig.includes('src/');
|
---|
218 | const tsConfigDirectory = core_1.join(core_1.normalize(clientProject.root), rootInSrc ? 'src' : '');
|
---|
219 | if (!options.skipInstall) {
|
---|
220 | context.addTask(new tasks_1.NodePackageInstallTask());
|
---|
221 | }
|
---|
222 | const templateSource = schematics_1.apply(schematics_1.url('./files/src'), [
|
---|
223 | schematics_1.applyTemplates({
|
---|
224 | ...core_1.strings,
|
---|
225 | ...options,
|
---|
226 | stripTsExtension: (s) => s.replace(/\.ts$/, ''),
|
---|
227 | hasLocalizePackage: !!dependencies_1.getPackageJsonDependency(host, '@angular/localize'),
|
---|
228 | }),
|
---|
229 | schematics_1.move(core_1.join(core_1.normalize(clientProject.root), 'src')),
|
---|
230 | ]);
|
---|
231 | const rootSource = schematics_1.apply(schematics_1.url('./files/root'), [
|
---|
232 | schematics_1.applyTemplates({
|
---|
233 | ...core_1.strings,
|
---|
234 | ...options,
|
---|
235 | stripTsExtension: (s) => s.replace(/\.ts$/, ''),
|
---|
236 | tsConfigExtends,
|
---|
237 | relativePathToWorkspaceRoot: paths_1.relativePathToWorkspaceRoot(tsConfigDirectory),
|
---|
238 | rootInSrc,
|
---|
239 | }),
|
---|
240 | schematics_1.move(tsConfigDirectory),
|
---|
241 | ]);
|
---|
242 | return schematics_1.chain([
|
---|
243 | schematics_1.mergeWith(templateSource),
|
---|
244 | schematics_1.mergeWith(rootSource),
|
---|
245 | addDependencies(),
|
---|
246 | updateConfigFile(options, tsConfigDirectory),
|
---|
247 | wrapBootstrapCall(clientBuildOptions.main),
|
---|
248 | addServerTransition(options, clientBuildOptions.main, clientProject.root),
|
---|
249 | ]);
|
---|
250 | };
|
---|
251 | }
|
---|
252 | exports.default = default_1;
|
---|