UNPKG

6.36 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3/**
4 * @license
5 * Copyright Google Inc. All Rights Reserved.
6 *
7 * Use of this source code is governed by an MIT-style license that can be
8 * found in the LICENSE file at https://angular.io/license
9 */
10const core_1 = require("@angular-devkit/core");
11const schematics_1 = require("@angular-devkit/schematics");
12const tasks_1 = require("@angular-devkit/schematics/tasks");
13const ts = require("../third_party/github.com/Microsoft/TypeScript/lib/typescript");
14const ast_utils_1 = require("../utility/ast-utils");
15const dependencies_1 = require("../utility/dependencies");
16const ng_ast_utils_1 = require("../utility/ng-ast-utils");
17const paths_1 = require("../utility/paths");
18const project_targets_1 = require("../utility/project-targets");
19const workspace_1 = require("../utility/workspace");
20function addDependencies() {
21 return (host, context) => {
22 const packageName = '@angular/service-worker';
23 context.logger.debug(`adding dependency (${packageName})`);
24 const coreDep = dependencies_1.getPackageJsonDependency(host, '@angular/core');
25 if (coreDep === null) {
26 throw new schematics_1.SchematicsException('Could not find version.');
27 }
28 const serviceWorkerDep = {
29 ...coreDep,
30 name: packageName,
31 };
32 dependencies_1.addPackageJsonDependency(host, serviceWorkerDep);
33 return host;
34 };
35}
36function updateAppModule(mainPath) {
37 return (host, context) => {
38 context.logger.debug('Updating appmodule');
39 const modulePath = ng_ast_utils_1.getAppModulePath(host, mainPath);
40 context.logger.debug(`module path: ${modulePath}`);
41 // add import
42 let moduleSource = getTsSourceFile(host, modulePath);
43 let importModule = 'ServiceWorkerModule';
44 let importPath = '@angular/service-worker';
45 if (!ast_utils_1.isImported(moduleSource, importModule, importPath)) {
46 const change = ast_utils_1.insertImport(moduleSource, modulePath, importModule, importPath);
47 if (change) {
48 const recorder = host.beginUpdate(modulePath);
49 recorder.insertLeft(change.pos, change.toAdd);
50 host.commitUpdate(recorder);
51 }
52 }
53 // add import for environments
54 // import { environment } from '../environments/environment';
55 moduleSource = getTsSourceFile(host, modulePath);
56 const environmentExportName = ast_utils_1.getEnvironmentExportName(moduleSource);
57 // if environemnt import already exists then use the found one
58 // otherwise use the default name
59 importModule = environmentExportName || 'environment';
60 // TODO: dynamically find environments relative path
61 importPath = '../environments/environment';
62 if (!environmentExportName) {
63 // if environment import was not found then insert the new one
64 // with default path and default export name
65 const change = ast_utils_1.insertImport(moduleSource, modulePath, importModule, importPath);
66 if (change) {
67 const recorder = host.beginUpdate(modulePath);
68 recorder.insertLeft(change.pos, change.toAdd);
69 host.commitUpdate(recorder);
70 }
71 }
72 // register SW in app module
73 const importText = `ServiceWorkerModule.register('ngsw-worker.js', { enabled: ${importModule}.production })`;
74 moduleSource = getTsSourceFile(host, modulePath);
75 const metadataChanges = ast_utils_1.addSymbolToNgModuleMetadata(moduleSource, modulePath, 'imports', importText);
76 if (metadataChanges) {
77 const recorder = host.beginUpdate(modulePath);
78 metadataChanges.forEach((change) => {
79 recorder.insertRight(change.pos, change.toAdd);
80 });
81 host.commitUpdate(recorder);
82 }
83 return host;
84 };
85}
86function getTsSourceFile(host, path) {
87 const buffer = host.read(path);
88 if (!buffer) {
89 throw new schematics_1.SchematicsException(`Could not read file (${path}).`);
90 }
91 const content = buffer.toString();
92 const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true);
93 return source;
94}
95function default_1(options) {
96 return async (host, context) => {
97 const workspace = await workspace_1.getWorkspace(host);
98 const project = workspace.projects.get(options.project);
99 if (!project) {
100 throw new schematics_1.SchematicsException(`Invalid project name (${options.project})`);
101 }
102 if (project.extensions.projectType !== 'application') {
103 throw new schematics_1.SchematicsException(`Service worker requires a project type of "application".`);
104 }
105 const buildTarget = project.targets.get('build');
106 if (!buildTarget) {
107 throw project_targets_1.targetBuildNotFoundError();
108 }
109 const buildOptions = (buildTarget.options || {});
110 let buildConfiguration;
111 if (options.configuration && buildTarget.configurations) {
112 buildConfiguration =
113 buildTarget.configurations[options.configuration];
114 }
115 const config = buildConfiguration || buildOptions;
116 const root = project.root;
117 config.serviceWorker = true;
118 config.ngswConfigPath = core_1.join(core_1.normalize(root), 'ngsw-config.json');
119 let { resourcesOutputPath = '' } = config;
120 if (resourcesOutputPath) {
121 resourcesOutputPath = core_1.normalize(`/${resourcesOutputPath}`);
122 }
123 const templateSource = schematics_1.apply(schematics_1.url('./files'), [
124 schematics_1.applyTemplates({
125 ...options,
126 resourcesOutputPath,
127 relativePathToWorkspaceRoot: paths_1.relativePathToWorkspaceRoot(project.root),
128 }),
129 schematics_1.move(project.root),
130 ]);
131 context.addTask(new tasks_1.NodePackageInstallTask());
132 return schematics_1.chain([
133 schematics_1.mergeWith(templateSource),
134 workspace_1.updateWorkspace(workspace),
135 addDependencies(),
136 updateAppModule(buildOptions.main),
137 ]);
138 };
139}
140exports.default = default_1;