feat(bootstrap): remove the need for explicit reflection setup in bootstrap code

BREAKING CHANGES:

Dart applications and TypeScript applications meant to transpile to Dart must now
import `package:angular2/bootstrap.dart` instead of `package:angular2/angular2.dart`
in their bootstrap code. `package:angular2/angular2.dart` no longer export the
bootstrap function. The transformer rewrites imports of `bootstrap.dart` and calls
to `bootstrap` to `bootstrap_static.dart` and `bootstrapStatic` respectively.
This commit is contained in:
yjbanov
2015-07-22 10:18:04 -07:00
parent 55e8dca8de
commit 3531bb7118
119 changed files with 896 additions and 827 deletions

View File

@ -0,0 +1,21 @@
library angular2.application;
import 'dart:async';
import 'package:angular2/src/reflection/reflection.dart' show reflector;
import 'package:angular2/src/reflection/reflection_capabilities.dart' show ReflectionCapabilities;
import 'application_common.dart';
export 'application_common.dart' show ApplicationRef;
/// Starts an application from a root component. This implementation uses
/// mirrors. Angular 2 transformer automatically replaces this method with a
/// static implementation (see `application_static.dart`) that does not use
/// mirrors and produces a faster and more compact JS code.
///
/// See [commonBootstrap] for detailed documentation.
Future<ApplicationRef> bootstrap(Type appComponentType,
[List componentInjectableBindings, Function errorReporter]) {
reflector.reflectionCapabilities = new ReflectionCapabilities();
return commonBootstrap(appComponentType, componentInjectableBindings, errorReporter);
}

View File

@ -1,372 +1 @@
import {Injector, bind, OpaqueToken, Binding} from 'angular2/di';
import {
NumberWrapper,
Type,
isBlank,
isPresent,
BaseException,
assertionsEnabled,
print,
stringify
} from 'angular2/src/facade/lang';
import {BrowserDomAdapter} from 'angular2/src/dom/browser_adapter';
import {DOM} from 'angular2/src/dom/dom_adapter';
import {Compiler, CompilerCache} from './compiler/compiler';
import {Reflector, reflector} from 'angular2/src/reflection/reflection';
import {
Parser,
Lexer,
ChangeDetection,
DynamicChangeDetection,
JitChangeDetection,
PreGeneratedChangeDetection,
Pipes,
defaultPipes
} from 'angular2/change_detection';
import {ExceptionHandler} from './exception_handler';
import {ViewLoader} from 'angular2/src/render/dom/compiler/view_loader';
import {StyleUrlResolver} from 'angular2/src/render/dom/compiler/style_url_resolver';
import {StyleInliner} from 'angular2/src/render/dom/compiler/style_inliner';
import {ViewResolver} from './compiler/view_resolver';
import {DirectiveResolver} from './compiler/directive_resolver';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle';
import {ShadowDomStrategy} from 'angular2/src/render/dom/shadow_dom/shadow_dom_strategy';
import {
EmulatedUnscopedShadowDomStrategy
} from 'angular2/src/render/dom/shadow_dom/emulated_unscoped_shadow_dom_strategy';
import {XHR} from 'angular2/src/render/xhr';
import {XHRImpl} from 'angular2/src/render/xhr_impl';
import {EventManager, DomEventsPlugin} from 'angular2/src/render/dom/events/event_manager';
import {KeyEventsPlugin} from 'angular2/src/render/dom/events/key_events';
import {HammerGesturesPlugin} from 'angular2/src/render/dom/events/hammer_gestures';
import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
import {UrlResolver} from 'angular2/src/services/url_resolver';
import {AppRootUrl} from 'angular2/src/services/app_root_url';
import {
ComponentRef,
DynamicComponentLoader
} from 'angular2/src/core/compiler/dynamic_component_loader';
import {TestabilityRegistry, Testability} from 'angular2/src/core/testability/testability';
import {AppViewPool, APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/compiler/view_pool';
import {AppViewManager} from 'angular2/src/core/compiler/view_manager';
import {AppViewManagerUtils} from 'angular2/src/core/compiler/view_manager_utils';
import {AppViewListener} from 'angular2/src/core/compiler/view_listener';
import {ProtoViewFactory} from 'angular2/src/core/compiler/proto_view_factory';
import {Renderer, RenderCompiler} from 'angular2/src/render/api';
import {
DomRenderer,
DOCUMENT_TOKEN,
DOM_REFLECT_PROPERTIES_AS_ATTRIBUTES
} from 'angular2/src/render/dom/dom_renderer';
import {DefaultDomCompiler} from 'angular2/src/render/dom/compiler/compiler';
import {internalView} from 'angular2/src/core/compiler/view_ref';
import {appComponentRefPromiseToken, appComponentTypeToken} from './application_tokens';
var _rootInjector: Injector;
// Contains everything that is safe to share between applications.
var _rootBindings = [bind(Reflector).toValue(reflector), TestabilityRegistry];
function _injectorBindings(appComponentType): List<Type | Binding | List<any>> {
var bestChangeDetection: Type = DynamicChangeDetection;
if (PreGeneratedChangeDetection.isSupported()) {
bestChangeDetection = PreGeneratedChangeDetection;
} else if (JitChangeDetection.isSupported()) {
bestChangeDetection = JitChangeDetection;
}
return [
bind(DOCUMENT_TOKEN)
.toValue(DOM.defaultDoc()),
bind(DOM_REFLECT_PROPERTIES_AS_ATTRIBUTES).toValue(false),
bind(appComponentTypeToken).toValue(appComponentType),
bind(appComponentRefPromiseToken)
.toFactory(
(dynamicComponentLoader, injector, testability, registry) => {
// TODO(rado): investigate whether to support bindings on root component.
return dynamicComponentLoader.loadAsRoot(appComponentType, null, injector)
.then((componentRef) => {
registry.registerApplication(componentRef.location.nativeElement, testability);
return componentRef;
});
},
[DynamicComponentLoader, Injector, Testability, TestabilityRegistry]),
bind(appComponentType)
.toFactory((p: Promise<any>) => p.then(ref => ref.instance), [appComponentRefPromiseToken]),
bind(LifeCycle)
.toFactory((exceptionHandler) => new LifeCycle(exceptionHandler, null, assertionsEnabled()),
[ExceptionHandler]),
bind(EventManager)
.toFactory(
(ngZone) => {
var plugins =
[new HammerGesturesPlugin(), new KeyEventsPlugin(), new DomEventsPlugin()];
return new EventManager(plugins, ngZone);
},
[NgZone]),
bind(ShadowDomStrategy)
.toFactory((doc) => new EmulatedUnscopedShadowDomStrategy(doc.head), [DOCUMENT_TOKEN]),
DomRenderer,
DefaultDomCompiler,
bind(Renderer).toAlias(DomRenderer),
bind(RenderCompiler).toAlias(DefaultDomCompiler),
ProtoViewFactory,
AppViewPool,
bind(APP_VIEW_POOL_CAPACITY).toValue(10000),
AppViewManager,
AppViewManagerUtils,
AppViewListener,
Compiler,
CompilerCache,
ViewResolver,
bind(Pipes).toValue(defaultPipes),
bind(ChangeDetection).toClass(bestChangeDetection),
ViewLoader,
DirectiveResolver,
Parser,
Lexer,
ExceptionHandler,
bind(XHR).toValue(new XHRImpl()),
ComponentUrlMapper,
UrlResolver,
StyleUrlResolver,
StyleInliner,
DynamicComponentLoader,
Testability,
AppRootUrl
];
}
function _createNgZone(givenReporter: Function): NgZone {
var defaultErrorReporter = (exception, stackTrace) => {
var longStackTrace = ListWrapper.join(stackTrace, "\n\n-----async gap-----\n");
DOM.logError(`${exception}\n\n${longStackTrace}`);
if (exception instanceof BaseException && isPresent(exception.context)) {
print("Error Context:");
print(exception.context);
}
throw exception;
};
var reporter = isPresent(givenReporter) ? givenReporter : defaultErrorReporter;
var zone = new NgZone({enableLongStackTrace: assertionsEnabled()});
zone.overrideOnErrorHandler(reporter);
return zone;
}
/**
* Bootstrapping for Angular applications.
*
* You instantiate an Angular application by explicitly specifying a component to use as the root
* component for your
* application via the `bootstrap()` method.
*
* ## Simple Example
*
* Assuming this `index.html`:
*
* ```html
* <html>
* <!-- load Angular script tags here. -->
* <body>
* <my-app>loading...</my-app>
* </body>
* </html>
* ```
*
* An application is bootstrapped inside an existing browser DOM, typically `index.html`. Unlike
* Angular 1, Angular 2
* does not compile/process bindings in `index.html`. This is mainly for security reasons, as well
* as architectural
* changes in Angular 2. This means that `index.html` can safely be processed using server-side
* technologies such as
* bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from Angular 2
* component double-curly
* `{{ syntax }}`.
*
* We can use this script code:
*
* ```
* @Component({
* selector: 'my-app'
* })
* @View({
* template: 'Hello {{ name }}!'
* })
* class MyApp {
* name:string;
*
* constructor() {
* this.name = 'World';
* }
* }
*
* main() {
* return bootstrap(MyApp);
* }
* ```
*
* When the app developer invokes `bootstrap()` with the root component `MyApp` as its argument,
* Angular performs the
* following tasks:
*
* 1. It uses the component's `selector` property to locate the DOM element which needs to be
* upgraded into
* the angular component.
* 2. It creates a new child injector (from the platform injector). Optionally, you can also
* override the injector configuration for an app by
* invoking `bootstrap` with the `componentInjectableBindings` argument.
* 3. It creates a new `Zone` and connects it to the angular application's change detection domain
* instance.
* 4. It creates a shadow DOM on the selected component's host element and loads the template into
* it.
* 5. It instantiates the specified component.
* 6. Finally, Angular performs change detection to apply the initial data bindings for the
* application.
*
*
* ## Instantiating Multiple Applications on a Single Page
*
* There are two ways to do this.
*
*
* ### Isolated Applications
*
* Angular creates a new application each time that the `bootstrap()` method is invoked. When
* multiple applications
* are created for a page, Angular treats each application as independent within an isolated change
* detection and
* `Zone` domain. If you need to share data between applications, use the strategy described in the
* next
* section, "Applications That Share Change Detection."
*
*
* ### Applications That Share Change Detection
*
* If you need to bootstrap multiple applications that share common data, the applications must
* share a common
* change detection and zone. To do that, create a meta-component that lists the application
* components in its template.
* By only invoking the `bootstrap()` method once, with the meta-component as its argument, you
* ensure that only a
* single change detection zone is created and therefore data can be shared across the applications.
*
*
* ## Platform Injector
*
* When working within a browser window, there are many singleton resources: cookies, title,
* location, and others.
* Angular services that represent these resources must likewise be shared across all Angular
* applications that
* occupy the same browser window. For this reason, Angular creates exactly one global platform
* injector which stores
* all shared services, and each angular application injector has the platform injector as its
* parent.
*
* Each application has its own private injector as well. When there are multiple applications on a
* page, Angular treats
* each application injector's services as private to that application.
*
*
* # API
* - `appComponentType`: The root component which should act as the application. This is a reference
* to a `Type`
* which is annotated with `@Component(...)`.
* - `componentInjectableBindings`: An additional set of bindings that can be added to the app
* injector
* to override default injection behavior.
* - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter for
* unhandled exceptions.
*
* Returns a `Promise` of {@link ApplicationRef}.
*/
export function bootstrap(appComponentType: Type,
componentInjectableBindings: List<Type | Binding | List<any>> = null,
errorReporter: Function = null): Promise<ApplicationRef> {
BrowserDomAdapter.makeCurrent();
var bootstrapProcess = PromiseWrapper.completer();
var zone = _createNgZone(errorReporter);
zone.run(() => {
// TODO(rado): prepopulate template cache, so applications with only
// index.html and main.js are possible.
var appInjector = _createAppInjector(appComponentType, componentInjectableBindings, zone);
var compRefToken: Promise<any> =
PromiseWrapper.wrap(() => appInjector.get(appComponentRefPromiseToken));
var tick = (componentRef) => {
var appChangeDetector = internalView(componentRef.hostView).changeDetector;
// retrieve life cycle: may have already been created if injected in root component
var lc = appInjector.get(LifeCycle);
lc.registerWith(zone, appChangeDetector);
lc.tick(); // the first tick that will bootstrap the app
bootstrapProcess.resolve(new ApplicationRef(componentRef, appComponentType, appInjector));
};
PromiseWrapper.then(compRefToken, tick,
(err, stackTrace) => bootstrapProcess.reject(err, stackTrace));
});
return bootstrapProcess.promise;
}
/**
* Represents a Angular's representation of an Application.
*
* `ApplicationRef` represents a running application instance. Use it to retrieve the host
* component, injector,
* or dispose of an application.
*/
export class ApplicationRef {
_hostComponent: ComponentRef;
_injector: Injector;
_hostComponentType: Type;
/**
* @private
*/
constructor(hostComponent: ComponentRef, hostComponentType: Type, injector: Injector) {
this._hostComponent = hostComponent;
this._injector = injector;
this._hostComponentType = hostComponentType;
}
/**
* Returns the current {@link Component} type.
*/
get hostComponentType(): Type { return this._hostComponentType; }
/**
* Returns the current {@link Component} instance.
*/
get hostComponent(): any { return this._hostComponent.instance; }
/**
* Dispose (un-load) the application.
*/
dispose(): void {
// TODO: We also need to clean up the Zone, ... here!
this._hostComponent.dispose();
}
/**
* Returns the root application {@link Injector}.
*/
get injector(): Injector { return this._injector; }
}
function _createAppInjector(appComponentType: Type, bindings: List<Type | Binding | List<any>>,
zone: NgZone): Injector {
if (isBlank(_rootInjector)) _rootInjector = Injector.resolveAndCreate(_rootBindings);
var mergedBindings: any[] =
isPresent(bindings) ? ListWrapper.concat(_injectorBindings(appComponentType), bindings) :
_injectorBindings(appComponentType);
mergedBindings.push(bind(NgZone).toValue(zone));
return _rootInjector.resolveAndCreateChild(mergedBindings);
}
export {ApplicationRef, commonBootstrap as bootstrap} from './application_common';

View File

@ -0,0 +1,372 @@
import {Injector, bind, OpaqueToken, Binding} from 'angular2/di';
import {
NumberWrapper,
Type,
isBlank,
isPresent,
BaseException,
assertionsEnabled,
print,
stringify
} from 'angular2/src/facade/lang';
import {BrowserDomAdapter} from 'angular2/src/dom/browser_adapter';
import {DOM} from 'angular2/src/dom/dom_adapter';
import {Compiler, CompilerCache} from './compiler/compiler';
import {Reflector, reflector} from 'angular2/src/reflection/reflection';
import {
Parser,
Lexer,
ChangeDetection,
DynamicChangeDetection,
JitChangeDetection,
PreGeneratedChangeDetection,
Pipes,
defaultPipes
} from 'angular2/change_detection';
import {ExceptionHandler} from './exception_handler';
import {ViewLoader} from 'angular2/src/render/dom/compiler/view_loader';
import {StyleUrlResolver} from 'angular2/src/render/dom/compiler/style_url_resolver';
import {StyleInliner} from 'angular2/src/render/dom/compiler/style_inliner';
import {ViewResolver} from './compiler/view_resolver';
import {DirectiveResolver} from './compiler/directive_resolver';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle';
import {ShadowDomStrategy} from 'angular2/src/render/dom/shadow_dom/shadow_dom_strategy';
import {
EmulatedUnscopedShadowDomStrategy
} from 'angular2/src/render/dom/shadow_dom/emulated_unscoped_shadow_dom_strategy';
import {XHR} from 'angular2/src/render/xhr';
import {XHRImpl} from 'angular2/src/render/xhr_impl';
import {EventManager, DomEventsPlugin} from 'angular2/src/render/dom/events/event_manager';
import {KeyEventsPlugin} from 'angular2/src/render/dom/events/key_events';
import {HammerGesturesPlugin} from 'angular2/src/render/dom/events/hammer_gestures';
import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
import {UrlResolver} from 'angular2/src/services/url_resolver';
import {AppRootUrl} from 'angular2/src/services/app_root_url';
import {
ComponentRef,
DynamicComponentLoader
} from 'angular2/src/core/compiler/dynamic_component_loader';
import {TestabilityRegistry, Testability} from 'angular2/src/core/testability/testability';
import {AppViewPool, APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/compiler/view_pool';
import {AppViewManager} from 'angular2/src/core/compiler/view_manager';
import {AppViewManagerUtils} from 'angular2/src/core/compiler/view_manager_utils';
import {AppViewListener} from 'angular2/src/core/compiler/view_listener';
import {ProtoViewFactory} from 'angular2/src/core/compiler/proto_view_factory';
import {Renderer, RenderCompiler} from 'angular2/src/render/api';
import {
DomRenderer,
DOCUMENT_TOKEN,
DOM_REFLECT_PROPERTIES_AS_ATTRIBUTES
} from 'angular2/src/render/dom/dom_renderer';
import {DefaultDomCompiler} from 'angular2/src/render/dom/compiler/compiler';
import {internalView} from 'angular2/src/core/compiler/view_ref';
import {appComponentRefPromiseToken, appComponentTypeToken} from './application_tokens';
var _rootInjector: Injector;
// Contains everything that is safe to share between applications.
var _rootBindings = [bind(Reflector).toValue(reflector), TestabilityRegistry];
function _injectorBindings(appComponentType): List<Type | Binding | List<any>> {
var bestChangeDetection: Type = DynamicChangeDetection;
if (PreGeneratedChangeDetection.isSupported()) {
bestChangeDetection = PreGeneratedChangeDetection;
} else if (JitChangeDetection.isSupported()) {
bestChangeDetection = JitChangeDetection;
}
return [
bind(DOCUMENT_TOKEN)
.toValue(DOM.defaultDoc()),
bind(DOM_REFLECT_PROPERTIES_AS_ATTRIBUTES).toValue(false),
bind(appComponentTypeToken).toValue(appComponentType),
bind(appComponentRefPromiseToken)
.toFactory(
(dynamicComponentLoader, injector, testability, registry) => {
// TODO(rado): investigate whether to support bindings on root component.
return dynamicComponentLoader.loadAsRoot(appComponentType, null, injector)
.then((componentRef) => {
registry.registerApplication(componentRef.location.nativeElement, testability);
return componentRef;
});
},
[DynamicComponentLoader, Injector, Testability, TestabilityRegistry]),
bind(appComponentType)
.toFactory((p: Promise<any>) => p.then(ref => ref.instance), [appComponentRefPromiseToken]),
bind(LifeCycle)
.toFactory((exceptionHandler) => new LifeCycle(exceptionHandler, null, assertionsEnabled()),
[ExceptionHandler]),
bind(EventManager)
.toFactory(
(ngZone) => {
var plugins =
[new HammerGesturesPlugin(), new KeyEventsPlugin(), new DomEventsPlugin()];
return new EventManager(plugins, ngZone);
},
[NgZone]),
bind(ShadowDomStrategy)
.toFactory((doc) => new EmulatedUnscopedShadowDomStrategy(doc.head), [DOCUMENT_TOKEN]),
DomRenderer,
DefaultDomCompiler,
bind(Renderer).toAlias(DomRenderer),
bind(RenderCompiler).toAlias(DefaultDomCompiler),
ProtoViewFactory,
AppViewPool,
bind(APP_VIEW_POOL_CAPACITY).toValue(10000),
AppViewManager,
AppViewManagerUtils,
AppViewListener,
Compiler,
CompilerCache,
ViewResolver,
bind(Pipes).toValue(defaultPipes),
bind(ChangeDetection).toClass(bestChangeDetection),
ViewLoader,
DirectiveResolver,
Parser,
Lexer,
ExceptionHandler,
bind(XHR).toValue(new XHRImpl()),
ComponentUrlMapper,
UrlResolver,
StyleUrlResolver,
StyleInliner,
DynamicComponentLoader,
Testability,
AppRootUrl
];
}
function _createNgZone(givenReporter: Function): NgZone {
var defaultErrorReporter = (exception, stackTrace) => {
var longStackTrace = ListWrapper.join(stackTrace, "\n\n-----async gap-----\n");
DOM.logError(`${exception}\n\n${longStackTrace}`);
if (exception instanceof BaseException && isPresent(exception.context)) {
print("Error Context:");
print(exception.context);
}
throw exception;
};
var reporter = isPresent(givenReporter) ? givenReporter : defaultErrorReporter;
var zone = new NgZone({enableLongStackTrace: assertionsEnabled()});
zone.overrideOnErrorHandler(reporter);
return zone;
}
/**
* Bootstrapping for Angular applications.
*
* You instantiate an Angular application by explicitly specifying a component to use as the root
* component for your
* application via the `bootstrap()` method.
*
* ## Simple Example
*
* Assuming this `index.html`:
*
* ```html
* <html>
* <!-- load Angular script tags here. -->
* <body>
* <my-app>loading...</my-app>
* </body>
* </html>
* ```
*
* An application is bootstrapped inside an existing browser DOM, typically `index.html`. Unlike
* Angular 1, Angular 2
* does not compile/process bindings in `index.html`. This is mainly for security reasons, as well
* as architectural
* changes in Angular 2. This means that `index.html` can safely be processed using server-side
* technologies such as
* bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from Angular 2
* component double-curly
* `{{ syntax }}`.
*
* We can use this script code:
*
* ```
* @Component({
* selector: 'my-app'
* })
* @View({
* template: 'Hello {{ name }}!'
* })
* class MyApp {
* name:string;
*
* constructor() {
* this.name = 'World';
* }
* }
*
* main() {
* return bootstrap(MyApp);
* }
* ```
*
* When the app developer invokes `bootstrap()` with the root component `MyApp` as its argument,
* Angular performs the
* following tasks:
*
* 1. It uses the component's `selector` property to locate the DOM element which needs to be
* upgraded into
* the angular component.
* 2. It creates a new child injector (from the platform injector). Optionally, you can also
* override the injector configuration for an app by
* invoking `bootstrap` with the `componentInjectableBindings` argument.
* 3. It creates a new `Zone` and connects it to the angular application's change detection domain
* instance.
* 4. It creates a shadow DOM on the selected component's host element and loads the template into
* it.
* 5. It instantiates the specified component.
* 6. Finally, Angular performs change detection to apply the initial data bindings for the
* application.
*
*
* ## Instantiating Multiple Applications on a Single Page
*
* There are two ways to do this.
*
*
* ### Isolated Applications
*
* Angular creates a new application each time that the `bootstrap()` method is invoked. When
* multiple applications
* are created for a page, Angular treats each application as independent within an isolated change
* detection and
* `Zone` domain. If you need to share data between applications, use the strategy described in the
* next
* section, "Applications That Share Change Detection."
*
*
* ### Applications That Share Change Detection
*
* If you need to bootstrap multiple applications that share common data, the applications must
* share a common
* change detection and zone. To do that, create a meta-component that lists the application
* components in its template.
* By only invoking the `bootstrap()` method once, with the meta-component as its argument, you
* ensure that only a
* single change detection zone is created and therefore data can be shared across the applications.
*
*
* ## Platform Injector
*
* When working within a browser window, there are many singleton resources: cookies, title,
* location, and others.
* Angular services that represent these resources must likewise be shared across all Angular
* applications that
* occupy the same browser window. For this reason, Angular creates exactly one global platform
* injector which stores
* all shared services, and each angular application injector has the platform injector as its
* parent.
*
* Each application has its own private injector as well. When there are multiple applications on a
* page, Angular treats
* each application injector's services as private to that application.
*
*
* # API
* - `appComponentType`: The root component which should act as the application. This is a reference
* to a `Type`
* which is annotated with `@Component(...)`.
* - `componentInjectableBindings`: An additional set of bindings that can be added to the app
* injector
* to override default injection behavior.
* - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter for
* unhandled exceptions.
*
* Returns a `Promise` of {@link ApplicationRef}.
*/
export function commonBootstrap(
appComponentType: Type, componentInjectableBindings: List<Type | Binding | List<any>> = null,
errorReporter: Function = null): Promise<ApplicationRef> {
BrowserDomAdapter.makeCurrent();
var bootstrapProcess = PromiseWrapper.completer();
var zone = _createNgZone(errorReporter);
zone.run(() => {
// TODO(rado): prepopulate template cache, so applications with only
// index.html and main.js are possible.
var appInjector = _createAppInjector(appComponentType, componentInjectableBindings, zone);
var compRefToken: Promise<any> =
PromiseWrapper.wrap(() => appInjector.get(appComponentRefPromiseToken));
var tick = (componentRef) => {
var appChangeDetector = internalView(componentRef.hostView).changeDetector;
// retrieve life cycle: may have already been created if injected in root component
var lc = appInjector.get(LifeCycle);
lc.registerWith(zone, appChangeDetector);
lc.tick(); // the first tick that will bootstrap the app
bootstrapProcess.resolve(new ApplicationRef(componentRef, appComponentType, appInjector));
};
PromiseWrapper.then(compRefToken, tick,
(err, stackTrace) => bootstrapProcess.reject(err, stackTrace));
});
return bootstrapProcess.promise;
}
/**
* Represents a Angular's representation of an Application.
*
* `ApplicationRef` represents a running application instance. Use it to retrieve the host
* component, injector,
* or dispose of an application.
*/
export class ApplicationRef {
_hostComponent: ComponentRef;
_injector: Injector;
_hostComponentType: Type;
/**
* @private
*/
constructor(hostComponent: ComponentRef, hostComponentType: Type, injector: Injector) {
this._hostComponent = hostComponent;
this._injector = injector;
this._hostComponentType = hostComponentType;
}
/**
* Returns the current {@link Component} type.
*/
get hostComponentType(): Type { return this._hostComponentType; }
/**
* Returns the current {@link Component} instance.
*/
get hostComponent(): any { return this._hostComponent.instance; }
/**
* Dispose (un-load) the application.
*/
dispose(): void {
// TODO: We also need to clean up the Zone, ... here!
this._hostComponent.dispose();
}
/**
* Returns the root application {@link Injector}.
*/
get injector(): Injector { return this._injector; }
}
function _createAppInjector(appComponentType: Type, bindings: List<Type | Binding | List<any>>,
zone: NgZone): Injector {
if (isBlank(_rootInjector)) _rootInjector = Injector.resolveAndCreate(_rootBindings);
var mergedBindings: any[] =
isPresent(bindings) ? ListWrapper.concat(_injectorBindings(appComponentType), bindings) :
_injectorBindings(appComponentType);
mergedBindings.push(bind(NgZone).toValue(zone));
return _rootInjector.resolveAndCreateChild(mergedBindings);
}

View File

@ -0,0 +1,14 @@
library angular2.application_static;
import 'dart:async';
import 'application_common.dart';
/// Starts an application from a root component.
///
/// See [commonBootstrap] for detailed documentation.
Future<ApplicationRef> bootstrapStatic(
Type appComponentType,
[List componentInjectableBindings,
Function errorReporter]) {
return commonBootstrap(appComponentType, componentInjectableBindings, errorReporter);
}

View File

@ -1,13 +1,6 @@
import {Directive} from 'angular2/annotations';
import {
ViewContainerRef,
ViewRef,
TemplateRef,
Pipes,
LifecycleEvent,
Pipe,
ChangeDetectorRef
} from 'angular2/angular2';
import {Directive, LifecycleEvent} from 'angular2/annotations';
import {ViewContainerRef, ViewRef, TemplateRef} from 'angular2/core';
import {ChangeDetectorRef, Pipe, Pipes} from 'angular2/change_detection';
import {isPresent, isBlank} from 'angular2/src/facade/lang';
/**

View File

@ -1,4 +1,4 @@
import {Directive, LifecycleEvent} from 'angular2/angular2';
import {Directive, LifecycleEvent} from 'angular2/annotations';
import {Inject, Ancestor, forwardRef, Binding} from 'angular2/di';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {CONST_EXPR} from 'angular2/src/facade/lang';

View File

@ -2,7 +2,8 @@ import {CONST_EXPR} from 'angular2/src/facade/lang';
import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {List, StringMap} from 'angular2/src/facade/collection';
import {Directive, LifecycleEvent, Query, QueryList} from 'angular2/angular2';
import {QueryList} from 'angular2/core';
import {Query, Directive, LifecycleEvent} from 'angular2/annotations';
import {forwardRef, Ancestor, Binding, Inject} from 'angular2/di';
import {ControlContainer} from './control_container';

View File

@ -1,7 +1,8 @@
import {CONST_EXPR} from 'angular2/src/facade/lang';
import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {Directive, LifecycleEvent, Query, QueryList} from 'angular2/angular2';
import {QueryList} from 'angular2/core';
import {Query, Directive, LifecycleEvent} from 'angular2/annotations';
import {forwardRef, Ancestor, Binding} from 'angular2/di';
import {NgControl} from './ng_control';

View File

@ -2,7 +2,7 @@ import {CONST_EXPR} from 'angular2/src/facade/lang';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {ObservableWrapper, EventEmitter} from 'angular2/src/facade/async';
import {Directive, LifecycleEvent} from 'angular2/angular2';
import {Directive, LifecycleEvent} from 'angular2/annotations';
import {forwardRef, Binding} from 'angular2/di';
import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group';

View File

@ -1,7 +1,8 @@
import {CONST_EXPR} from 'angular2/src/facade/lang';
import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {Directive, LifecycleEvent, QueryList, Query} from 'angular2/angular2';
import {QueryList} from 'angular2/core';
import {Query, Directive, LifecycleEvent} from 'angular2/annotations';
import {forwardRef, Ancestor, Binding} from 'angular2/di';
import {NgControl} from './ng_control';

View File

@ -1,5 +1,6 @@
import {Renderer} from 'angular2/render';
import {ElementRef, QueryList, Directive, Query} from 'angular2/angular2';
import {ElementRef, QueryList} from 'angular2/core';
import {Query, Directive} from 'angular2/annotations';
import {NgControl} from './ng_control';
import {ControlValueAccessor} from './control_value_accessor';

View File

@ -84,7 +84,7 @@ function _getAppBindings() {
// The document is only available in browser environment
try {
appDoc = DOM.defaultDoc();
appDoc = DOM.createHtmlDocument();
} catch (e) {
appDoc = null;
}

View File

@ -14,6 +14,7 @@ const INJECTABLES = const [
'Injectable', 'package:angular2/src/di/decorators.dart'),
const ClassDescriptor('Injectable', 'package:angular2/di.dart'),
const ClassDescriptor('Injectable', 'package:angular2/angular2.dart'),
const ClassDescriptor('Injectable', 'package:angular2/bootstrap_static.dart'),
];
const DIRECTIVES = const [
@ -32,6 +33,8 @@ const DIRECTIVES = const [
superClass: 'Injectable'),
const ClassDescriptor('Directive', 'package:angular2/core.dart',
superClass: 'Injectable'),
const ClassDescriptor('Directive', 'package:angular2/bootstrap_static.dart',
superClass: 'Injectable'),
];
const COMPONENTS = const [
@ -48,6 +51,8 @@ const COMPONENTS = const [
superClass: 'Directive'),
const ClassDescriptor('Component', 'package:angular2/angular2.dart',
superClass: 'Directive'),
const ClassDescriptor('Component', 'package:angular2/bootstrap_static.dart',
superClass: 'Directive'),
const ClassDescriptor('Component', 'package:angular2/core.dart',
superClass: 'Directive'),
];
@ -55,6 +60,7 @@ const COMPONENTS = const [
const VIEWS = const [
const ClassDescriptor('View', 'package:angular2/view.dart'),
const ClassDescriptor('View', 'package:angular2/angular2.dart'),
const ClassDescriptor('View', 'package:angular2/bootstrap_static.dart'),
const ClassDescriptor('View', 'package:angular2/core.dart'),
const ClassDescriptor(
'View', 'package:angular2/src/core/annotations/view.dart'),
@ -75,24 +81,29 @@ class AnnotationMatcher extends ClassMatcherBase {
..addAll(VIEWS));
}
bool _implementsWithWarning(
ClassDescriptor descriptor, List<ClassDescriptor> interfaces) =>
implements(descriptor, interfaces,
bool _implementsWithWarning(Annotation annotation, AssetId assetId,
List<ClassDescriptor> interfaces) {
ClassDescriptor descriptor = firstMatch(annotation.name, assetId);
if (descriptor == null) {
throw 'Unable to locate descriptor for ${annotation.name} in ${assetId}';
}
return implements(descriptor, interfaces,
missingSuperClassWarning: 'Missing `custom_annotation` entry for `${descriptor.superClass}`.');
}
/// Checks if an [Annotation] node implements [Injectable].
bool isInjectable(Annotation annotation, AssetId assetId) =>
_implementsWithWarning(firstMatch(annotation.name, assetId), INJECTABLES);
_implementsWithWarning(annotation, assetId, INJECTABLES);
/// Checks if an [Annotation] node implements [Directive].
bool isDirective(Annotation annotation, AssetId assetId) =>
_implementsWithWarning(firstMatch(annotation.name, assetId), DIRECTIVES);
_implementsWithWarning(annotation, assetId, DIRECTIVES);
/// Checks if an [Annotation] node implements [Component].
bool isComponent(Annotation annotation, AssetId assetId) =>
_implementsWithWarning(firstMatch(annotation.name, assetId), COMPONENTS);
_implementsWithWarning(annotation, assetId, COMPONENTS);
/// Checks if an [Annotation] node implements [View].
bool isView(Annotation annotation, AssetId assetId) =>
_implementsWithWarning(firstMatch(annotation.name, assetId), VIEWS);
_implementsWithWarning(annotation, assetId, VIEWS);
}

View File

@ -1,5 +1,6 @@
library angular2.transform.common.names;
const BOOTSTRAP_NAME = 'bootstrap';
const SETUP_METHOD_NAME = 'initReflector';
const REFLECTOR_VAR_NAME = 'reflector';
const TRANSFORM_DYNAMIC_MODE = 'transform_dynamic';

View File

@ -15,6 +15,10 @@ class AstTester {
bool isReflectionCapabilitiesImport(ImportDirective node) {
return node.uri.stringValue.endsWith("reflection_capabilities.dart");
}
bool isBootstrapImport(ImportDirective node) {
return node.uri.stringValue.endsWith("/bootstrap.dart");
}
}
/// An object that checks for {@link ReflectionCapabilities} using a fully resolved
@ -32,4 +36,8 @@ class ResolvedTester implements AstTester {
bool isReflectionCapabilitiesImport(ImportDirective node) {
return node.uriElement == _forbiddenClass.library;
}
bool isBootstrapImport(ImportDirective node) {
throw 'Not implemented';
}
}

View File

@ -1,6 +1,5 @@
library angular2.transform.reflection_remover.codegen;
import 'package:analyzer/src/generated/ast.dart';
import 'package:path/path.dart' as path;
import 'package:angular2/src/transform/common/names.dart';
@ -36,45 +35,10 @@ class Codegen {
/// Generates code to call the method which sets up Angular2 reflection
/// statically.
///
/// If `reflectorAssignment` is provided, it is expected to be the node
/// representing the {@link ReflectionCapabilities} assignment, and we will
/// attempt to parse the access of `reflector` from it so that `reflector` is
/// properly prefixed if necessary.
String codegenSetupReflectionCall(
{AssignmentExpression reflectorAssignment}) {
var reflectorExpression = null;
if (reflectorAssignment != null) {
reflectorExpression = reflectorAssignment.accept(new _ReflectorVisitor());
}
if (reflectorExpression == null) {
reflectorExpression = 'reflector';
}
String codegenSetupReflectionCall() {
var count = 0;
return importUris
.map((_) => '${prefix}${count++}.${SETUP_METHOD_NAME}();')
.join('');
}
}
/// A visitor whose job it is to find the access of `reflector`.
class _ReflectorVisitor extends Object with SimpleAstVisitor<Expression> {
@override
Expression visitAssignmentExpression(AssignmentExpression node) {
if (node == null || node.leftHandSide == null) return null;
return node.leftHandSide.accept(this);
}
@override
Expression visitPropertyAccess(PropertyAccess node) {
if (node == null || node.target == null) return null;
return node.target;
}
@override
Expression visitPrefixedIdentifier(PrefixedIdentifier node) {
if (node == null || node.prefix == null) return null;
return node.prefix;
}
}

View File

@ -32,96 +32,11 @@ class Rewriter {
String rewrite(CompilationUnit node) {
if (node == null) throw new ArgumentError.notNull('node');
var visitor = new _FindReflectionCapabilitiesVisitor(_tester);
var visitor = new _RewriterVisitor(this);
node.accept(visitor);
if (visitor.reflectionCapabilityImports.isEmpty) {
logger.error('Failed to find ${REFLECTION_CAPABILITIES_NAME} import.');
return _code;
}
if (visitor.reflectionCapabilityAssignments.isEmpty) {
logger.error('Failed to find ${REFLECTION_CAPABILITIES_NAME} '
'instantiation.');
return _code;
}
var compare = (AstNode a, AstNode b) => a.offset - b.offset;
visitor.reflectionCapabilityImports.sort(compare);
visitor.reflectionCapabilityAssignments.sort(compare);
var importAdded = false;
var buf = new StringBuffer();
var idx = visitor.reflectionCapabilityImports.fold(0,
(int lastIdx, ImportDirective node) {
buf.write(_code.substring(lastIdx, node.offset));
if ('${node.prefix}' == _codegen.prefix) {
logger.warning(
'Found import prefix "${_codegen.prefix}" in source file.'
' Transform may not succeed.');
}
if (_mirrorMode != MirrorMode.none) {
buf.write(_importDebugReflectionCapabilities(node));
} else {
buf.write(_commentedNode(node));
}
if (!importAdded && _writeStaticInit) {
buf.write(_codegen.codegenImport());
importAdded = true;
}
return node.end;
});
var setupAdded = false;
idx = visitor.reflectionCapabilityAssignments.fold(idx,
(int lastIdx, AssignmentExpression assignNode) {
var node = assignNode;
while (node.parent is ExpressionStatement) {
node = node.parent;
}
buf.write(_code.substring(lastIdx, node.offset));
switch (_mirrorMode) {
case MirrorMode.debug:
buf.write(node);
break;
case MirrorMode.verbose:
buf.write(_instantiateVerboseReflectionCapabilities(assignNode));
break;
case MirrorMode.none:
default:
buf.write(_commentedNode(node));
break;
}
if (!setupAdded && _writeStaticInit) {
buf.write(_codegen.codegenSetupReflectionCall(
reflectorAssignment: assignNode));
setupAdded = true;
}
return node.end;
});
if (idx < _code.length) buf.write(_code.substring(idx));
return buf.toString();
}
String _instantiateVerboseReflectionCapabilities(
AssignmentExpression assignNode) {
if (assignNode.rightHandSide is! InstanceCreationExpression) {
return '$assignNode;';
}
var rhs = (assignNode.rightHandSide as InstanceCreationExpression);
return '${assignNode.leftHandSide} ${assignNode.operator} '
'new ${rhs.constructorName}(verbose: true);';
}
String _importDebugReflectionCapabilities(ImportDirective node) {
var uri = '${node.uri}';
uri = path
.join(path.dirname(uri), 'debug_${path.basename(uri)}')
.replaceAll('\\', '/');
var asClause = node.prefix != null ? ' as ${node.prefix}' : '';
return 'import $uri$asClause;';
}
String _commentedNode(AstNode node) {
return '/*${_code.substring(node.offset, node.end)}*/';
return visitor.outputRewrittenCode();
}
}
@ -130,18 +45,31 @@ class Rewriter {
///
/// This breaks our dependency on dart:mirrors, which enables smaller code
/// size and better performance.
class _FindReflectionCapabilitiesVisitor extends Object
class _RewriterVisitor extends Object
with RecursiveAstVisitor<Object> {
final reflectionCapabilityImports = new List<ImportDirective>();
final reflectionCapabilityAssignments = new List<AssignmentExpression>();
final AstTester _tester;
final Rewriter _rewriter;
final buf = new StringBuffer();
final reflectionCapabilityAssignments = [];
_FindReflectionCapabilitiesVisitor(this._tester);
int _currentIndex = 0;
bool _setupAdded = false;
bool _importAdded = false;
_RewriterVisitor(this._rewriter);
@override
Object visitImportDirective(ImportDirective node) {
if (_tester.isReflectionCapabilitiesImport(node)) {
reflectionCapabilityImports.add(node);
buf.write(_rewriter._code.substring(_currentIndex, node.offset));
_currentIndex = node.offset;
if (_rewriter._tester.isReflectionCapabilitiesImport(node)) {
_rewriteReflectionCapabilitiesImport(node);
} else if (_rewriter._tester.isBootstrapImport(node)) {
_rewriteBootstrapImportToStatic(node);
}
if (!_importAdded && _rewriter._writeStaticInit) {
// Add imports for ng_deps (once)
buf.write(_rewriter._codegen.codegenImport());
_importAdded = true;
}
return null;
}
@ -149,19 +77,130 @@ class _FindReflectionCapabilitiesVisitor extends Object
@override
Object visitAssignmentExpression(AssignmentExpression node) {
if (node.rightHandSide is InstanceCreationExpression &&
_tester.isNewReflectionCapabilities(node.rightHandSide)) {
_rewriter._tester.isNewReflectionCapabilities(node.rightHandSide)) {
reflectionCapabilityAssignments.add(node);
_rewriteReflectionCapabilitiesAssignment(node);
}
return super.visitAssignmentExpression(node);
}
@override
Object visitInstanceCreationExpression(InstanceCreationExpression node) {
if (_tester.isNewReflectionCapabilities(node) &&
if (_rewriter._tester.isNewReflectionCapabilities(node) &&
!reflectionCapabilityAssignments.contains(node.parent)) {
logger.error('Unexpected format in creation of '
'${REFLECTION_CAPABILITIES_NAME}');
}
return super.visitInstanceCreationExpression(node);
}
@override
Object visitMethodInvocation(MethodInvocation node) {
if (node.methodName.toString() == BOOTSTRAP_NAME) {
_rewriteBootstrapCallToStatic(node);
}
return super.visitMethodInvocation(node);
}
String outputRewrittenCode() {
if (_currentIndex < _rewriter._code.length) {
buf.write(_rewriter._code.substring(_currentIndex));
}
return '$buf';
}
_rewriteBootstrapImportToStatic(ImportDirective node) {
if (_rewriter._writeStaticInit) {
// rewrite `bootstrap.dart` to `bootstrap_static.dart`
buf.write(_rewriter._code.substring(_currentIndex, node.offset));
// TODO(yjbanov): handle import "..." show/hide ...
buf.write("import 'package:angular2/bootstrap_static.dart';");
} else {
// leave it as is
buf.write(_rewriter._code.substring(_currentIndex, node.end));
}
_currentIndex = node.end;
}
_rewriteBootstrapCallToStatic(MethodInvocation node) {
if (_rewriter._writeStaticInit) {
buf.write(_rewriter._code.substring(_currentIndex, node.offset));
_writeStaticReflectorInitOnce();
// rewrite `bootstrap(...)` to `bootstrapStatic(...)`
buf.write('bootstrapStatic${node.argumentList}');
} else {
// leave it as is
buf.write(_rewriter._code.substring(_currentIndex, node.end));
}
_currentIndex = node.end;
}
_writeStaticReflectorInitOnce() {
if (!_setupAdded) {
buf.write(_rewriter._codegen.codegenSetupReflectionCall());
_setupAdded = true;
}
}
_rewriteReflectionCapabilitiesImport(ImportDirective node) {
buf.write(_rewriter._code.substring(_currentIndex, node.offset));
if ('${node.prefix}' == _rewriter._codegen.prefix) {
logger.warning(
'Found import prefix "${_rewriter._codegen.prefix}" in source file.'
' Transform may not succeed.');
}
if (_rewriter._mirrorMode != MirrorMode.none) {
buf.write(_importDebugReflectionCapabilities(node));
} else {
buf.write(_commentedNode(node));
}
_currentIndex = node.end;
}
_rewriteReflectionCapabilitiesAssignment(AssignmentExpression assignNode) {
var node = assignNode;
while (node.parent is ExpressionStatement) {
node = node.parent;
}
buf.write(_rewriter._code.substring(_currentIndex, node.offset));
if (_rewriter._writeStaticInit) {
_writeStaticReflectorInitOnce();
}
switch (_rewriter._mirrorMode) {
case MirrorMode.debug:
buf.write(node);
break;
case MirrorMode.verbose:
buf.write(_instantiateVerboseReflectionCapabilities(assignNode));
break;
case MirrorMode.none:
default:
buf.write(_commentedNode(node));
break;
}
_currentIndex = node.end;
}
String _commentedNode(AstNode node) {
return '/*${_rewriter._code.substring(node.offset, node.end)}*/';
}
}
String _importDebugReflectionCapabilities(ImportDirective node) {
var uri = '${node.uri}';
uri = path
.join(path.dirname(uri), 'debug_${path.basename(uri)}')
.replaceAll('\\', '/');
var asClause = node.prefix != null ? ' as ${node.prefix}' : '';
return 'import $uri$asClause;';
}
String _instantiateVerboseReflectionCapabilities(
AssignmentExpression assignNode) {
if (assignNode.rightHandSide is! InstanceCreationExpression) {
return '$assignNode;';
}
var rhs = (assignNode.rightHandSide as InstanceCreationExpression);
return '${assignNode.leftHandSide} ${assignNode.operator} '
'new ${rhs.constructorName}(verbose: true);';
}