UNPKG

7.99 kBJavaScriptView Raw
1/**
2 * @license
3 * Copyright Google Inc. All Rights Reserved.
4 *
5 * Use of this source code is governed by an MIT-style license that can be
6 * found in the LICENSE file at https://angular.io/license
7 */
8"use strict";
9/**
10 * Transform template html and css into executable code.
11 * Intended to be used in a build step.
12 */
13var compiler = require('@angular/compiler');
14var core_1 = require('@angular/core');
15var fs_1 = require('fs');
16var path = require('path');
17var path_mapped_reflector_host_1 = require('./path_mapped_reflector_host');
18var private_import_core_1 = require('./private_import_core');
19var reflector_host_1 = require('./reflector_host');
20var static_reflection_capabilities_1 = require('./static_reflection_capabilities');
21var static_reflector_1 = require('./static_reflector');
22var GENERATED_FILES = /\.ngfactory\.ts$|\.css\.ts$|\.css\.shim\.ts$/;
23var GENERATED_OR_DTS_FILES = /\.d\.ts$|\.ngfactory\.ts$|\.css\.ts$|\.css\.shim\.ts$/;
24var PREAMBLE = "/**\n * @fileoverview This file is generated by the Angular 2 template compiler.\n * Do not edit.\n * @suppress {suspiciousCode,uselessCode,missingProperties}\n */\n /* tslint:disable */\n\n";
25var CodeGenerator = (function () {
26 function CodeGenerator(options, program, host, staticReflector, compiler, reflectorHost) {
27 this.options = options;
28 this.program = program;
29 this.host = host;
30 this.staticReflector = staticReflector;
31 this.compiler = compiler;
32 this.reflectorHost = reflectorHost;
33 }
34 // Write codegen in a directory structure matching the sources.
35 CodeGenerator.prototype.calculateEmitPath = function (filePath) {
36 var root = this.options.basePath;
37 for (var _i = 0, _a = this.options.rootDirs || []; _i < _a.length; _i++) {
38 var eachRootDir = _a[_i];
39 if (this.options.trace) {
40 console.error("Check if " + filePath + " is under rootDirs element " + eachRootDir);
41 }
42 if (path.relative(eachRootDir, filePath).indexOf('.') !== 0) {
43 root = eachRootDir;
44 }
45 }
46 // transplant the codegen path to be inside the `genDir`
47 var relativePath = path.relative(root, filePath);
48 while (relativePath.startsWith('..' + path.sep)) {
49 // Strip out any `..` path such as: `../node_modules/@foo` as we want to put everything
50 // into `genDir`.
51 relativePath = relativePath.substr(3);
52 }
53 return path.join(this.options.genDir, relativePath);
54 };
55 CodeGenerator.prototype.codegen = function (options) {
56 var _this = this;
57 var staticSymbols = extractProgramSymbols(this.program, this.staticReflector, this.reflectorHost, this.options);
58 return this.compiler.compileModules(staticSymbols, options).then(function (generatedModules) {
59 generatedModules.forEach(function (generatedModule) {
60 var sourceFile = _this.program.getSourceFile(generatedModule.fileUrl);
61 var emitPath = _this.calculateEmitPath(generatedModule.moduleUrl);
62 _this.host.writeFile(emitPath, PREAMBLE + generatedModule.source, false, function () { }, [sourceFile]);
63 });
64 });
65 };
66 CodeGenerator.create = function (options, cliOptions, program, compilerHost, reflectorHostContext, resourceLoader, reflectorHost) {
67 resourceLoader = resourceLoader || {
68 get: function (s) {
69 if (!compilerHost.fileExists(s)) {
70 // TODO: We should really have a test for error cases like this!
71 throw new Error("Compilation failed. Resource file not found: " + s);
72 }
73 return Promise.resolve(compilerHost.readFile(s));
74 }
75 };
76 var transFile = cliOptions.i18nFile;
77 var locale = cliOptions.locale;
78 var transContent = '';
79 if (transFile) {
80 if (!locale) {
81 throw new Error("The translation file (" + transFile + ") locale must be provided. Use the --locale option.");
82 }
83 transContent = fs_1.readFileSync(transFile, 'utf8');
84 }
85 var urlResolver = compiler.createOfflineCompileUrlResolver();
86 if (!reflectorHost) {
87 var usePathMapping = !!options.rootDirs && options.rootDirs.length > 0;
88 reflectorHost = usePathMapping ?
89 new path_mapped_reflector_host_1.PathMappedReflectorHost(program, compilerHost, options, reflectorHostContext) :
90 new reflector_host_1.ReflectorHost(program, compilerHost, options, reflectorHostContext);
91 }
92 var staticReflector = new static_reflector_1.StaticReflector(reflectorHost);
93 static_reflection_capabilities_1.StaticAndDynamicReflectionCapabilities.install(staticReflector);
94 var htmlParser = new compiler.I18NHtmlParser(new compiler.HtmlParser(), transContent, cliOptions.i18nFormat);
95 var config = new compiler.CompilerConfig({
96 genDebugInfo: options.debug === true,
97 defaultEncapsulation: core_1.ViewEncapsulation.Emulated,
98 logBindingUpdate: false,
99 useJit: false
100 });
101 var normalizer = new compiler.DirectiveNormalizer(resourceLoader, urlResolver, htmlParser, config);
102 var expressionParser = new compiler.Parser(new compiler.Lexer());
103 var elementSchemaRegistry = new compiler.DomElementSchemaRegistry();
104 var console = new private_import_core_1.Console();
105 var tmplParser = new compiler.TemplateParser(expressionParser, elementSchemaRegistry, htmlParser, console, []);
106 var resolver = new compiler.CompileMetadataResolver(new compiler.NgModuleResolver(staticReflector), new compiler.DirectiveResolver(staticReflector), new compiler.PipeResolver(staticReflector), elementSchemaRegistry, normalizer, staticReflector);
107 // TODO(vicb): do not pass cliOptions.i18nFormat here
108 var offlineCompiler = new compiler.OfflineCompiler(resolver, tmplParser, new compiler.StyleCompiler(urlResolver), new compiler.ViewCompiler(config, elementSchemaRegistry), new compiler.DirectiveWrapperCompiler(config, expressionParser, elementSchemaRegistry, console), new compiler.NgModuleCompiler(), new compiler.TypeScriptEmitter(reflectorHost), cliOptions.locale, cliOptions.i18nFormat, new compiler.AnimationParser(elementSchemaRegistry));
109 return new CodeGenerator(options, program, compilerHost, staticReflector, offlineCompiler, reflectorHost);
110 };
111 return CodeGenerator;
112}());
113exports.CodeGenerator = CodeGenerator;
114function extractProgramSymbols(program, staticReflector, reflectorHost, options) {
115 // Compare with false since the default should be true
116 var skipFileNames = options.generateCodeForLibraries === false ? GENERATED_OR_DTS_FILES : GENERATED_FILES;
117 var staticSymbols = [];
118 program.getSourceFiles()
119 .filter(function (sourceFile) { return !skipFileNames.test(sourceFile.fileName); })
120 .forEach(function (sourceFile) {
121 var absSrcPath = reflectorHost.getCanonicalFileName(sourceFile.fileName);
122 var moduleMetadata = staticReflector.getModuleMetadata(absSrcPath);
123 if (!moduleMetadata) {
124 console.warn("WARNING: no metadata found for " + absSrcPath);
125 return;
126 }
127 var metadata = moduleMetadata['metadata'];
128 if (!metadata) {
129 return;
130 }
131 for (var _i = 0, _a = Object.keys(metadata); _i < _a.length; _i++) {
132 var symbol = _a[_i];
133 if (metadata[symbol] && metadata[symbol].__symbolic == 'error') {
134 // Ignore symbols that are only included to record error information.
135 continue;
136 }
137 staticSymbols.push(reflectorHost.findDeclaration(absSrcPath, symbol, absSrcPath));
138 }
139 });
140 return staticSymbols;
141}
142exports.extractProgramSymbols = extractProgramSymbols;
143//# sourceMappingURL=codegen.js.map
\No newline at end of file