-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathng-codegen.js
231 lines (200 loc) · 7.27 KB
/
ng-codegen.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import 'reflect-metadata';
const path = Npm.require('path');
const ts = Npm.require('typescript');
const { NgModule } = Npm.require('@angular/core');
const {
ReflectorHost,
StaticReflector,
CodeGenerator,
PathMappedCompilerHost,
CompilerHost,
} = Npm.require('@angular/compiler-cli');
import {
removeTsExtension,
getMeteorPath,
getFullPath,
isRooted,
basePath,
} from './file-utils';
import Logger from './logger';
const ngCompilerOptions = {
transitiveModules: true
};
function resolveModuleNames(ngcOptions, ngcHost) {
return (filePaths, containingFile) => {
return filePaths.map(filePath => {
if (STATIC_ASSET.test(filePath)) {
const dirPath = ts.getDirectoryPath(containingFile);
return {
resolvedFileName: path.join(dirPath, filePath),
isExternalLibraryImport: false
}
}
const resolved = ts.resolveModuleName(
filePath, containingFile, ngcOptions, ngcHost);
return resolved.resolvedModule;
});
}
}
function createNgcTsHost(ngcOptions, getFileContent) {
const defaultHost = ts.createCompilerHost(ngcOptions, true);
const customHost = {
getSourceFile: (filePath, languageVersion, onError) => {
const content = getFileContent(filePath);
if (content) {
return ts.createSourceFile(filePath, content, languageVersion, true);
}
return defaultHost.getSourceFile(filePath, languageVersion, onError);
},
realpath: filePath => filePath,
fileExists: filePath => {
const exists = defaultHost.fileExists(filePath);
return exists || !!getFileContent(filePath);
},
directoryExists: dirName => {
const exists = defaultHost.directoryExists(dirName);
return exists || !!getFileContent(path.join(dirName, 'index.ts'));
},
trace: msg => {
Logger.log(msg);
},
};
const ngcHost = _.extend({}, defaultHost, customHost);
return ngcHost;
}
function createNgcTsProgram(filePaths, ngcOptions, ngcHost) {
const program = ts.createProgram(filePaths, ngcOptions, ngcHost);
const getSourceFile = program.getSourceFile;
program.getSourceFile = filePath => {
let sf = getSourceFile.call(this, filePath);
if (sf) return sf;
filePath = getMeteorPath(filePath);
return getSourceFile.call(this, filePath);
};
return program;
}
function createCompilerHostContext(ngcHost) {
const assumedExists = {};
let reflectorContext = {
fileExists(filePath) {
return assumedExists[filePath] || ngcHost.fileExists(filePath);
},
assumeFileExists(filePath) {
assumedExists[filePath] = true;
},
readResource(filePath) {
if (! ngcHost.fileExists(filePath)) {
throw new Error(`Compilation failed. Resource file not found: ${filePath}`);
}
return Promise.resolve(ngcHost.readFile(filePath));
}
}
return _.extend({}, ngcHost, reflectorContext);
}
function createCompilerHost(tsProgram, ngcOptions, compilerHostContext, usePathMapping) {
return usePathMapping ?
new PathMappedCompilerHost(tsProgram, ngcOptions, compilerHostContext) :
new CompilerHost(tsProgram, ngcOptions, compilerHostContext);
}
function genBootstrapCode(moduleFilePath) {
const path = removeTsExtension(moduleFilePath);
return `
import {platformBrowser} from '@angular/platform-browser';
import {AppModuleNgFactory} from '${path}.ngfactory';
Meteor.startup(function() {
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);
});
`;
}
export function hasDynamicBootstrap(code) {
return code.indexOf('platformBrowserDynamic') !== -1;
}
export function removeDynamicBootstrap(code, mainModuleName) {
code = code
.replace(/(import\s*{[^{]*platformBrowserDynamic[^}]*})/, '//\$1')
.replace(/([^\n]*platformBrowserDynamic\(\))/, '//\$1')
.replace(/([^\n]*bootstrapModule\()/, '//\$1');
mainModuleName = mainModuleName.replace('.', '\.');
const regExp = new RegExp(`([^\\n]*import[\\s]+.*${mainModuleName})`);
code = code.replace(regExp, '//\$1');
return code;
}
function findBootstrapModule(ngModules) {
return ngModules.find(module =>
module.bootstrapComponents && module.bootstrapComponents.length);
}
function extractProgramSymbols(symbolResolver, filePaths, host) {
const staticSymbols = [];
filePaths
.filter(filePath => host.isSourceFile(filePath))
.forEach(sf => {
symbolResolver.getSymbolsOf(sf).forEach((symbol) => {
const resolvedSymbol = symbolResolver.resolveSymbol(symbol);
const symbolMeta = resolvedSymbol.metadata;
if (symbolMeta && symbolMeta.__symbolic !== 'error') {
staticSymbols.push(resolvedSymbol.symbol);
}
});
});
return staticSymbols;
}
const GENERATED_FILES = /\.d\.ts$|\.ngfactory\.ts$/;
const GENERATED_SUMMARY = /\.json$/;
function extractNgModules(metadataResolver, programSymbols) {
const ngModuleMap = new Map();
programSymbols
.filter(symbol => ! GENERATED_FILES.test(symbol.filePath))
.forEach(symbol => {
const ngModule = metadataResolver.getNgModuleMetadata(symbol, false);
if (ngModule && ! ngModuleMap.has(symbol)) {
ngModuleMap.set(ngModule.type.reference, ngModule);
}
});
return ngModuleMap;
}
export class CodeGeneratorWrapper {
static generate(filePaths, ngcOptions, getMeteorFileContent) {
const tsHost = createNgcTsHost(ngcOptions, getMeteorFileContent);
const tsProgram = createNgcTsProgram(filePaths, ngcOptions, tsHost);
const compilerHostContext = createCompilerHostContext(tsHost);
const usePathMapping = !!ngcOptions.rootDirs && ngcOptions.rootDirs.length > 0;
const compilerHost = createCompilerHost(
tsProgram, ngcOptions, compilerHostContext, usePathMapping);
const { compiler } = CodeGenerator.create(
ngcOptions, {}, tsProgram, tsHost, compilerHostContext, compilerHost);
const ngcFilePaths = tsProgram.getSourceFiles().map(sf => sf.fileName);
return compiler
.compileAll(ngcFilePaths)
.then(generatedModules => {
const ngcFilesMap = new Map();
generatedModules.forEach((generatedModule) => {
// Filter out summary json files generated by the compiler.
if (! GENERATED_SUMMARY.test(generatedModule.genFileUrl)) {
const filePath = getMeteorPath(generatedModule.genFileUrl);
ngcFilesMap.set(filePath, generatedModule.source);
}
});
return ngcFilesMap;
})
.then(ngcFilesMap => {
// TODO: make sense to create own instances of the
// metadata and symbol resolvers.
const symbolResolver = compiler._symbolResolver;
const metadataResolver = compiler._metadataResolver;
const symbols = extractProgramSymbols(symbolResolver, filePaths, compilerHost);
const ngModulesMap = extractNgModules(metadataResolver, symbols);
const ngModules = Array.from(ngModulesMap.values());
const bootModule = findBootstrapModule(ngModules);
let bootstrapCode = null;
let mainModulePath = null;
ngModulesMap.forEach((ngModule, symb) => {
if (bootModule === ngModule) {
const path = getMeteorPath(symb.filePath);
bootstrapCode = genBootstrapCode(path);
mainModulePath = path;
}
});
return { ngcFilesMap, bootstrapCode, mainModulePath };
});
}
}