refactor(compiler): split compiler and core (#18683)

After this, neither @angular/compiler nor @angular/comnpiler-cli depend
on @angular/core.

This add a duplication of some interfaces and enums which is stored
in @angular/compiler/src/core.ts

BREAKING CHANGE:
- `@angular/platform-server` now additionally depends on
  `@angular/platform-browser-dynamic` as a peer dependency.


PR Close #18683
This commit is contained in:
Tobias Bosch
2017-08-16 09:00:03 -07:00
committed by Miško Hevery
parent a0ca01d580
commit 0cc77b4a69
107 changed files with 1504 additions and 1564 deletions

View File

@ -0,0 +1,221 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Compiler, CompilerFactory, ComponentFactory, CompilerOptions, ModuleWithComponentFactories, Inject, InjectionToken, Optional, PACKAGE_ROOT_URL, PlatformRef, StaticProvider, TRANSLATIONS, Type, isDevMode, platformCore, ɵConsole as Console, ViewEncapsulation, Injector, NgModuleFactory, TRANSLATIONS_FORMAT, MissingTranslationStrategy,} from '@angular/core';
import {StaticSymbolCache, JitCompiler, ProviderMeta, ExternalReference, I18NHtmlParser, Identifiers, ViewCompiler, CompileMetadataResolver, UrlResolver, TemplateParser, NgModuleCompiler, JitSummaryResolver, SummaryResolver, StyleCompiler, PipeResolver, ElementSchemaRegistry, DomElementSchemaRegistry, ResourceLoader, NgModuleResolver, HtmlParser, CompileReflector, CompilerConfig, DirectiveNormalizer, DirectiveResolver, Lexer, Parser} from '@angular/compiler';
import {JitReflector} from './compiler_reflector';
export const ERROR_COLLECTOR_TOKEN = new InjectionToken('ErrorCollector');
/**
* A default provider for {@link PACKAGE_ROOT_URL} that maps to '/'.
*/
export const DEFAULT_PACKAGE_URL_PROVIDER = {
provide: PACKAGE_ROOT_URL,
useValue: '/'
};
const _NO_RESOURCE_LOADER: ResourceLoader = {
get(url: string): Promise<string>{
throw new Error(
`No ResourceLoader implementation has been provided. Can't read the url "${url}"`);}
};
const baseHtmlParser = new InjectionToken('HtmlParser');
export class CompilerImpl implements Compiler {
private _delegate: JitCompiler;
constructor(
private _injector: Injector, private _metadataResolver: CompileMetadataResolver,
templateParser: TemplateParser, styleCompiler: StyleCompiler, viewCompiler: ViewCompiler,
ngModuleCompiler: NgModuleCompiler, summaryResolver: SummaryResolver<Type<any>>,
compileReflector: CompileReflector, compilerConfig: CompilerConfig, console: Console) {
this._delegate = new JitCompiler(
_metadataResolver, templateParser, styleCompiler, viewCompiler, ngModuleCompiler,
summaryResolver, compileReflector, compilerConfig, console,
this.getExtraNgModuleProviders.bind(this));
}
get injector(): Injector { return this._injector; }
private getExtraNgModuleProviders() {
return [this._metadataResolver.getProviderMetadata(
new ProviderMeta(Compiler, {useValue: this}))];
}
compileModuleSync<T>(moduleType: Type<T>): NgModuleFactory<T> {
return this._delegate.compileModuleSync(moduleType) as NgModuleFactory<T>;
}
compileModuleAsync<T>(moduleType: Type<T>): Promise<NgModuleFactory<T>> {
return this._delegate.compileModuleAsync(moduleType) as Promise<NgModuleFactory<T>>;
}
compileModuleAndAllComponentsSync<T>(moduleType: Type<T>): ModuleWithComponentFactories<T> {
const result = this._delegate.compileModuleAndAllComponentsSync(moduleType);
return {
ngModuleFactory: result.ngModuleFactory as NgModuleFactory<T>,
componentFactories: result.componentFactories as ComponentFactory<any>[],
};
}
compileModuleAndAllComponentsAsync<T>(moduleType: Type<T>):
Promise<ModuleWithComponentFactories<T>> {
return this._delegate.compileModuleAndAllComponentsAsync(moduleType)
.then((result) => ({
ngModuleFactory: result.ngModuleFactory as NgModuleFactory<T>,
componentFactories: result.componentFactories as ComponentFactory<any>[],
}));
}
getNgContentSelectors(component: Type<any>): string[] {
return this._delegate.getNgContentSelectors(component);
}
loadAotSummaries(summaries: () => any[]) { this._delegate.loadAotSummaries(summaries); }
hasAotSummary(ref: Type<any>): boolean { return this._delegate.hasAotSummary(ref); }
getComponentFactory<T>(component: Type<T>): ComponentFactory<T> {
return this._delegate.getComponentFactory(component) as ComponentFactory<T>;
}
clearCache(): void { this._delegate.clearCache(); }
clearCacheFor(type: Type<any>) { this._delegate.clearCacheFor(type); }
}
/**
* A set of providers that provide `JitCompiler` and its dependencies to use for
* template compilation.
*/
export const COMPILER_PROVIDERS = <StaticProvider[]>[
{provide: CompileReflector, useValue: new JitReflector()},
{provide: ResourceLoader, useValue: _NO_RESOURCE_LOADER},
{provide: JitSummaryResolver, deps: []},
{provide: SummaryResolver, useExisting: JitSummaryResolver},
{provide: Console, deps: []},
{provide: Lexer, deps: []},
{provide: Parser, deps: [Lexer]},
{
provide: baseHtmlParser,
useClass: HtmlParser,
deps: [],
},
{
provide: I18NHtmlParser,
useFactory: (parser: HtmlParser, translations: string | null, format: string,
config: CompilerConfig, console: Console) => {
translations = translations || '';
const missingTranslation =
translations ? config.missingTranslation ! : MissingTranslationStrategy.Ignore;
return new I18NHtmlParser(parser, translations, format, missingTranslation, console);
},
deps: [
baseHtmlParser,
[new Optional(), new Inject(TRANSLATIONS)],
[new Optional(), new Inject(TRANSLATIONS_FORMAT)],
[CompilerConfig],
[Console],
]
},
{
provide: HtmlParser,
useExisting: I18NHtmlParser,
},
{
provide: TemplateParser, deps: [CompilerConfig, CompileReflector,
Parser, ElementSchemaRegistry,
I18NHtmlParser, Console]
},
{ provide: DirectiveNormalizer, deps: [ResourceLoader, UrlResolver, HtmlParser, CompilerConfig]},
{ provide: CompileMetadataResolver, deps: [CompilerConfig, NgModuleResolver,
DirectiveResolver, PipeResolver,
SummaryResolver,
ElementSchemaRegistry,
DirectiveNormalizer, Console,
[Optional, StaticSymbolCache],
CompileReflector,
[Optional, ERROR_COLLECTOR_TOKEN]]},
DEFAULT_PACKAGE_URL_PROVIDER,
{ provide: StyleCompiler, deps: [UrlResolver]},
{ provide: ViewCompiler, deps: [CompilerConfig, CompileReflector, ElementSchemaRegistry]},
{ provide: NgModuleCompiler, deps: [CompileReflector] },
{ provide: CompilerConfig, useValue: new CompilerConfig()},
{ provide: Compiler, useClass: CompilerImpl, deps: [Injector, CompileMetadataResolver,
TemplateParser, StyleCompiler,
ViewCompiler, NgModuleCompiler,
SummaryResolver, CompileReflector, CompilerConfig,
Console]},
{ provide: DomElementSchemaRegistry, deps: []},
{ provide: ElementSchemaRegistry, useExisting: DomElementSchemaRegistry},
{ provide: UrlResolver, deps: [PACKAGE_ROOT_URL]},
{ provide: DirectiveResolver, deps: [CompileReflector]},
{ provide: PipeResolver, deps: [CompileReflector]},
{ provide: NgModuleResolver, deps: [CompileReflector]},
];
export class JitCompilerFactory implements CompilerFactory {
private _defaultOptions: CompilerOptions[];
constructor(defaultOptions: CompilerOptions[]) {
const compilerOptions: CompilerOptions = {
useDebug: isDevMode(),
useJit: true,
defaultEncapsulation: ViewEncapsulation.Emulated,
missingTranslation: MissingTranslationStrategy.Warning,
enableLegacyTemplate: true,
preserveWhitespaces: true,
};
this._defaultOptions = [compilerOptions, ...defaultOptions];
}
createCompiler(options: CompilerOptions[] = []): Compiler {
const opts = _mergeOptions(this._defaultOptions.concat(options));
const injector = Injector.create([
COMPILER_PROVIDERS, {
provide: CompilerConfig,
useFactory: () => {
return new CompilerConfig({
// let explicit values from the compiler options overwrite options
// from the app providers
useJit: opts.useJit,
jitDevMode: isDevMode(),
// let explicit values from the compiler options overwrite options
// from the app providers
defaultEncapsulation: opts.defaultEncapsulation,
missingTranslation: opts.missingTranslation,
enableLegacyTemplate: opts.enableLegacyTemplate,
preserveWhitespaces: opts.preserveWhitespaces,
});
},
deps: []
},
opts.providers !
]);
return injector.get(Compiler);
}
}
function _mergeOptions(optionsArr: CompilerOptions[]): CompilerOptions {
return {
useJit: _lastDefined(optionsArr.map(options => options.useJit)),
defaultEncapsulation: _lastDefined(optionsArr.map(options => options.defaultEncapsulation)),
providers: _mergeArrays(optionsArr.map(options => options.providers !)),
missingTranslation: _lastDefined(optionsArr.map(options => options.missingTranslation)),
enableLegacyTemplate: _lastDefined(optionsArr.map(options => options.enableLegacyTemplate)),
preserveWhitespaces: _lastDefined(optionsArr.map(options => options.preserveWhitespaces)),
};
}
function _lastDefined<T>(args: T[]): T|undefined {
for (let i = args.length - 1; i >= 0; i--) {
if (args[i] !== undefined) {
return args[i];
}
}
return undefined;
}
function _mergeArrays(parts: any[][]): any[] {
const result: any[] = [];
parts.forEach((part) => part && result.push(...part));
return result;
}

View File

@ -0,0 +1,149 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CompileReflector, ExternalReference, Identifiers, getUrlScheme, syntaxError} from '@angular/compiler';
import {ANALYZE_FOR_ENTRY_COMPONENTS, ChangeDetectionStrategy, ChangeDetectorRef, Component, ComponentFactory, ComponentFactoryResolver, ComponentRef, ElementRef, Inject, InjectionToken, Injector, LOCALE_ID, NgModuleFactory, NgModuleRef, Optional, PACKAGE_ROOT_URL, PlatformRef, QueryList, Renderer, SecurityContext, StaticProvider, TRANSLATIONS, TRANSLATIONS_FORMAT, TemplateRef, Type, ViewContainerRef, ViewEncapsulation, createPlatformFactory, isDevMode, platformCore, ɵCodegenComponentFactoryResolver, ɵConsole as Console, ɵEMPTY_ARRAY, ɵEMPTY_MAP, ɵReflectionCapabilities as ReflectionCapabilities, ɵand, ɵccf, ɵcmf, ɵcrt, ɵdid, ɵeld, ɵinlineInterpolate, ɵinterpolate, ɵmod, ɵmpd, ɵncd, ɵnov, ɵpad, ɵpid, ɵpod, ɵppd, ɵprd, ɵqud, ɵregisterModuleFactory, ɵstringify as stringify, ɵted, ɵunv, ɵvid} from '@angular/core';
export const MODULE_SUFFIX = '';
const builtinExternalReferences = createBuiltinExternalReferencesMap();
export class JitReflector implements CompileReflector {
private reflectionCapabilities: ReflectionCapabilities;
private builtinExternalReferences = new Map<ExternalReference, any>();
constructor() { this.reflectionCapabilities = new ReflectionCapabilities(); }
componentModuleUrl(type: any, cmpMetadata: Component): string {
const moduleId = cmpMetadata.moduleId;
if (typeof moduleId === 'string') {
const scheme = getUrlScheme(moduleId);
return scheme ? moduleId : `package:${moduleId}${MODULE_SUFFIX}`;
} else if (moduleId !== null && moduleId !== void 0) {
throw syntaxError(
`moduleId should be a string in "${stringify(type)}". See https://goo.gl/wIDDiL for more information.\n` +
`If you're using Webpack you should inline the template and the styles, see https://goo.gl/X2J8zc.`);
}
return `./${stringify(type)}`;
}
parameters(typeOrFunc: /*Type*/ any): any[][] {
return this.reflectionCapabilities.parameters(typeOrFunc);
}
annotations(typeOrFunc: /*Type*/ any): any[] {
return this.reflectionCapabilities.annotations(typeOrFunc);
}
propMetadata(typeOrFunc: /*Type*/ any): {[key: string]: any[]} {
return this.reflectionCapabilities.propMetadata(typeOrFunc);
}
hasLifecycleHook(type: any, lcProperty: string): boolean {
return this.reflectionCapabilities.hasLifecycleHook(type, lcProperty);
}
resolveExternalReference(ref: ExternalReference): any {
return builtinExternalReferences.get(ref) || ref.runtime;
}
}
function createBuiltinExternalReferencesMap() {
const map = new Map<ExternalReference, any>();
map.set(
Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS,
ANALYZE_FOR_ENTRY_COMPONENTS);
map.set(Identifiers.ElementRef, ElementRef);
map.set(Identifiers.NgModuleRef, NgModuleRef);
map.set(Identifiers.ViewContainerRef, ViewContainerRef);
map.set(
Identifiers.ChangeDetectorRef,
ChangeDetectorRef);
map.set(Identifiers.QueryList, QueryList);
map.set(Identifiers.TemplateRef, TemplateRef);
map.set(
Identifiers.CodegenComponentFactoryResolver,
ɵCodegenComponentFactoryResolver);
map.set(
Identifiers.ComponentFactoryResolver,
ComponentFactoryResolver);
map.set(Identifiers.ComponentFactory, ComponentFactory);
map.set(Identifiers.ComponentRef, ComponentRef);
map.set(Identifiers.NgModuleFactory, NgModuleFactory);
map.set(
Identifiers.createModuleFactory,
ɵcmf, );
map.set(
Identifiers.moduleDef,
ɵmod, );
map.set(
Identifiers.moduleProviderDef,
ɵmpd, );
map.set(
Identifiers.RegisterModuleFactoryFn,
ɵregisterModuleFactory, );
map.set(Identifiers.Injector, Injector);
map.set(
Identifiers.ViewEncapsulation,
ViewEncapsulation);
map.set(
Identifiers.ChangeDetectionStrategy,
ChangeDetectionStrategy);
map.set(
Identifiers.SecurityContext,
SecurityContext, );
map.set(Identifiers.LOCALE_ID, LOCALE_ID);
map.set(
Identifiers.TRANSLATIONS_FORMAT,
TRANSLATIONS_FORMAT);
map.set(
Identifiers.inlineInterpolate,
ɵinlineInterpolate);
map.set(Identifiers.interpolate, ɵinterpolate);
map.set(Identifiers.EMPTY_ARRAY, ɵEMPTY_ARRAY);
map.set(Identifiers.EMPTY_MAP, ɵEMPTY_MAP);
map.set(Identifiers.Renderer, Renderer);
map.set(Identifiers.viewDef, ɵvid);
map.set(Identifiers.elementDef, ɵeld);
map.set(Identifiers.anchorDef, ɵand);
map.set(Identifiers.textDef, ɵted);
map.set(Identifiers.directiveDef, ɵdid);
map.set(Identifiers.providerDef, ɵprd);
map.set(Identifiers.queryDef, ɵqud);
map.set(Identifiers.pureArrayDef, ɵpad);
map.set(Identifiers.pureObjectDef, ɵpod);
map.set(Identifiers.purePipeDef, ɵppd);
map.set(Identifiers.pipeDef, ɵpid);
map.set(Identifiers.nodeValue, ɵnov);
map.set(Identifiers.ngContentDef, ɵncd);
map.set(Identifiers.unwrapValue, ɵunv);
map.set(Identifiers.createRendererType2, ɵcrt);
map.set(Identifiers.createComponentFactory, ɵccf);
return map;
}

View File

@ -6,14 +6,16 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ResourceLoader, platformCoreDynamic} from '@angular/compiler';
import {PlatformRef, Provider, StaticProvider, createPlatformFactory} from '@angular/core';
import {ResourceLoader} from '@angular/compiler';
import {CompilerFactory, PlatformRef, Provider, StaticProvider, createPlatformFactory, platformCore} from '@angular/core';
import {platformCoreDynamic} from './platform_core_dynamic';
import {INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS} from './platform_providers';
import {CachedResourceLoader} from './resource_loader/resource_loader_cache';
export * from './private_export';
export {VERSION} from './version';
/**
* @experimental
*/

View File

@ -0,0 +1,20 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {COMPILER_OPTIONS, CompilerFactory, PlatformRef, StaticProvider, createPlatformFactory, platformCore} from '@angular/core';
import {JitCompilerFactory} from './compiler_factory';
/**
* A platform that included corePlatform and the compiler.
*
* @experimental
*/
export const platformCoreDynamic = createPlatformFactory(platformCore, 'coreDynamic', [
{provide: COMPILER_OPTIONS, useValue: {}, multi: true},
{provide: CompilerFactory, useClass: JitCompilerFactory, deps: [COMPILER_OPTIONS]},
]);

View File

@ -6,5 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
export {CompilerImpl as ɵCompilerImpl} from './compiler_factory';
export {platformCoreDynamic as ɵplatformCoreDynamic} from './platform_core_dynamic';
export {INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS as ɵINTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS} from './platform_providers';
export {ResourceLoaderImpl as ɵResourceLoaderImpl} from './resource_loader/resource_loader_impl';